This is how I created my JComboBox -
String[] options = {"First", "Second" , "Third"};
JComboBox optionsCombo = new JComboBox(options);
When one of these items is selected, how do i get the index of the item which was selected ? I don't want the item the item that was selected.
Use : optionsCombo.getSelectedIndex();
inside actionListener Like this :
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Selected: " + optionsCombo.getSelectedItem());
System.out.println(", Position: " + optionsCombo.getSelectedIndex());
}
};
optionsCombo.addActionListener(actionListener);
int index = optionsCombo.getSelectedIndex()
will give selected index. Use this in combo box action listener
indexes starts from 0,1,2,.. if you want to get the index of selected item then do this
optionsCombo.getSelectedIndex()
来源:https://stackoverflow.com/questions/15760592/how-do-i-get-the-index-of-the-item-selected-from-a-jcombobox