Ever need to make an image blink continuously to signal for some kind of incoming activity? Well....I'm going to share a simple sample on how to do that.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
public class BlinkingLabel extends JLabel implements Runnable{
private boolean show=false,blink=true;
private Icon iconImg;
private JLayeredPane parent;
public BlinkingLabel(Icon icon, JLayeredPane pane)
{
super(icon);
this.iconImg = icon;
this.parent = pane;
this.setVisible(true);
new Thread(this).start();
}
public void run() {
while (blink) {
show=!show;
if(show)
parent.moveToFront(this);
else
parent.moveToBack(this);
repaint();
try { Thread.sleep(400); } catch (Exception e) { }
}
}
public boolean isBlink() {
return blink;
}
public void setBlink(boolean blink) {
this.blink = blink;
}
}
|
The concept of this
BlinkingLabel class is to pass in a secondary image along with another
JLayeredPane object which is the main container for the original image. That is to say we are actually making use of the 2 images one of which shows the original state and the other is actually the lighted up state. Upon instantiating an object with this class, the secondary image will be toggled on and off with a variable of 400 milliseconds. You can tweak this setting if you wish it to be faster or slower.
Of course this is just one of the ways to make an image blink repeatedly. I'm sure there are other methods like overriding the
paintComponent method or something.
If you've enjoyed this article, drop me a comment!
Related Posts by Categories
This entry was posted
on Monday, September 29, 2008
at Monday, September 29, 2008
and is filed under
java,
programming
. You can follow any responses to this entry through the
comments feed
.