Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Key Listener

 
Justin Fox
Ranch Hand
Posts: 802
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok here is a snippet of my code in one of my JPanel constructors...



ok for some reason, when I run the JFrame, the directional keys do not
respond..

i've tried key adapter...
and ive tried..



then defining an inner class 'ShipListener' that imple. KeyListener

umm, what I have is different JPanels, that represent ships on a
game board in the game "battleship".

now when i click on a "ship", i set a 'currentShip' object equal to that
ship Clicked on, and when i press, up, down, right, left, i want that
particular 'currentShip' to move.

but I did the following:



the only reason i called repaint, is because i printed out
CurrentShip.getName() in the paintComponent() and it does
get updated each time you click on each different kind of ship..

aircraft carrier
battleship
cruiser
2 destroyers
2 submarines

now in the shipListener I WAS doing the following until I changed
it to the above, so I could see if i could even get the arrow keys
to respond...

ok:



the example above is just little of what i had, i would 'if' each
'ship.getName()' for each ship object, in each case in the switch statement, for each direction.


if anyone could help me understand what i am doing wrong...
oh, and in the above example, I added a KeyListener to each
individual ship object.

by the way, the ship class extends JPanel..

Justin Fox
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> by the way, the ship class extends JPanel..

 
Justin Fox
Ranch Hand
Posts: 802
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well I added the setFocusable(true); to my main JPanel constructor,
not the ship panel, just to see if the

"up pushed" etc...

would print to the console, and it still didn't work...

thanks,


Justin
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
run this, nothing happens



uncomment the line, recompile/rerun it will work
(may have to click into the inner panel first,
but unlikely with no other components)
 
Justin Fox
Ranch Hand
Posts: 802
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
lol, i figured out what it was, when i clicked on log in,
it set the frame to focusable, so it was interfering with the JPanel

Thank dude...

Justin
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic