Results 1 to 3 of 3
Thread: KeyListener Graphics Problem
- 05-25-2011, 09:13 PM #1
Member
- Join Date
- May 2011
- Posts
- 1
- Rep Power
- 0
KeyListener Graphics Problem
Hi there,
I'm pretty new to Java but interested in eventually making games of some kind. Right now I'm struggling with the KeyListener. I'm trying to set up basic WASD-like movement, but the graphics don't seem to respond. KeyPressed is supposed to change the x-coord of a component, but no visual movement happens. However, the System.out.println returns changing coordinates, which means that the Listener itself is working, right? Any help would be appreciated, thanks.
Java Code:public class MoveViewer { static JFrame frame=new JFrame("Move Viewer"); static JPanel panel=new JPanel(); static int yPos=10; static int xPos=10; static MoveComponent mc=new MoveComponent(xPos,yPos); public static void main(String[] args) { frame.setSize(600,600); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel.add(mc); panel.setLayout(new OverlayLayout(panel)); frame.add(panel); panel.setFocusable(true); panel.requestFocus(); class MoveListener implements KeyListener { public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { int key=e.getKeyCode(); if(key==KeyEvent.VK_RIGHT) { xPos=xPos+50; mc=new MoveComponent(xPos,yPos); System.out.println(""+xPos+", "+yPos); panel.repaint(); } } public void keyReleased(KeyEvent e) { } } MoveListener ml=new MoveListener(); panel.addKeyListener(ml); frame.setVisible(true); } }
- 05-25-2011, 10:59 PM #2
What does panel's paintComponent method do?
What code is supposed to cause the movement?
What is supposed to happen to the object pointed to by mc in the listener?Last edited by Norm; 05-25-2011 at 11:01 PM.
- 05-26-2011, 04:07 AM #3
Senior Member
- Join Date
- Jul 2009
- Posts
- 1,143
- Rep Power
- 5
This DOES NOT add a component to the GUI. All it does is create a new Object in memory.Java Code:mc=new MoveComponent(xPos,yPos);
If you want to create a new component then you would do:
However even that code is wrong because now you would have 2 components on the panel.Java Code:mc=new MoveComponent(xPos,yPos); panel.add( mc ); panel.revalidate(); panel.repaint();
The proper way to do this is to just invoke mc.setLocation(...) to move the existing component to a new location.
Similar Threads
-
JTextArea's KeyListener' overloaded method works only once... what can be a problem?
By nikkka in forum New To JavaReplies: 2Last Post: 05-11-2011, 06:29 PM -
Problem with Keylistener, some help pls
By syon in forum AWT / SwingReplies: 1Last Post: 01-21-2011, 01:31 AM -
AWT KeyListener Problem
By plm-pusik in forum New To JavaReplies: 15Last Post: 11-10-2010, 03:38 PM -
KeyListener problem
By siyi90 in forum AWT / SwingReplies: 7Last Post: 02-08-2010, 10:16 AM -
Problem with KeyListener in Jtable
By sandeepsai17 in forum New To JavaReplies: 0Last Post: 06-30-2009, 10:14 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks