键绑定不起作用 - 摇摆

时间:2015-02-10 00:38:53

标签: java swing key-bindings

我一直在努力创建一个小程序,当用户按下某个键时会打印消息,但它不会打印消息。以下是我的代码:

    public static void key() {
    Main main = new Main();
    JFrame frame = new JFrame();
    JComponent component = frame.getRootPane();
    frame.getContentPane().add(main);
    System.out.println("adad");

    Action test = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("w has been pressed");
        }
    };
    component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0),"test");
    component.getActionMap().put("test", test);

}

没有错误,但是当按下“w”键时,不会调用actionPerformed。我究竟做错了什么?我不知道这是否相关,但这是主要的方法,也许我在这里做错了。

    public static void main(String[] args) {

    Main main = new Main();
    JFrame frame = new JFrame();
    frame.add(main);
    frame.pack();
    frame.setTitle("Test");
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setLayout(new BorderLayout());
    key();
    frame.setVisible(true);
    frame.add(frame, BorderLayout.CENTER);
}

1 个答案:

答案 0 :(得分:2)

您已经创建了第二个在屏幕上看不到的框架,其中的键绑定也被绑定了......

正如我昨天所说,密钥绑定必须在附加到可显示组件的组件(一个连接到本地对等组件的组件)上注册,然后才能工作

如果你尝试使用更像......

的东西
public static void key(JComponent component) {
    Action test = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("w has been pressed");
        }
    };
    component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "test");
    component.getActionMap().put("test", test);

}

并从JFrame方法传递main的实例或其中一个子组件(如contentPanepublic static void main(...)),它应该可以正常工作