我一直在试图制作一个小程序,当用户按下某个键时打印消息,但它不会打印该消息。以下是我的代码: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);
}
为了更好地帮助越早,张贴[MCVE](http://stackoverflow.com/help/ (最小完整可验证示例)或[SSCCE](http://www.sscce.org/)(简短的,独立的,正确的示例)。 – 2015-02-10 00:39:25