Results 1 to 2 of 2
Thread: Help with KeyListener
- 11-25-2011, 06:03 AM #1
Member
- Join Date
- Nov 2011
- Posts
- 3
- Rep Power
- 0
Help with KeyListener
Hi, I am trying to write a program that basically moves a man across the screen with the 'W' 'A' 'S' and 'D' keys. I have been working for hours trying to figure out what is wrong with my code but I cannot. For some reason my keyListener is never picking up that a key is being pressed.
Here is the code:
Java Code:package edu.truman.mrsamt; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import javax.swing.JComponent; import javax.swing.JTextField; public class SceneComponent extends JComponent { private ArrayList<ButtonShape> shapes; private MoveableMan person; private Rectangle boundingBox; public SceneComponent() { shapes = new ArrayList<ButtonShape>(); this.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { System.out.println("Key is pressed!"); if (e.getKeyChar() == 'w') { System.out.println("A key is pressed!"); person.translate(0, 1); boundingBox.translate(0, 1); repaint(); } else if (e.getKeyChar() == 'a') { person.translate(-1, 0); boundingBox.translate(-1, 0); } else if (e.getKeyChar() == 's') { person.translate(0, -1); boundingBox.translate(0, -1); repaint(); } else if (e.getKeyChar() == 'd') { person.translate(1, 0); boundingBox.translate(1, 0); repaint(); } } }); } public void add(MoveableMan p) { person = new MoveableMan(p.getX(), p.getY(), p.getHeight()); boundingBox = new Rectangle(p.getX(), p.getY()); } public void add(ButtonShape s) { shapes.add(s); repaint(); } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; person.draw(g2); for(ButtonShape s: shapes) { s.paintComponent(g2); } } }Last edited by Norm; 11-25-2011 at 12:54 PM. Reason: added code tags
- 11-25-2011, 12:56 PM #2
Re: Help with KeyListener
Does the component with the key listener have the focus? Is that component able to get the focus?
Read the API doc for the JComponent class. It has several links to the tutorial about the Focus subsystem and about how to handle keystrokes.
Java Platform SE 6
Similar Threads
-
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 -
KeyListener Example
By Java Tip in forum SWTReplies: 0Last Post: 07-11-2008, 04:46 PM -
how to add a KeyListener
By leonard in forum New To JavaReplies: 1Last Post: 08-06-2007, 04:44 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks