Java:分割屏幕

zed*_*d13 3 java layout swing grid-layout

我尝试做一个简单的摆动窗口,但布局并不容易......我的意思是我只想要一个带有 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);
}
Run Code Online (Sandbox Code Playgroud)

你能帮助我吗 ?此致

use*_*751 5

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

下面的示例JPanel在窗口的顶部 20% 中显示红色,在中间 60% 中显示绿色,在底部 20% 中JPanel显示蓝色:JPanel

    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);
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述