如果我在组合框中有三个项目:

123、456和789,只能获取第一个(123),而忽略其余所有内容。

mainCombo.addPopupMenuListener(new PopupMenuListener() {

        ArrayList<Object> selectionSaver = new ArrayList<Object>();

        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent arg0) {
            if (mainList.getSelectedValue() != null) {
                ArrayList<Object> arrayValue = mainMethods.returnArrayList(mainList.getSelectedValue());
                for (int i = 0; i < arrayValue.size(); i++) {
                mainCombo.addItem(arrayValue.get(i));
                }
                Object lastSelected = mainCombo.getSelectedItem(); // It gets the bloody first and never the other ones, even when I select them.
                selectionSaver.add(lastSelected); // It adds the bloody first that was captured.
                System.out.println(selectionSaver); // Prints only the first, because it was selected by default.
            }
        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) {
            mainCombo.removeAllItems();
        }

        @Override
        public void popupMenuCanceled(PopupMenuEvent arg0) {
            // TODO Auto-generated method stub

        }
    });


非常不愉快的问题。我仅在单击组合框(弹出框)时才使用组合框,因此我仅在此刻添加其项目,然后将其删除。但是,第一个/标题项永远不会更新,或者只是空白,而且我无法使用字段保存最后的选择状态,现在我也无法通过ArrayList来完成。我尝试了鼠标和项目侦听器,但每次都失败了,因为它总是返回第一个元素。

您是否有关于如何保持所选内容跟踪的想法,即使仅在弹出窗口中进行处理也没有?我非常感谢你!

最佳答案

辉煌的mKorbel!我删除了弹出侦听器并转到JList,最后使它起作用。现在它可以完美工作,可以根据JList精美地更新组合框,并且第一个Item可以神奇地使用组合框项选择进行更新。

出于学习目的,下面是代码:

mainList.addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent arg0) {
            int selected[] = mainList.getSelectedIndices();
            for (int i = 0; i < selected.length; i++) {
                String element = mainList.getModel().getElementAt(selected[i]);
                textItem.setText(element);
            }
            if (arg0.getValueIsAdjusting() == true) {
                if (mainList.getSelectedValue() != null) {
                    ArrayList<Object> arrayValue = mainMethods.returnArrayList(mainList.getSelectedValue());
                    mainCombo.removeAllItems();
                    for (int i = 0; i < arrayValue.size(); i++) {
                        mainCombo.addItem(arrayValue.get(i));
                    }
                }
            }

        }
    });

09-25 20:18
查看更多