键绑定不起作用 - 摆动

Keybindings not working - swing

我一直在尝试制作一个小程序,在用户按下某个键时打印消息,但它不打印消息。以下是我的代码:

    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);
}

您已经创建了第二个框架,它在屏幕上不可见,键绑定也被绑定...

正如我昨天所说,键绑定必须在附加到可显示组件(附加到本机对等组件)的组件中注册才能工作

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

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);

}

并从您的 public static void main(...) 方法传递 JFrame 的实例或其子组件之一(如 maincontentPane),它应该可以工作