Java GridBagLayout 不水平填充框架

Java GridBagLayout does not fill frame horizontally

我正在为聊天程序编写 GUI。我似乎无法让 scroller 水平和垂直填充框架,而 messageInput 水平填充框架。这是它的样子:

import javax.swing.*;
import java.awt.*;

public class GUI extends JFrame{

private JPanel panel;
private JEditorPane content;
private JTextField messageInput;
private JScrollPane scroller;
private JMenu options;
private JMenuBar mb;
private JMenuItem item;

public GUI(){
    /** This is the frame**/
    this.setPreferredSize(new Dimension(380,600));
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel = new JPanel();
    panel.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;

    /** This is where the context shows up **/
    content = new JEditorPane();
    content.setEditable(false);

    /** Scroller that shows up in the context JEditorPane **/
    scroller = new JScrollPane(content);
    c.weightx = 0.0;
    c.weighty = 0.0;
    c.gridx = 0;
    c.gridy = 0;
    panel.add(scroller, c);

    /** This is where you type your message **/
    messageInput = new JTextField();
    c.weightx = 0.0;
    c.weighty = 0.0;
    c.gridx = 0;
    c.gridy = 1;
    c.weighty = 0.5;
    panel.add(messageInput, c);

    mb = new JMenuBar();
    options = new JMenu("Options");
    mb.add(options);
    this.setJMenuBar(mb);

    this.add(panel);
    this.pack();
    this.setVisible(true);

}



public static void main(String[] args) {
    new GUI();
}
}

get the scroller to fill the frame horizontally and vertically and the messageInput to fill the frame horizontally.

你想在两个方向都填写,所以设置

c.fill = GridBagConstraints.BOTH; // not HORIZONTAL

下一部分是固定权重,这将告诉我们为每个组件(相对)分配多少space:

    scroller = new JScrollPane(content);
    c.weightx = 0.5;
    c.weighty = 1.0;
    c.gridx = 0;
    c.gridy = 0;
    panel.add(scroller, c);

    messageInput = new JTextField();
    c.weightx = 0.5;
    c.weighty = 0.0;
    c.gridx = 0;
    c.gridy = 1;
    panel.add(messageInput, c);

weightx 应该是 non-zero 值以允许组件水平拉伸。 weighty 对于编辑器应该是 non-zero,但对于文本字段则不是,这样它就不会占用额外的垂直 space(在这种情况下,您不需要设置 c.fill = GridBagConstraints.HORIZONTAL 为它)。