1

I have a JComboBox with multiple values in it. How to detect the keystroke control-option-space to open a pop-up window of JComboBox in MAC?

4

1 回答 1

3

目前尚不清楚您是否想要control-option-space除了标准键之外或代替标准space键的键绑定。在任何一种情况下,您都可以aquaSpacePressed使用如下所示的绑定来调用操作。有关详细信息,请参阅如何使用键绑定

combo.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
    KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,
        KeyEvent.ALT_DOWN_MASK | KeyEvent.CTRL_DOWN_MASK),
    "aquaSpacePressed");

因为这是特定于 Mac 的,您可能需要使用如下谓词:

System.getProperty("os.name").startsWith("Mac OS X")

附录:下面的sscce用于测试修改后的问题中的场景。

附录:由于不清楚的原因,启用会System Preferences > Speech > Text to Speech抢占control-option-space绑定。作为替代方案,您可以绑定到标准Action, "spacePopup",如下面修改后的示例所示。

import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

/**
 * @see http://stackoverflow.com/a/13412208/230513
 */
public class ComboKeyTest extends JPanel {

    public ComboKeyTest() {
        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);
    }

    private void display() {
        JFrame f = new JFrame("NewJavaGUI");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ComboKeyTest().display();
            }
        });
    }
}
于 2012-11-16T07:30:04.340 回答