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

荒凉一梦 提交于 2019-11-30 19:55:43

问题


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.


回答1:


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);



回答2:


int index = optionsCombo.getSelectedIndex() 

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




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!