Java 为什么中间一栏没有出现?

Java 为什么中间一栏没有出现?,java,swing,alignment,centering,gridbaglayout,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.setLa

我正在用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列?而不使其他按钮消失。

您正在使用

c.gridwidth = GridBagConstraints.REMAINDER;
它指定当前组件是其列或行中的最后一个组件

所以把这行注释掉,它应该可以正常工作

更多关于


如何在没有gridwidth的情况下使标签跨越3列

在添加其他组件之前,需要将其重置为1

使其位于“2”按钮的中心

您还需要设置标签的文本对齐方式:

label.setHorizontalAlignment(JLabel.CENTER);

您可以尝试使用具有3列的GridLayout(
new GridLayout(0,3)
)。如何使标签跨越3列而不使用gridwidth?我基于该链接中的示例创建GUI,但它不起作用。您是否已将上述行作为我的说明进行了注释?是的,但标签“我是计算器”只占用一个单元格。我希望它跨越第0列、第1列和第2列,以便它位于“2”按钮的中心。我没有意识到我必须重置它。
label.setHorizontalAlignment(JLabel.CENTER);