Getting and Setting the Selected Item in a JComboBox Component

// Create a read-only combobox String[] items = {"item1", "item2"}; JComboBox cb = new JComboBox(items); // Get current value Object obj = cb.getSelectedItem(); // item1 // Set a new value cb.setSelectedItem("item2"); obj = cb.getSelectedItem(); // item2 // If the new value is not in the list of valid items, the call is ignored cb.setSelectedItem("item3"); obj = cb.getSelectedItem(); // item2 // However, if the combobox is editable, the new value can be any value cb.setEditable(true); cb.setSelectedItem("item3"); obj = cb.getSelectedItem(); // item3

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.