Java Swing Tutorial - Java JComboBox .setSelectedItem (Object anObject)








Syntax

JComboBox.setSelectedItem(Object anObject) has the following syntax.

public void setSelectedItem(Object anObject)

Example

In the following code shows how to use JComboBox.setSelectedItem(Object anObject) method.

//  w  ww . ja v  a 2s.  c om
import javax.swing.JComboBox;

public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);

    Object obj = cb.getSelectedItem(); 

    cb.setSelectedItem("item2");
    obj = cb.getSelectedItem(); 

    cb.setSelectedItem("item3");
    obj = cb.getSelectedItem(); 
  }
}