无法显示JComboBox

时间:2014-10-04 21:59:04

标签: java jcombobox

以下是我的Java程序的简化版本。 它工作正常,直到我添加该行 JComboBox comboBox =新的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);
    }    
}

1 个答案:

答案 0 :(得分:1)

你可以做两件事:

在最后添加frame.setVisible(true);或在代码中添加comboBox而不是在其中。

在结尾处或在代码中添加frame.getRootPane().updateUI();后添加comboBox

在您完成在树中添加或更改组件时添加上述代码是首选,例如在您的方法结束时。

我期待您的代码中出现问题的原因很明显。但是,如果没有,请告诉我。

相关问题