Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set selected index JComboBox by value

I want to set the selected index in a JComboBox by the value not the index. How to do that? Example

public class ComboItem {      private String value;     private String label;      public ComboItem(String value, String label) {         this.value = value;         this.label = label;     }      public String getValue() {         return this.value;     }      public String getLabel() {         return this.label;     }      @Override     public String toString() {         return label;     } }  JComboBox test = new JComboBox(); test.addItem(new ComboItem(0, "orange")); test.addItem(new ComboItem(1, "pear")); test.addItem(new ComboItem(2, "apple")); test.addItem(new ComboItem(3, "banana")); test.setSelectedItem("banana"); 

Ok, I have modified my question a bit. I forgot that i have a custom item inside my JComboBox that makes it a bit more difficult. i cant do setSelectedItem as i have a ComboItem inside each item. So still, how do i get this done?

like image 354
Arto Uusikangas Avatar asked Nov 30 '11 14:11

Arto Uusikangas


People also ask

Which method returns currently selected item in choice or JComboBox?

getRenderer. Returns the renderer used to display the selected item in the JComboBox field.

Which method is used to add items to JComboBox?

addItem(E item) : adds the item to the JComboBox.

What is the difference between JList and JComboBox?

A JComboBox is a component that displays a drop-down list and gives users options that we can select one and only one item at a time whereas a JList shows multiple items (rows) to the user and also gives an option to let the user select multiple items.

How do I center text in JComboBox?

By default, items in the JCombobox are left-aligned, we can also change to center alignment by using the setHorizontalAlignment(DefaultListCellRenderer.


2 Answers

setSelectedItem("banana"). You could have found it yourself by just reading the javadoc.

Edit: since you changed the question, I'll change my answer.

If you want to select the item having the "banana" label, then you have two solutions:

  1. Iterate through the items to find the one (or the index of the one) which has the given label, and then call setSelectedItem(theFoundItem) (or setSelectedIndex(theFoundIndex))
  2. Override equals and hashCode in ComboItem so that two ComboItem instances having the same name are equal, and simply use setSelectedItem(new ComboItem(anyNumber, "banana"));
like image 173
JB Nizet Avatar answered Sep 28 '22 07:09

JB Nizet


You should use model

comboBox.getModel().setSelectedItem(object); 
like image 26
milosz Avatar answered Sep 28 '22 07:09

milosz