我正在用 Java 制作一个简单的计算器 GUI,以开始学习如何使用 Java。以下代码不起作用。仅出现第一列。第二列和第三列去哪里?
package Start;
import java.awt.*;
import javax.swing.*;
public class CalculatorGUI {
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
JLabel label;
JButton button;
label = new JLabel("I'm a calculator");
c.gridwidth = GridBagConstraints.REMAINDER;
c.weightx = 0.0;
c.gridx = 0;
c.gridy = 0;
pane.add(label, c);
button = new JButton("1");
c.gridx = 0;
c.gridy = 1;
pane.add(button, c);
button = new JButton("2");
c.gridx = 1;
c.gridy = 1;
pane.add(button, c);
button = new JButton("3");
c.gridx = 2;
c.gridy = 1;
pane.add(button, c);
button = new JButton("4");
c.gridx = 0;
c.gridy = 2;
pane.add(button, c);
button = new JButton("5");
c.gridx = 1;
c.gridy = 2;
pane.add(button, c);
button = new JButton("6");
c.gridx = 2;
c.gridy = 2;
pane.add(button, c);
button = new JButton("7");
c.gridx = 0;
c.gridy = 3;
pane.add(button, c);
button = new JButton("8");
c.gridx = 1;
c.gridy = 3;
pane.add(button, c);
button = new JButton("9");
c.gridx = 2;
c.gridy = 3;
pane.add(button, c);
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("CalculatorGUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
我尝试让标签只写c.gridwidth = 3;
,但这做了同样的事情。当我将宽度设为 1 时,所有按钮都会出现,但标签仅位于一个单元格中。 如何使标签跨越 3 列?而不使其他按钮消失。
最佳答案
How do i make the label span 3 columns without gridwidth?
c.gridwidth = 3;
然后,您需要在添加其他组件之前将其重置为 1。
so that it is centered over the '2' button
您还需要设置标签的文本对齐方式:
label.setHorizontalAlignment(JLabel.CENTER);
关于java - 为什么中间的栏不显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23091864/