I am having a problem using the repaint method in the following code.Please suggest how to use repaint method so that my screen is updated for a small animation.
This is my code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class movingObjects extends JPanel {
Timer timer;
int x = 2, y = 2, width = 10, height = 10;
public void paintComponent(final Graphics g) { // <---- using repaint method
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
g.setColor(Color.red);
g.drawOval(x, y, width, height);
g.fillOval(x, y, width, height);
x++;
y++;
width++;
height++;
}
};
new Timer(100, taskPerformer).start();
}
}
class mainClass {
mainClass() {
buildGUI();
}
public void buildGUI() {
JFrame fr = new JFrame("Moving Objects");
movingObjects obj = new movingObjects();
fr.add(obj);
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setSize(1300, 700);
}
public static void main(String args[]) {
new mainClass();
}
}
Don’t try to delay the actual painting. The component needs to be painted when it is asked to be painted.
Instead, use your timer to modify some state in
MovingObjects. In your case the state you want to change isx,y,widthandheight. When your timer fires, increment those values and callrepaint().Then in your
paintComponentsmethod, you would just use those values to paint the componentEdit
Not sure what you’re having trouble with, but calling repaint() is not difficult: