Jump to content

I have a piece of code below from my program and I'm trying to set up a key listener so that when the keys right, left, up, and down are pressed, it removes the corresponding jbutton (_b1, _b2, etc) from the jpanel (_panel). I'm not getting any compilation errors and the bottom section of the if statement does indeed remove the jbutton, I just need help as to how to implement the key listener prior to that.

 

public void keyPressed(KeyEvent e) {
 
   int key = e.getKeyCode();
 
   if (key == KeyEvent.VK_LEFT) {
       _panel.remove(_b1);
   }
 
   if (key == KeyEvent.VK_RIGHT) {
    _panel.remove(_b2);
   }
 
   if (key == KeyEvent.VK_UP) {
    _panel.remove(_b3);
   }
 
   if (key == KeyEvent.VK_DOWN) {
    _panel.remove(_b4);
   }
 
}
Link to comment
https://linustechtips.com/topic/487343-java-key-listener-help/
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×