In this section, you can learn how to operate the Combo Box component, you will learn how to add items to the combo box, remove items from the combo box.
This program shows a text field, a combo box and two command buttons, first is for the adding items to the combo box and another is for the removing items from the combo. When you click on the add command button then the text of the text box is added to the combo box if the text box is not blank otherwise a message box will display with the message "Please enter text in Text Box". But when you click on the remove button the item at the 0th (zero) position of the combo box will be remove from the combo box if the combo box has one item at least otherwise a message box will display with the message "Item not available.". Following is the image for the result of the given program:
This program has used various java APIs for doing required are explained as follows:
JComboBox combo = new JComboBox(items);
The above code has been used to create a combo box in this program. The JComboBox instance combo is created using the constructor of the JComboBox class of the javax.swing.*; package. This constructor holds the string array in which items for the combo box are kept.
This is the method of the JComboBox class which return the number of the items present is the combo box.
this is the method of the JComboBox class which returns the name of the item of the combo box at the specified position. This specification of position the item in the combo box is held by the getItemAt() method as a parameter.
This the method of the JOptionPane class of javax.swing.*; package. This method displays some messages in the special dialog box. This method holds two argument in this program in which first is the parent object name and another is the message text which has to be displayed.
This is the method of the JComboBox class which adds items to the combo box. This method takes a string argument which is to be used to add to the combo box.
This is the method of the JComboBox class which remove the item at the specified position of the combo box. This method holds the integer value for the position number of he of the item in combo box to remove it.
Here is the code of the program:
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial