This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Adding a KeyListener to a JLabel?

 
Josh Rodrigues
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I'm making a game and I'm trying to add a KeyListener to a JLabel which contains an ImageIcon. Every time I press the up, down, right or left arrow key, they print out what I want it to print out, but do not do the action I wish for them to perform. Here's my code:



I tried adding the requestFocus() method and a few different ways of creating the keyPressed(KeyEvent e) method. Help is appreciated. Thanks.
 
Olivier Legat
Ranch Hand
Posts: 176
Chrome Mac Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Josh,

I don't see why anything should happen other than printing the text. In the keyPressed methods you are incrementing/decrementing the variables xPos and yPos, which are not ever used locally (other than in keyPressed). Unless these variables are used elsewhere, these variations are useless.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic