当我使用下面的代码使用GridBagLayout制作JFrame时,这是输出:
我希望前三行的按钮都具有相同的宽度,但它们不是。
我还希望第四行按钮都具有相同的宽度。
我怎么能这样做?
这是代码:
public Test() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menu = new JMenuBar();
setJMenuBar(menu);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
field = new JTextField(20);
field.setFont(new Font("Cambria Math", Font.PLAIN, 32));
field.setEditable(false);
updateDisplay();
c.fill = GridBagConstraints.HORIZONTAL;
//c.insets = new Insets(9,9,9,9);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 24;
c.gridheight = 2;
add(field, c);
// sin, cos, tan
c.weightx = 0;
c.gridwidth = 4;
c.gridheight = 1;
c.gridx = 0;
c.weightx = 0;
c.gridy = 2;
add(createButton("sin"), c);
c.gridx = 4;
add(createButton("cos"), c);
c.gridx = 8;
add(createButton("tan"), c);
// cot, sec, csc
c.gridx = 0;
c.gridy = 3;
add(createButton("cot"), c);
c.gridx = 4;
add(createButton("sec"), c);
c.gridx = 8;
add(createButton("csc"), c);
// asin, acos, atan
c.gridx = 0;
c.gridy = 4;
add(createButton("asin"), c);
c.gridx = 4;
add(createButton("acos"), c);
c.gridx = 8;
add(createButton("atan"), c);
// atan2, acot, asec, acsc
c.gridy = 5;
c.gridwidth = 3;
c.weightx = 0;
c.gridx = 0;
add(createButton("atan2"), c);
c.gridx = 3;
add(createButton("acot"), c);
c.gridx = 6;
add(createButton("asec"), c);
c.gridx = 9;
add(createButton("acsc"), c);
pack();
setVisible(true);
}
public JButton createButton(String name) {
JButton button = new JButton(name);
button.setActionCommand(name);
button.addActionListener(this);
button.setFont(new Font("Dialog", Font.PLAIN, 25));
return button;
}
答案 0 :(得分:2)
我认为你不能使用GridBagLayout。
而是使用GridLayout(0,1)创建主面板;
然后使用GridLayout(1,0)为前3个按钮创建第二个面板,并将此面板添加到第一个面板。
重复其他三行。