gpt4 book ai didi

Java - 无法从 JComboBox 获取所选项目

转载 作者:行者123 更新时间:2023-12-01 14:37:05 26 4
gpt4 key购买 nike

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

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 完美更新,第一个项目神奇地随着组合框项目选择而更新。

出于学习目的,代码如下:

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

}
});

关于Java - 无法从 JComboBox 获取所选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16388377/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com