I am having a problem using both ActionListener and KeyListener in the same class that extends JPanel for a basic game i am working on. For the KeyListener only the KeyPressed class is implemented and is implemented as such.
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()){
case 37:{
grid.moveSelectedWest();
break;
}
case 38:{
grid.moveSelectedNorth();
break;
}
case 39:{
grid.moveSelectedEast();
break;
}
case 40:{
grid.moveSelectedSouth();
break;
}
}
repaint();
e.consume();
}
I have a button set to reset my game board and uses the action preformed method. Both the initialization of the button and ActionPreformed method are below.
private JButton resetButton = new JButton("Reset");
...
this.resetButton.setVerticalTextPosition(AbstractButton.CENTER); this.resetButton.setHorizontalTextPosition(AbstractButton.CENTER);
this.resetButton.setLocation(10, 10);
this.resetButton.setSize(70, 30);
this.resetButton.setActionCommand("Reset");
this.resetButton.addActionListener(this);
add(this.resetButton);
...
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "Reset"){
grid.reset();
repaint();
}
}
Everything works perfectly until i click the reset button. The board resets correctly but after that the KeyPressed method does not get called no matter what keys i press. I cant figure out how to make the KeyListener continue to work after reset button is pressed. Thanks in advance for the help!