11.11.2009 Java Swing: Fensterhintergrund blinken

Zur Visualisierung von Ereignissen, z.B. Warnungen – oder in meinem aktuellen Projekt zur Anzeige eines sich wiederholenden, zeitgesteuerten Ereignisses – kann man den Hintergrund von Java-Swing Fenstern ganz einfach kurz aufblinken lassen:

import java.awt.*;
import javax.swing.*;

public class Flasher
{
    private Component component;
    private int flashMS;
    private Color flashColor;

    /** Create a flasher for 'component' which flashes 
     *  in 'color' for 'flashMS' milliseconds.
     */
    public Flasher(Component component,
                         Color color, int flashMS) {
        this.component = component;
        this.flashMS = flashMS;
        this.flashColor = color;
    }

    /// flash the specified window in 'delayMS' milliseconds
    public void trigger(final int delayMS) {
        new Thread() {

            @Override
            public void run() {
                Color normalColor = component.getBackground();
                try {
                    sleep(delayMS);
                    setBackground(flashColor);
                    Thread.sleep(flashMS);
                } catch (InterruptedException e) {
                    // ignore
                } finally {
                    setBackground(normalColor);
                }
            }

        }.start();
    }

    private void setBackground(final Color color) {
        SwingUtilities.invokeLater( new Runnable() {

          @Override
           public void run() {
               component.setBackground(color);
           }
        });
    }

    /// just sample code
    public static void main(String[] args)
                throws InterruptedException {
        JFrame frame = new JFrame("Flasher");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setSize(600, 400);
        frame.setVisible(true);

        Flasher flasher =
                new Flasher(frame.getContentPane(), Color.RED, 100);
        flasher.trigger(3000);
    }
}