0

This is the block of code that I am using to check for key presses. If I press the 'esc' key then the JFrame closes. But, if I press the 'space' bar the listener performs the last JButton pressed, NOT the specific button I am telling it to click. The doClick() also does not run unless a JButton was previously clicked.

addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent ke) { 
        if(ke.getKeyCode() == KeyEvent.VK_ESCAPE) {
            SaveScripts.saveData(player);
            dispose();
        }
        if(ke.getKeyCode() == KeyEvent.VK_SPACE) {
            center.buttonMenuAttack.doClick(); 
        }
    } 
});

Edit 1: Ok after some more testing, the issue seems to be that the listener breaks when anything in the frame is clicked.

  1. Program Launches
  2. Listener is active and working.
  3. Any component of the frame is clicked, the listener breaks

Edit 2: I ended up going with camickr's solution, its much easier to set up and I haven't had any issues with using it.

InputMap events = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actions = getRootPane().getActionMap();

events.put(KeyStroke.getKeyStroke("SPACE"), "click");
actions.put("click", new AbstractAction() { 
    public void actionPerformed(ActionEvent event) { 
        center.bAttack.doClick();
        } 
    });
events.put(KeyStroke.getKeyStroke("ESCAPE"), "click");
actions.put("click", new AbstractAction() { 
    public void actionPerformed(ActionEvent event) { 
        manage.bDataExit.doClick();
        } 
    });
  • [Welcome to Stack Overflow! What does your step debugger tell you?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Heri May 18 '18 at 15:55
  • 1
    You can try to insert `ke.consume()` line in your `if` statement for SPACE key. Probably this will help you. If not so please provide a [mcve] so we can also reproduce (and better understand) your problem. – Sergiy Medvynskyy May 18 '18 at 15:55
  • Don't use a KeyListener. A KeyEvent is only generated when the component has focus. Instead use [Key Bindings](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html). The Action can be invoked even when the component doesn't have focus. – camickr May 18 '18 at 19:07

1 Answers1

0

I figured out the issue. The Listener stopped working because when a button is clicked, it becomes the focused. I made a class that extends JButton so that all my buttons have the same behavior and added the following line of code to its constructors;

setRequestFocusEnabled(false);

This way, after a button is clicked the JFrame remains focused, allowing the Listener to behave as intended.