我正在为聊天程序编写 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 themessageInput
to fill the frame horizontally.
你要往两个方向都填,所以设置
c.fill = GridBagConstraints.BOTH; // not HORIZONTAL
下一部分是固定权重,这将告诉(相对)为每个组件分配多少空间:
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
应该是一个非零值以允许组件水平拉伸(stretch)。 weighty
对于编辑器应该是非零的,但对于文本字段则不是,这样它就不会占用额外的垂直空间(在这种情况下你不需要设置 c.fill = GridBagConstraints.HORIZONTAL
)。
关于Java GridBagLayout 不水平填充框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34951954/