public void blinkImage(Image e, ImageIcon f)
Not sure why you have two parameters. Is the Image the Image in the Icon?
Painting onto the Image will be permanent. So if it is the same Image as the Icon you can't restore the Icon to its original state.
displayTimer.start();
displayTimer.stop();
You can't invoke stop() right after you start() the Timer because the Timer will never fire. So all you need is the start().
Since you only want the Timer to fire once you would just use:
timer.setRepeats( false );
then you don't have to worry about stopping the Timer.
One approach is create a custom Icon with two states. Then you can toggle the state of the Icon:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DarkIcon implements Icon
{
private Icon icon;
private Color color;
private boolean dark = false;
public DarkIcon(Icon icon, Color color)
{
this.icon = icon;
this.color = color;
}
public void setDark(boolean dark)
{
this.dark = dark;
}
@Override
public int getIconWidth()
{
return icon.getIconWidth();
}
@Override
public int getIconHeight()
{
return icon.getIconHeight();
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y)
{
icon.paintIcon(c, g, x, y);
if (dark)
{
g.setColor(color);
g.fillRect(x, y, getIconWidth(), getIconHeight());
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI()
{
Icon icon = new ImageIcon("mong.jpg");
DarkIcon darkIcon = new DarkIcon(icon, new Color(0, 0, 0, 128));
JLabel label = new JLabel( darkIcon );
Action blink = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e2)
{
darkIcon.setDark( false );
label.repaint();
}
};
Timer timer = new Timer(2000, blink);
timer.setRepeats( false );
JButton button = new JButton("Blink Icon");
button.addActionListener( new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
darkIcon.setDark(true);
label.repaint();
timer.restart();
}
});
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(label);
f.add(button, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo( null );
f.setVisible(true);
}
}