Leb*_*ski 4 java swing layout-manager gridbaglayout
我正在为聊天程序编写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();
}
}
Run Code Online (Sandbox Code Playgroud)
让
scroller水平和垂直messageInput填充框架,水平填充框架.
你想填写两个方向,所以设置
c.fill = GridBagConstraints.BOTH; // not HORIZONTAL
Run Code Online (Sandbox Code Playgroud)
下一部分是修复权重,它将告诉每个组件分配多少空间(相对):
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);
Run Code Online (Sandbox Code Playgroud)
weightx应该是一个非零值,以允许组件水平拉伸.weighty对于编辑器应该不为零,但对于文本字段不应该为零,这样它就不会占用额外的垂直空间(在这种情况下,您不需要c.fill = GridBagConstraints.HORIZONTAL为它设置).