JComboBox isn't display data?

75 Views Asked by At

I try with code below:

 public class JComboBoxDemo extends JFrame{
    private JPanel panelParents;
    private JLabel lblTitle;
    private JComboBox cboLanguage;

public JComboBoxDemo() {
    super("JComboBox Demo");
    setContentPane(panelParents);

    String language[] = {"English","Khmer","Korea","Chinese","Thai","Russia"};

    cboLanguage = new JComboBox(language);
    cboLanguage.setSelectedIndex(1);
    cboLanguage.setMaximumRowCount(5);

    pack();
    setBounds(100,100,450,256);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
}
}

But it doesn't show anything in JComboBox, What's wrong with my code?

2

There are 2 best solutions below

0
On

The problem is you're are passing null to setContentPane. Below code is working

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JComboBoxDemo1 extends JFrame {
    private JPanel panelParents;
    private JLabel lblTitle;
    private JComboBox cboLanguage;

    public JComboBoxDemo1() {
        super("JComboBox Demo");

        String language[] = {"English", "Khmer", "Korea", "Chinese", "Thai",
                "Russia"};

        cboLanguage = new JComboBox(language);
        cboLanguage.setSelectedIndex(1);
        cboLanguage.setMaximumRowCount(5);
        getContentPane().add(cboLanguage);

        pack();
        setBounds(100, 100, 450, 256);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new JComboBoxDemo1();
    }
}
0
On

And below is the second approach. Ideally you should not override a class if you are not extending it's functionality. Prefer composition over inheritance, detail here. Incase of JFrame detail can be found here

Code below:

import java.awt.Component;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JComboBoxDemo {
    private JPanel panelParents;
    private JLabel lblTitle;

    public JComboBoxDemo() {
        JFrame frame = new JFrame("JComboBox Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(getMainComponent());
        frame.pack();
        frame.setBounds(100, 100, 450, 256);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
    }

    private Component getMainComponent() {
        JComboBox cboLanguage = new JComboBox();
        String language[] = {"English", "Khmer", "Korea", "Chinese", "Thai",
                "Russia"};
        cboLanguage = new JComboBox(language);
        cboLanguage.setSelectedIndex(1);
        cboLanguage.setMaximumRowCount(5);
        return cboLanguage;
    }

    public static void main(String[] args) {
        new JComboBoxDemo();
    }
}