1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| /*
* BlinkingLabel.java 1.0
*
* Copyright (c) 1999 Emmanuel PUYBARET - eTeks.
* All Rights Reserved.
*
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// Classe de label clignotant en utilisant
// alternativement la couleur par défaut du label
// et une autre couleur passée au constructeur
public class BlinkingLabel extends JLabel
{
Color defaultColor; // Couleur par défaut du label
Color blinkingColor; // Couleur de clignotement
Timer timer; // Timer déclenchant des tics
// Constructeur
public BlinkingLabel (String text,
Color blinkingColor)
{
super (text);
this.blinkingColor = blinkingColor;
this.defaultColor = getForeground ();
// Création et lancement du timer
timer = createTimer ();
timer.start ();
}
// Méthode renvoyant un timer prêt à démarrer
private Timer createTimer ()
{
// Création d'une instance de listener
// associée au timer
ActionListener action = new ActionListener ()
{
// Méthode appelée à chaque tic du timer
public void actionPerformed (ActionEvent event)
{
// Inversion de la couleur
if (getForeground ().equals (defaultColor))
setForeground (blinkingColor);
else
setForeground (defaultColor);
}
};
// Création d'un timer qui génère un tic
// chaque 500 millième de seconde
return new Timer (500, action);
}
// Méthode main () d'exemple de mise en oeuvre.
// Utilisation : java BlinkingLabel
public static void main (String [] args)
{
// Création de deux labels
JLabel label1 = new BlinkingLabel ("Label 1", Color.blue);
JLabel label2 = new BlinkingLabel ("Label 2", Color.red.darker ());
// Ajout des labels à une fenêtre d'exemple
JFrame frame = new JFrame ("Exemple");
frame.getContentPane ().setLayout (new GridLayout (2, 1, 5, 5));
frame.getContentPane ().add (label1);
frame.getContentPane ().add (label2);
frame.pack ();
frame.show ();
}
} |
Partager