我正在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列?沒有使其他按鈕消失。
你可以嘗試使用GridLayout的3列('新的GridLayout(0,3)')。 – user3507600