hello i am having trouble trying to understand swing timers. to help me could someone show me a simple flickering animation? i have looked arround on the internet but still
maybe this would help:
public class object{
Color color = Color.GREEN;
Timer timer;
public object() {
timer = null;
timer = new Timer(5000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (color.equals(Color.GREEN)) {
color = Color.RED;
timer.setDelay(2000);
} else {
color = Color.GREEN;
timer.setDelay(8000);
}
repaint();
}
});
timer.start();}}
First of all, you wouldn't hard-code your color use like this:
g.setColor(colors.ORANGE);
g.fillOval(160, 70, 50, 50);
Since this prevents all ability to change the color's state. Instead use a class field to hold the Color used, and call it something like ovalColor
:
private Color ovalColor = SOME_DEFAULT_COLOR; // some starting color
And then use that color to draw with:
g.setColor(ovalColor);
g.fillOval(160, 70, 50, 50);
I'd then give my class an array of Color or ArrayList<Color>
and an int index field:
private static final Color[] COLORS = {Color.black, Color.blue, Color.red,
Color.orange, Color.cyan};
private int index = 0;
private Color ovalColor = COLORS[index]; // one way to set starting value
Then in the Swing Timer's ActionListener I'd increment the index, I'd mod it by the size of the array or of the ArrayList, I'd get the Color indicated by the index and call repaint()
;
index++;
index %= COLORS.length;
ovalColor = COLORS[index];
repaint();
Also here's a somewhat similar example.
Also please look at the Swing Timer Tutorial.
I think a paint method would work.like this:
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.green);
g.filloval(30,40,50,50);
}