aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Key Listener Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Key Listener" Watch "Key Listener" New topic
Author

Key Listener

Justin Fox
Ranch Hand

Joined: Jan 24, 2006
Posts: 802
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


You down with OOP? Yeah you know me!
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
> by the way, the ship class extends JPanel..

Justin Fox
Ranch Hand

Joined: Jan 24, 2006
Posts: 802
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

Joined: Jun 09, 2003
Posts: 4632
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

Joined: Jan 24, 2006
Posts: 802
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Key Listener
 
Similar Threads
KeyEvent problem on a JPanel
KeyListener working randomly
Beginner game
ListSelectionListener getValueIsAdjusting()
Key listener or what?