获取JComboBox的选定对象位置

时间:2011-07-12 04:51:35

标签: java swing drop-down-menu jcombobox

我正在尝试获取JComboBox对象的位置(作为int),生成ComboBox并拥有这样的动作侦听器

for (int d=0; d<i; d++)
        {
            titulos.addItem(listaPraBox[d]);
        }

  ActionListener comboListener = new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
            ItemSelectable is =(ItemSelectable)actionEvent.getSource();     
            objectoseleccionado = selectedString(is);
            DeskMetodos.listaTexto(objectoseleccionado);        
          }
        };
    titulos.addActionListener(comboListener);

执行

 static private String selectedString(ItemSelectable is) {
    Object selected[] = is.getSelectedObjects();

    return ((selected.length == 0) ? "null" : (String)selected[0]);
  }

但我希望所选对象的位置通过该int从另一个数组中获取字符串。

这甚至可能吗?通过我所做的搜索,甚至没有提到这一点。

2 个答案:

答案 0 :(得分:5)

JComboBox定义getSelectedIndex()。实现只是循环检查与getSelectedItem()的等式的数据模型。

这不会导致ItemSelectable,但数据模型本身也没有,所以你可能需要使用具体的类。

答案 1 :(得分:1)

不是将项存储在ComboBox中,而是必须使用索引来引用另一个值数组。只需在ComboBox中存储一个对象,该对象具有与您当前显示值匹配的toString()输出以及对该数组中对象的直接引用。这样,拉动所选项目或处理comobo框的任何对象都可以拉出他们需要的值,而不必“知道”这个其他数组。

相关问题