2014-10-04 70 views
0

下面是我的Java程序的簡化版本。 它工作正常,直到我添加行 JComboBox comboBox = new JComboBox(options);無法讓JComboBox顯示

添加該行後,窗口上不再顯示任何內容(無按鈕,無標籤,無顏色等)。

有人可以幫我弄清楚這行代碼有什麼問題(它沒有顯示語法錯誤)。

import java.awt.*; 
import javax.swing.*; 

public class JavaApplication23 { 

    public static void main(String[] args) { 
     JFrame frame = new JFrame(); 
     frame.setLayout(new BorderLayout());   
     frame.setTitle("Test program");   
     frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
     frame.setSize(600, 400);   
     frame.setVisible(true);     

     JLabel label = new JLabel("Hello"); 
     JButton button = new JButton("Click"); 
     String[] options = new String[] {"Cat", "Dog"}; 
     JComboBox comboBox = new JComboBox(options);  //It goes wrong when I add this line 

     JPanel topPanel = new JPanel(); 
     JPanel centerPanel = new JPanel(); 
     JPanel bottomPanel = new JPanel(); 

     topPanel.add(label); 
     bottomPanel.add(button); 
     centerPanel.add(comboBox); 

     frame.add(topPanel, BorderLayout.PAGE_START); 
     frame.add(bottomPanel, BorderLayout.PAGE_END); 
     frame.add(centerPanel, BorderLayout.CENTER); 
    }  
} 
+3

所有組件添加後調用'setVisible' – Reimeus 2014-10-04 22:01:10

+0

非常感謝您的幫助。這解決了問題。 – user2939293 2014-10-04 22:11:41

回答

1

你可以做兩件事情:

末或在你的代碼,而不是添加之中後comboBox添加frame.setVisible(true);

末或在你的代碼中加入comboBox後添加frame.getRootPane().updateUI();

當您完成在樹中添加或更改組件時,添加上面的代碼是首選的,例如在您的方法結束時。

我在期待您的代碼中存在問題的原因很明確。但是,如果不是,請告訴我。

+0

就這麼簡單? 非常感謝!對於updateUI()建議,爲 – user2939293 2014-10-04 22:10:50

+0

-1。沒有必要使用該方法。如果你想添加組件到一個可見的GUI那麼你應該調用'revalidate()'和'repaint()'。 – camickr 2014-10-04 22:20:20

+2

'repaint()'在他的情況下不起作用,'revalidate()'等價於調用invalidate()和validate()**。另一方面'updateUI()'在他的情況下工作,它會重置其中包含的所有UI組件。 – afzalex 2014-10-04 22:33:51