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.
- Program Launches
- Listener is active and working.
- 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();
}
});