Java Reference
In-Depth Information
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(10, 30, 50, 50);
}
}
17.
A
Timer
is an object that can fire an
ActionListener
event at regular intervals.
A
Timer
can be used to animate a panel by having its
ActionListener
change
the state of the panel in some way and then repaint it.
18.
// An animated panel that draws a red and blue circle.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RedCirclePanel2 extends JPanel {
private boolean red;
public RedCirclePanel2() {
red = true;
Timer timer = new Timer(1000, new ColorListener());
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (red) {
g.setColor(Color.RED);
} else {
g.setColor(Color.BLUE);
}
g.drawOval(10, 30, 50, 50);
}
private class ColorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
red = !red;
repaint();
}
}
}
Search WWH ::
Custom Search