Reputation: 103
I have been trying to make a small program that prints messages when the user presses a key, however it doesn't print the message. The following is my code:
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);
}
There are no errors but when the "w" key is pressed actionPerformed isn't called. What am I doing wrong? I don't know if this is relevant, but here is the main method, maybe i'm doing something wrong here.
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);
}
Upvotes: 0
Views: 252
Reputation: 347334
You've created a second frame which is not visible on the screen, which the key bindings are bound too...
As I said yesterday, the key bindings must be registered with a component which is attached to a displayable component (one which is attached to a native peer) before they will work
If you try using something more like...
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);
}
and pass either the instance of JFrame
or one of it's child components (like main
or the contentPane
) from your public static void main(...)
method, it should work
Upvotes: 2