java - 为什么中间的栏不显示?

标签 java swing alignment centering gridbaglayout

我正在用 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/

相关文章:

java - 在 Timer 类对象中使用 Main 方法中的 NULL Autowired 对象

html - 无法垂直居中 h1 元素和输入元素

html - 如何垂直对齐字形?

jquery - 为什么这个用于使 div 转到右上角或左上角的 jQuery 代码不起作用?

java - HTTP 状态 500 - shopizer 中的请求处理失败

java - 替换 PDF 文件中的数据

java - 如何从 java.util.date 转换为 JodaTime 并获得相同的日期

java - 如何让这个 JButton 工作?

java - Stacktrace 不包括我的类(class)。我应该怎么办?

java - Java EE 应用程序浏览器的替代品?