2014-10-04 71 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