Be a Supporter!

stuck on java animation problem.

  • 238 Views
  • 0 Replies
New Topic Respond to this Topic
ronk
ronk
  • Member since: Dec. 23, 2007
  • Offline.
Forum Stats
Member
Level 13
Programmer
stuck on java animation problem. 2012-06-19 16:54:36 Reply

i have a problem that has completely got me and i have not idea how it is happening.
i have a class that extends a jPanel and uses a timer but for some reason inside the paint components method it won't read variables correctly.

here is the souce code

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Stage extends JPanel{
	
	public Ball ball = new Ball();
	JFrame frame = new JFrame();
	Container contentPane = frame.getContentPane();
	
	Timer animationTimer = new Timer(1000, new ActionListener(){
		public void actionPerformed(ActionEvent e){
			contentPane.repaint();
			ball.setX(ball.x + 10);
			System.out.println("timer says:" + ball.x);
		}
	});
	
	
	public void open(){
	    frame.setTitle("DrawRect");
	    frame.setSize(300, 200);
	    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    contentPane.add(new Stage());
	    frame.setVisible(true);
	    animationTimer.start();
	}
	
	@Override
	public void paintComponent(Graphics g){
		super.paintComponents(g);
		System.out.println("painter says: " + ball.x);
		g.drawImage(ball.getImage(), ball.x, ball.y, ball.width, ball.height, null);
	}
}

and the output says:

painter says: 10
painter says: 10
timer says:20
painter says: 10
timer says:30
painter says: 10
timer says:40
painter says: 10
timer says:50
painter says: 10

i have no idea what is causing this, any help would be appreciated.