gpt4 book ai didi

Java : divide the screen

转载 作者:行者123 更新时间:2023-12-02 15:29:50 27 4
gpt4 key购买 nike

我尝试做一个简单的 Swing 窗,但布局并不容易...我的意思是我只想要一个有 3 个面板的窗口:

  • 标题占窗口高度的 20%
  • 内容占窗口高度的 60%
  • 页脚占窗口高度的 20%

但我无法成功拥有我想要的东西。我使用了 gridLayout(3,1) 但无法指定高度。

public class Window extends JFrame implements Serializable  {
private JPanel _header;
private JPanel _content;
private JPanel _footer;

public Window() {
GridLayout grid = new GridLayout(3,1);
setLayout(grid);

_header = new JPanel();
_header.setBackground(Color.GRAY);
getContentPane().add(_header);

_content = new JPanel();
JScrollPane jsp = new JScrollPane(_content, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(jsp);

_footer = new JPanel();
_footer.setBackground(Color.GRAY);
getContentPane().add(_footer);
pack();
validate();

setTitle("Chat client");
setVisible(true);
setSize(500, 500);
setLocationRelativeTo(null);
}

你能帮帮我吗?最好的问候

最佳答案

GridBagLayout 能够按比例划分垂直或水平空间。

这是一个示例,它在窗口的前 20% 处显示一个红色的 JPanel,在中间的 60% 处显示一个绿色的 JPanel,在窗口的中间 60% 处显示一个蓝色的 JPanel 在后 20% 中:

    JFrame window = new JFrame();

window.setLayout(new GridBagLayout());

JPanel top = new JPanel(), middle = new JPanel(), bottom = new JPanel();
top.setBackground(Color.red);
middle.setBackground(Color.green);
bottom.setBackground(Color.blue);

GridBagConstraints c = new GridBagConstraints();
// we want the layout to stretch the components in both directions
c.fill = GridBagConstraints.BOTH;
// if the total X weight is 0, then it won't stretch horizontally.
// It doesn't matter what the weight actually is, as long as it's not 0,
// because the grid is only one component wide
c.weightx = 1;

// Vertical space is divided in proportion to the Y weights of the components
c.weighty = 0.2;
c.gridy = 0;
window.add(top, c);
// It's fine to reuse the constraints object; add makes a copy.
c.weighty = 0.6;
c.gridy = 1;
window.add(middle, c);
c.weighty = 0.2;
c.gridy = 2;
window.add(bottom, c);


window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);

结果:

enter image description here

关于Java : divide the screen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28425321/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com