How do I get the index of the item selected from a

2020-03-06 01:04发布

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.

3条回答
再贱就再见
2楼-- · 2020-03-06 01:34

indexes starts from 0,1,2,.. if you want to get the index of selected item then do this

optionsCombo.getSelectedIndex()
查看更多
男人必须洒脱
3楼-- · 2020-03-06 01:43
int index = optionsCombo.getSelectedIndex() 

will give selected index. Use this in combo box action listener

查看更多
女痞
4楼-- · 2020-03-06 01:46

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);
查看更多
登录 后发表回答