In its swing library, Java provides a timer class that can be used to animate controls. For example, one could create a blinking label as follows:
class BlinkLabel extends JLabel {
private static final int BLINK_INTERVAL = 500;
public BlinkLabel(String text) {
super(text);
ActionListener listener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(!isVisible());
}
};
Timer timer = new Timer(BLINK_INTERVAL, listener);
timer.start();
}
}
The problem with this approach is that the label will continue blinking even after its parent window has been disposed. Also, the label will never be garbage collected, since the timer still maintains a reference to it.
Here's the proper way to do it.
class BlinkLabel extends JLabel {
private static final int BLINK_INTERVAL = 500;
private Timer timer;
private ActionListener listener;
public BlinkLabel(String text) {
super(text);
listener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(!isVisible());
}
};
}
public void addNotify() {
super.addNotify();
timer = new Timer(BLINK_INTERVAL, listener);
timer.start();
}
public void removeNotify() {
super.removeNotify();
timer.stop();
timer.removeActionListener(listener);
timer = null;
}
}