简体   繁体   English

如何获得从JComboBox中选择的项目的索引?

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

This is how I created my JComboBox - 这就是我创建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. 我不想要该项目被选中的项目。

int index = optionsCombo.getSelectedIndex() 

will give selected index. 将给出选定的索引。 Use this in combo box action listener 在组合框动作监听器中使用它

indexs从0,1,2,..开始。如果要获取所选项目的索引,请执行此操作

optionsCombo.getSelectedIndex()

Use : optionsCombo.getSelectedIndex(); 使用: optionsCombo.getSelectedIndex();

inside actionListener Like this : actionListener内部,像这样:

 ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("Selected: " + optionsCombo.getSelectedItem());
        System.out.println(", Position: " + optionsCombo.getSelectedIndex());
      }
    };
    optionsCombo.addActionListener(actionListener);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM