Java Swing How to - Use Control-Option-Space key to open a Popup in a JCombobox








Question

We would like to know how to use Control-Option-Space key to open a Popup in a JCombobox.

Answer

import java.awt.event.KeyEvent;
//from  w  ww.  ja  v a 2 s.c  om
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class Main extends JPanel {

  public Main() {
    JComboBox cpmbo = new JComboBox();
    cpmbo.addItem("One");
    cpmbo.addItem("Two");
    cpmbo.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
        KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, KeyEvent.ALT_DOWN_MASK
            | KeyEvent.CTRL_DOWN_MASK), "spacePopup");

    this.add(cpmbo);
  }
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new Main());
    f.pack();
    f.setVisible(true);
  }
}