问题
I am trying to code a simple animation like a moving circle. I have tried using getGraphics()
and work with that but it's not dynamic and it's painted for just one time
So please help me and guide me to code a dynamic graphic program.
I mean for example defining a function and every time when it called, it draws a line on a label.
回答1:
Here is how to make a growing rectangle:
public class MovingRectangle extends JPanel {
private Timer timer = new Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent event) {
rectWidth += 100;
repaint();
}
};
private int rectWidth = 100;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0, 0, 100. rectWidth);
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
public void reset() {
rectWidth = 100;
repaint();
}
}
回答2:
you should override the paintComponent(Graphic g)
.
This method is called every time the repaint()
is called, so you should periodic calling that method.
You should also set DoubleBuffering on true: setDoubleBuffered(true)
It will prevent possible flicker of your animation
来源:https://stackoverflow.com/questions/17770249/dynamic-graphic-programming-animation