2014-04-15 60 views
1

我正在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列?沒有使其他按鈕消失。

+0

你可以嘗試使用GridLayout的3列('新的GridLayout(0,3)')。 – user3507600

回答

2

我如何使標籤跨度3列沒有gridwidth?

c.gridwidth = 3; 

然後,您將需要添加其他組件之前將其重置爲1。

,使其集中在「2」鍵

您還需要設置標籤的文本對齊方式:

label.setHorizontalAlignment(JLabel.CENTER); 
+0

謝謝,沒有意識到我不得不重置它。 – Cole

0

您使用

c.gridwidth = GridBagConstraints.REMAINDER; 

指定當前組件是其行或列中的最後一個組件。

因此,評論這條線,它應該工作得很好。

Reaf更多關於GridBagLayout

+0

如何使標籤跨度3列沒有gridwidth? – Cole

+0

我基於我的GUI關閉了該鏈接中的示例,但它不起作用。 – Cole

+0

您是否按照上面的描述評論過上述行? – Salah