Ultimate Gear War
Join the alien war, prepare your gear and protect your base at all cost!
4.21 / 5.00 14,525 Viewsi 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.