Reputation: 7845
If I have three items in the ComboBox:
123, 456 and 789, it's only possible to get the first one (123), ignoring all the rest.
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
}
});
Very unpleasant problem. I work with the combobox only when I click on it (Popup), therefore I add its items just in this moment and then I erase them. Nevertheless, the first/title Item gets never updated or it's just blank, and I can't save the last selection state with fields and now I can't do it through the aid of an ArrayList either. I tried mouse and item listeners and I failed miserably everytime, because it returns the first element always.
Do you have any idea on how to keep the track of what was selected, even while dealing with it only inside the popup? I thank you very much!
Upvotes: 0
Views: 928
Reputation: 7845
Brilliant mKorbel! I erased the popup listener and went to the JList, and I finally got it to work; now it works perfectly, the combobox gets updated beautifully according to the JList, and the first Item gets updated with the combobox item selection magically.
For learning purposes, here's the code:
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));
}
}
}
}
});
Upvotes: 1
Reputation: 3591
You need to react on the SelectionEvents and not only on the Popup events. In your code the selectionsaver.add() method is only called at the each time before the popup will be visible.
Upvotes: 0