我有JLabel
,JButton
和JTextField
;我需要将JLabel
放在JFrame
原点的单元格(0,0)中,然后放入JTextField
(1,0),最后放JButton
(0 ,1)在第二行。但是,我的所有组件都放在同一行,它们从左到右开始。
我的代码:
public static void initializeFrame(){
GridBagLayout layout = new GridBagLayout();
// set frame layout
JFrame frame = new JFrame("JFrame Source Demo");
frame.setSize(new Dimension(400,200));
frame.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
JPanel topPanel = new JPanel();
JLabel jlbempty = new JLabel("MacAddress");
c.gridx = 0;
c.gridy = 0;
c.ipadx = 30;
c.ipady = 10;
topPanel.add(jlbempty,c);
JTextField field1 = new JTextField();
c.gridx = 1;
c.gridy = 0;
c.ipadx = 30;
c.ipady = 10;
topPanel.add(field1,c);
field1.setPreferredSize(new Dimension(150, 20));
JButton jb = new JButton("Generation Mac");
c.gridx = 0;
c.gridy = 1;
c.ipadx = 30;
c.ipady = 10;
layout.setConstraints( jb, c ); // set constraints
topPanel.add(field1,c);
topPanel.add(jb,c);
frame.add(topPanel);
frame.pack();
frame.setVisible(true);
}
答案 0 :(得分:1)
我在您的代码中观察到的一些事情。
将topPanel
的布局设置为GridBagLayout
。
您正在拨打topPanel.add(field1, c);
两次。
不要使用首选大小而不是使用相对大小。只需将其移交给布局管理器即可调整组件的大小。
详细了解How to Use GridBagLayout以获得更清晰的信息,并查找示例代码。
请详细了解GridBagLayout的其他属性。
以下是带内联注释的简化代码。
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
// c.insets=new Insets(5,5,5,5); // margin outside the panel
JPanel topPanel = new JPanel(new GridBagLayout());
JLabel jlbempty = new JLabel("MacAddress");
c.gridx = 0;
c.gridy = 0;
// c.weightx=0.25; // width 25% for 1st column
topPanel.add(jlbempty, c);
JTextField field1 = new JTextField();
c.gridx = 1;
c.gridy = 0;
// c.weightx=0.75; // width 75% for 2nd column
topPanel.add(field1, c);
JButton jb = new JButton("Generation Mac");
c.gridx = 0;
c.gridy = 1;
//c.gridwidth = 2; //SPAN to 2 columns if needed
// c.weightx=1.0; // back to width 100%
topPanel.add(jb, c);