Movement Problem

After reading some posts about smoothing key movements, I tried testing it, but I can’t get it to work. Can anyone tell me what I’m doing wrong?
Thanks.


class Test extends JFrame 
{
	private final int CANVAS_WIDTH = 500;
	private final int CANVAS_HEIGHT = 500;
	private int x;
	private int y;
	private boolean left;
	private boolean right;
	private boolean up;
	private boolean down;

	public Test()
	{
		this.setSize( CANVAS_WIDTH, CANVAS_HEIGHT );
		this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		this.setBackground( Color.gray );
		
		this.addKeyListener( new KeyAdapter()
							 {
							 	public void keyPressed( KeyEvent e )
							 	{
							 		if( e.getKeyCode() == KeyEvent.VK_LEFT )
							 			left = true;
							 		if( e.getKeyCode() == KeyEvent.VK_RIGHT )
							 			right = true;
							 		if( e.getKeyCode() == KeyEvent.VK_UP )
							 			up = true;
							 		if( e.getKeyCode() == KeyEvent.VK_DOWN )
							 			down = true;
							 		move();	
							 	}
							 	
							 	public void keyReleased( KeyEvent e )
							 	{
							 		if( e.getKeyCode() == KeyEvent.VK_LEFT )
							 			left = false;
							 		if( e.getKeyCode() == KeyEvent.VK_RIGHT )
							 			right = false;
							 		if( e.getKeyCode() == KeyEvent.VK_UP )
							 			up = false;
							 		if( e.getKeyCode() == KeyEvent.VK_DOWN )
							 			down = false;
							 	}	
							 } );
							 
		x = CANVAS_WIDTH/2 - 15; 
		y = CANVAS_HEIGHT/2 - 15;
		this.setVisible( true );
	}
	
	
	private void move()
	{
		if( left ) 
		{
			x -= 3;
		} 	
		if( right ) 
		{
			x += 3;
		}
		if( up )
		{
			y -= 3;
		}
		if( down )
		{
			y += 3;
		}
		
		repaint();
	}
	
	public void paint( Graphics g )
	{
		g.clearRect( 0, 0, 500, 500 );
		g.setColor( Color.black );
		g.fillRect( x, y, 30, 30 );
	}
}

Well… I dont see anything that actually calls move() for one, Where is your game loop?

Also, it is very hard to get any kind of smooth animation calling repaint() because painting based on repaint(0 is asynchronous and happens at some random time after rerpaint() is called. Even worse, 3 calls to repaint() may not result in 3 calls to paint() as AWT will combine repaints() for efficiency.

Edit: Now I see it, its in your KB handler. Ick. Nasty. Bad.

You need a real game-loop, you arent going to get anything at ALL controlled trying to drive it all off of AWT input events. Ontop of the asynchronicity of repaint() already mentioned, the mouse events themselves are asynchronous and uncontrolled.

Smoothness in animation is a matter of control of your time base. You need to drive the animation off of a “near real-time” loop that monitors physical time.

This is all basic game stuff. Forget all you know about AWT and Swing apps. It doesnt apply. Any form of animation is VERY different from an event driven GUI app.