2013-07-11 120 views
0

嗨有人知道爲什麼我的「button1」不顯示?我似乎無法弄清楚,當我執行該程序它一切正常,運行成功,但它不顯示此按鈕。任何幫助,將不勝感激。JButton不顯示

private Container c; 
private JPanel gridPanel; 
private JComboBox combo; 
final JLabel label = new JLabel(); 
private JButton button1 = new JButton("Clear"); 
private JButton button2 = new JButton("Exit"); 

/** 
* Christopher Haddad - 559815X 
*/ 
public Planets() { 
    c = getContentPane(); 
    gridPanel = new JPanel(); 
    gridPanel.setLayout(new GridLayout(5, 0, 0, 0)); 

    label.setVisible(true); 

    combo = new JComboBox(); 
    combo.setEditable(false); 
    combo.addItem("No Planet Selected"); 
    combo.addItem("Mercury"); 
    combo.addItem("Venus"); 
    combo.addItem("Earth"); 
    gridPanel.add(combo); 

    add(button1); 
    add(button2); 
    button1.addActionListener(this); 
    button2.addActionListener(this); 

    c.add(gridPanel, BorderLayout.NORTH); 
    setTitle("Planet Diameter"); 
    setSize(700, 250); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setVisible(true); 

    combo.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent event) { 

      JComboBox comboBox = (JComboBox) event.getSource(); 

      Object select = comboBox.getSelectedItem(); 

      if(select.toString().equals("No Planet Selected")) 
       label.setText(""); 
      else if(select.toString().equals("Mercury")) 
       label.setText("The planet Mercury is 3100kms in diameter"); 
      else if(select.toString().equals("Venus")) 
       label.setText("The planet Venus is 7500kms in diameter"); 
      else if (select.toString().equals("Earth")) 
       label.setText("The planet Earth is 8000kms in diameter"); 

     } 
    }); 
    getContentPane().add(combo); 
    getContentPane().add(label); 
} 

    // event handling method, implementing the actionPerformed method of ActionListener 
    public void actionPerformed(ActionEvent e) 
    { 
     // set the button label to number of times it has been clicked 
     if(e.getSource() == button1) { 
      label.setText(" "); 
     } 
     else if(e.getSource() == button2) { 
      System.exit(0); 
     } 
    } 
+0

沒關係,解決它,謝謝 – thechrishaddad

+0

這是導致你的佈局,刪除帖子,然後的xD – nachokk

+0

IIRC只有主持人可以刪除帖子。 – mattbdean

回答

3

這是很難確定的,但我假設你是直接將內容添加到頂層容器,就像一個JFrame

JFrame使用BorderLayout因爲它的默認佈局管理器,所以使用

add(button1); 
add(button2); 

Basially說,addbutton1CENTER位置然後addbutton2CENTER的位置。 BorderLayout將只允許單個組件存在於特定位置。

嘗試添加按鈕,另一個小組第一...