Results 1 to 5 of 5
Thread: Keylistener
- 09-19-2012, 03:23 AM #1
Member
- Join Date
- Oct 2010
- Posts
- 41
- Rep Power
- 0
Keylistener
Hey guys I'm trying to program a game of snake but my keylistener to change directions isn't working. I've set it up like all the examples I've seen online and I can't see what I'm missing. I've made a SSCCE for just the up direction (either 'w' or the up arrow key):
Java Code:import java.applet.*; import java.awt.*; import java.awt.event.*; public class GameSSCCE extends Applet implements KeyListener{ private String direction; public void init(){ setSize(300,100); direction = "No keys have been pressed."; addKeyListener(this); } public void paint(Graphics g){ g.drawString(direction, 60, 60); } public void keyPressed(KeyEvent e) { if(e.getKeyChar() == KeyEvent.VK_W || e.getKeyChar() == KeyEvent.VK_UP){ direction = "Up."; } repaint(); } public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} }
- 09-19-2012, 08:25 PM #2
Re: Keylistener
KeyEvent.VK_W is a key code, not a key char.
Use the getKeyCode() method instead of getKeyChar()
- 09-20-2012, 06:20 PM #3
Member
- Join Date
- Oct 2010
- Posts
- 41
- Rep Power
- 0
Re: Keylistener
Thanks! That was part of the problem. another part was that the applet did not have the keyboard focus originally so I had to click on it before typing. I put in setFocusable(true); and that fixed it.
Last edited by dyelax; 09-20-2012 at 06:59 PM.
- 09-20-2012, 06:41 PM #4
Re: Keylistener
I believe you can use the requestFocus(); method. Add it to the paint method.
- 09-20-2012, 07:06 PM #5
Similar Threads
-
Need help with KeyListener
By McDucky in forum New To JavaReplies: 3Last Post: 09-16-2012, 05:35 PM -
Help with KeyListener
By armyson in forum New To JavaReplies: 1Last Post: 11-25-2011, 12:56 PM -
Help with keylistener?
By Kaizo in forum New To JavaReplies: 4Last Post: 12-11-2010, 12:55 AM -
keyListener not doing anything
By imorio in forum AWT / SwingReplies: 10Last Post: 08-17-2010, 10:46 PM -
KeyListener - Is this what I need?
By dbashby in forum New To JavaReplies: 26Last Post: 04-18-2009, 04:14 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks