JComboBox in Java Swing

Home  »  Java  »  Advance Java  »  Swing »  JComboBox

Choice lists, which are created in the AWT using the Choice class, are one the the implementations possible with the JComboBox class. JComboBox class is similar to the Choice class of the AWT package.

The following list show how a choice list is created:

  1. The JComboBox() object is constructed with no argument.
  2. The combo box's addItem(Object) method adds items to the list.
  3. The combo box's setEditable(boolean) method is used with false as the argument.

The JComboBox object is created with default choices. The setEditable() method allows the entry of another value if the parameter is set to true apart from the list choices.

If the setEditable() method is set to false, the combo box is converted into a choice list the only choice a user can make are those items added to the list.

Making the comob box setEditable() property to true, the user can enter text into the field instead of using the choice list to pick an item. This is the combination that gives combo boxes their name.

Example:

The following example creates a combo box with two items.



The following table describes some of the methods provided by the JComboBox class.

MethodsDescription
void addItem(Object)
void insertItemAt(Object, int)
Add or insert the specified object into the combo box's menu. The insert method places the specified object at the specified index, thus inserting it before the object currently at that index.
Boolean getState()
void setState(boolean)
Set or gets the status of the check box
Object getItemAt(int)
Object getSelectedItem()
Get an item from the combo box's menu from specific position. getSelectedItem() method returns an array containing the selected items.
void removeAllItems()
void removeItemAt(int)
Remove one or more items from the combo box's menu.
int getItemCount()Get the number of items in the combo box's menu
selectedItemChanged()This method is called when the selected item is changed.


Example:

The following applet displays a ComboBox with an Icon label. The Icon displayed, is changed according to the selection in the ComboBox.



C:\>jdk1.4\bin>javac JComboBoxDemo.java
C:\>jdk1.4\bin>java JComboBoxDemo

"Output of JComboBox.class"


Download Complete Program

  -  




Java Swing-1


JFrame JPanel JApplet
JButtons JLabels JTextFields
JPasswordField JTextAreas JCheckBoxes
JRadioButtons JList JComboBox




No comments:

Post a Comment