If you want to be able to select exactly by the string, which is what you indicate in the description, I would create a class to represent your specific item, maintaining in it the int and string as separate fields, and override toString()
to return the representation you want. You can then have a method searching your item based on the string alone. For a relatively small number of items, this is efficient and simple. If you had a large number of items, I'd suggest storing them as values in a HashMap
using the string as a key.
import java.awt.BorderLayout;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JComboBox;
import javax.swing.JFrame;
class Item {
int intValue;
String strValue;
public Item(int intValue, String strValue) {
this.intValue = intValue;
this.strValue = strValue;
}
public String toString() {
return intValue + " - " + strValue;
}
}
public class TestCombo {
private static JComboBox<Item> cb;
public static void main(String[]args) {
JFrame f = new JFrame();
f.setSize(640,400);
cb = new JComboBox<>();
cb.addItem(new Item(1, "one"));
cb.addItem(new Item(2, "two"));
cb.addItem(new Item(3, "three"));
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(cb, BorderLayout.NORTH);
f.setVisible(true);
selectItemByString("three");
}
private static void selectItemByString(String s) {
for (int i=0; i<cb.getItemCount(); i++) {
if (cb.getItemAt(i).strValue.equals(s)) {
cb.setSelectedIndex(i);
break;
}
}
return;
}
}