Combo Box in Java

Combo box is a list of values which is shown in  dropdown. In combo box, scroll bar appears for more than 8 items. Also we can specify the number of visible items using inbuilt function:

                                        setMaximumRowCount(int)

example, 

                                        setMaximumRowCount(5);

Items in combo box can be added in two ways, they are:

a) Using parameterized constructor
b) Using addItem() method

a) Using parameterized constructor

example,

String items [] = {"Item1","Item2",....};

JComboBox cb = new JComboBox(items); // this is the parameterized constructor.

b) Using addItem() method

example,

JComboBox cb = new JComboBox();

cb.addItem("item1");

cb.addItem("item2");

Event Handling in ComboBox

In ComboBox, Both ActionEvent and ItemEvent are generated when item is selected.

ItemEvent is generated every time when a new item is selected whereas ActionEvent is generated when any item is selected.

--> getSelectedItem() => returns the item selected

      getSelectedIndex() => returns the index of item selected

Post a Comment

Previous Post Next Post