Reputation: 302
When I register ActionListener on a non-editable JComboBox it fires actionPerformed() every time user changes selected item with arrows keys or with context search (typing the first letter of the item name).
I found similar question here: How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard. But that solution doesn't cover context search option. It fires actionPerformed() when I type something.
How to determine when user confirms selected item using enter key or mouse click?
Upvotes: 3
Views: 7178
Reputation: 302
Thank you for answer. This is what I really needed. I also added actionListener for the case when user moves through the combobox with arrows keys when popup is invisible:
scriptsCombobox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox source = (JComboBox) e.getSource();
if(!source.isPopupVisible()){
//update data
}
}
});
Upvotes: 3
Reputation: 109815
better would be implements ItemListener (fired twice SELECTED and DESELECTED), than ActionListener and KeyBindings, maybe with succes this simple example here
import java.awt.*;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class PopupTest {
public static void main(String[] args) {
final JComboBox c = new JComboBox();
c.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
System.out.println(e.getSource());
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
System.out.println(e.getSource());
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
System.out.println(e.getSource());
}
});
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new FlowLayout());
f.getContentPane().add(c);
f.pack();
f.setVisible(true);
}
private PopupTest() {
}
}
Upvotes: 7