【问题标题】:How to make string get elements from an array based on the combobox array如何使字符串从基于组合框数组的数组中获取元素
【发布时间】:2016-08-06 21:24:55
【问题描述】:

我想念一些东西,我会感谢你的帮助 我有一个组合框的数组

String array [] = {"aa", "bb", "cc"};

我让这个 for 循环在整个数组中运行

for(String s: array) {
    if(s.equals(array[0]) {
        //do something
    }
}

现在我需要的是,只有当组合框选择元素时,我才需要对数组中的每个元素进行“做某事”,我的数组太长了,我无法为每个元素编写 if 语句数组中的元素。

我想要的是类似的东西

for(String s : array) { 
  if(s equals the array elements) {
      substring the first index of each element
      print s
      so result let's say will be like this
      a ----> if only element a is selected
      b ----> if only element b is seleceted
      etc ...
  }
}

【问题讨论】:

  • 我认为您需要的是组合框的事件侦听器,然后在 if 语句中将该组合框的值与您的数组进行匹配,然后将其与 do something 匹配。我不确定您在什么情况下谈论“组合框”,无论是 Android 还是 JavaFX 还是什么。
  • @px06 谢谢,是的,我确实为此使用了 ItelmListener,但我错过了一些让我的 if 语句正常工作的东西。我在 Eclipse 中使用普通的 Java 来做到这一点
  • 那么,你指的是像 JCombobox 这样的东西?
  • 请扩展和改进您的问题。你知道怎么做 for 循环,你知道怎么做 if 块——那么你到底在坚持什么?
  • 如果这是使用 Java Swing 那么这里有一个关于如何获取组合框的选定值的重复问题,但是由于问题和标签非常模糊,我无法确定是什么库OP正在使用。 stackoverflow.com/questions/11999560/…

标签: java arrays if-statement for-loop jcombobox


【解决方案1】:

正如 px06 所说,您可能希望在 Combobox 上添加一个事件侦听器,然后处理项目选择。 这是您要查找的代码 sn-p:

String[] array = {"aa", "bb", "cc"};
JComboBox comboBox = new JComboBox(array);
comboBox.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent event) {
        JComboBox<String> combo = (JComboBox<String>) event.getSource();
        String selectedItem = (String) combo.getSelectedItem();

        if (selectedItem.equals("<some-choice>")) {
            //do something
        } else if (selectedItem.equals("<some-other-choice>")) {
            //do something else...
        }
    }
});

但是,如果您想根据选择执行特定操作,我看不出如何逃避检查选择了哪个项目。

我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    这解决了我的问题,谢谢大家,很抱歉打扰您

    for(String s: arrar) {
      if(combobox.getSelectedItem().equals(s)) {
         do something;
        }
    }   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-28
      • 2017-10-11
      • 2012-08-29
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多