简体   繁体   中英

Adding a JComboBox to a JPanel

I am trying to add a Combobox to a jpanel. I want to add the items for the combobox from an arraylist but it's not working. Nothing shows up. The code I am writing here is not the whole thing, I have a JFrame and inside the JFrame after I click a button the JPanel supposed to open.

                     ArrayList<Integer> days;
                     days = new ArrayList<Integer>();

                     for (int i=1; i<=31; i++) { 
                        days.add(i);

                     }
                    JPanel res = new JPanel();
                    res.setBounds(20, 50, 300, 300);
                    JComboBox<ArrayList<Integer>> day = new JComboBox<ArrayList<Integer>>();                         
                   day.addItem(days);
                   day.addItem(days);
                    res.add(day);
                    jf.add(res);

                }

Add to a model, then to the combo box

DefaultComboBoxModel<Integer> model = new DefaultComboBoxModel<>();
for (int i = 1; i <= 31; i++) {
   model.addElement(i);
}
JComboBox comboBox = new JComboBox(model);

Your combobox instanciation seems not good.

This might be better:

List<Integer> days = new ArrayList<>(); for (int i=1; i<=31; i++) days.add(i); JComboBox day = new JComboBox( days );

See examples there: https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM