I am painting vehicle objects that I defined using the paintComponent(). Because the vehicles can move, I implement ActionListener and set a Timer() to trigger.
As a result, my vehicles can move. But it is kind of "shaking". When I keep resizing the window to call the paintComponent(), the movement becomes smooth. When I do not resize the window (not calling paintComponent), it gets skaking again. Why? How to fix it?
public class VehiclesComponent extends JComponent implements ActionListener{
private Vehicle[] vehicles;
private Timer timer;
public VehiclesComponent(int n){
vehicles = Vehicle.generateVehicle(n);
timer = new Timer(5,this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for (int i=0; i<vehicles.length; i++) {
vehicles[i].draw(g2);
}
// may change later
timer.start();
}
@Override
public void actionPerformed(ActionEvent e){
//check collision in here
for (Vehicle v : vehicles) {
if (Vehicle.intersectsOther(v, vehicles)) {
v.collisionSideEffect();
}
}
//move all in here
for (Vehicle v : vehicles ) {
v.move();
}
repaint();
//?? repaint slower than paintComponent
}
}
Start by taking a look at Painting in AWT and Swing. Remember,
repaint
is only a suggest made to theRepaintManager
, theRepaintManager
may choose to consolidate multiplerepaint
calls into a smaller number of actual paint events.Make sure you are calling
super.paintComponent
, otherwise you will end up with no end of strange paint artifacts.Don't, directly or indirectly, modify the state of the component or ant other components from within any paint method, this will result in a new
repaint
request been made, which could lead to a cycle of paint events which could consume your CPU cycles. This means, don't calltimer.start()
!Without a runable example to go by, I hobbled this together. Now this is animating 10, 000 individual
Vehicle
s (rectangles), so it's massively over kill, but it should provide the point...(the gif is only running at 7fps, not your 200fps)
You could also take a look at this example which renders upwards of 4500 images in random directions and demonstrates some optimisation techniques.
You can also take a look at this example which is capable of animating both in direction and rotation, upwards of 10, 000 images