我一直在試圖製作一個小程序,當用戶按下某個鍵時打印消息,但它不會打印該消息。以下是我的代碼: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