【问题标题】:How do I get the index of the item selected from a JComboBox?如何获取从 JComboBox 中选择的项目的索引?
【发布时间】:2013-03-23 12:57:07
【问题描述】:

这就是我创建 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 ?我不想要被选中的项目。

【问题讨论】:

  • 您是否在 JComboBox 上检查了相应的侦听器?它必须提供一种获取所选索引的方法。

标签: java swing selection jcombobox


【解决方案1】:

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

optionsCombo.getSelectedIndex()

【讨论】:

    【解决方案2】:
    int index = optionsCombo.getSelectedIndex() 
    

    将给出选定的索引。在组合框动作监听器中使用它

    【讨论】:

      【解决方案3】:

      使用:optionsCombo.getSelectedIndex();

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多