Search code examples
javajcombobox

Can't get JComboBox to show


Below is a simplified version of my Java program. It works fine until I add the line JComboBox comboBox = new JComboBox(options);

After adding that line nothing no longer shows on the window (no buttons, no labels, no colors and so on...).

Can someone please help me figure out what is wrong with that line of code (it shows no syntax error).

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);
    }    
}

Solution

  • You can do 2 things :

    Add frame.setVisible(true); at the end or after adding comboBox in your code instead of amid.

    or

    Add frame.getRootPane().updateUI(); at the end or after adding comboBox in your code.

    To add the above code when you are done with adding or changing components in tree is preferred i.e. in your case at the end of your method.

    I am expecting that the reason for the problem in you code is clear. But let me know if not.