0

I am trying to get a simple KeyBindings program to work. I followed the instructions from java doc, and tried to test the stuff answered in this (Java Key Bindings Not Working) thread, but i just cant get it to work. I want to output "test" to the console when "F1" is pressed. Can anyone spot my mistake?

JFrame frame = new JFrame("shit");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

JPanel jPanel = new JPanel();
jPanel.getInputMap().put(KeyStroke.getKeyStroke("F1"), "focus");
jPanel.getActionMap().put("focus", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("test");
    }
});

frame.add(jPanel);
Community
  • 1
  • 1
Elias Fyksen
  • 879
  • 9
  • 12

1 Answers1

-1
  1. Components should be added to the frame BEFORE the frame is made visible.

  2. If that doesn't work then use a different InputMap. Read the section from the Swing tutorial on How Key Bindings Work to see how the 3 different InputMaps are used.

camickr
  • 321,443
  • 19
  • 166
  • 288