Results 1 to 2 of 2
Thread: Problem with key listener
- 03-14-2011, 12:20 PM #1
Member
- Join Date
- Mar 2011
- Posts
- 1
- Rep Power
- 0
Problem with key listener
Hey, Im new to java and new to these forums and im having a problem with my code.
Im trying to make a simple 2d game but till now it hasnt really been working out much =\...
I'm trying to add 3 classes as listeners 1 is mouse motion class, mouse click and keyboard class.
The GUI class is the first one to run (after my frame class to run the JFrame, the GUI class is the JPanel) The constructor of my GUI class looks like this:
all the var's are declaired in the class..Java Code:p = new Player(); mm = new MouseMotion(p); key = new Keyboard(p); addMouseMotionListener(mm); addKeyListener(key); refresh = new Timer(5, this); refresh.start();
the mouseMotionListener works perfectly but the keyboard class doesnt (the mouse clicked i havnt implemented yet.). This is my keyboard class:
When i press a button the text "TEST" doesnt display in the terminal so the listener isnt doing its job...Java Code:import java.awt.event.*; public class Keyboard implements KeyListener { Player p; public Keyboard(Player p) { this.p = p; } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { System.out.println("TEST"); int key = e.getKeyCode(); if(key == KeyEvent.VK_RIGHT) { p.moving = 1; } if(key == KeyEvent.VK_LEFT) { p.moving = -1; } } public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); if(key == KeyEvent.VK_RIGHT) { p.moving = 0; } if(key == KeyEvent.VK_LEFT) { p.moving = 0; } } }
What am i doing wrong here and how could i fix this?
[EDIT] I'v tried letting the class extends KeyAdapter but it also doesnt work
Thanks for taking the time to read my problem :)
- 03-14-2011, 02:02 PM #2
For a KeyListener to do its stuff, the component to which it is added must have the focus.
If this is a Swing GUI, the recommended approach is to use key bindings instead.
How to Use Key Bindings (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)
db
Similar Threads
-
Problem in action listener
By cool in forum AWT / SwingReplies: 4Last Post: 11-16-2010, 07:44 AM -
problem with browser Listener in linux
By chakribobby in forum SWT / JFaceReplies: 0Last Post: 06-14-2010, 03:54 PM -
JColorChooser modeless - Event Listener problem
By siamino in forum New To JavaReplies: 1Last Post: 04-14-2009, 12:39 AM -
#key listener problem
By mij1_7 in forum New To JavaReplies: 2Last Post: 02-14-2009, 09:02 PM -
Regarding Listener
By adeeb in forum AWT / SwingReplies: 2Last Post: 06-10-2008, 02:00 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks