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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class BlinkingComponent {
private final JComponent component;
private final Timer timer;
private BlinkingTask timerTask;
public BlinkingComponent(JComponent component) {
this.component = component;
this.timer = new Timer();
}
public final void start(final long period) {
start(null, period);
}
public final void start(final Color blinkingColor, final long period) {
start(blinkingColor, component.getForeground(), period);
}
public final synchronized void start(final Color blinkingColor,
final Color color, final long period) {
if (timerTask != null) {
stop();
}
timerTask = new BlinkingTask(blinkingColor, color);
timer.scheduleAtFixedRate(timerTask, period, period);
}
public final synchronized boolean isBlinking() {
return timerTask != null;
}
public final synchronized void stop() {
if (timerTask != null) {
timerTask.cancel();
component.setForeground(timerTask.foregroundColor);
timerTask = null;
}
}
private class BlinkingTask extends TimerTask {
public final Color foregroundColor;
public final Color blinkingColor;
private boolean blink;
public BlinkingTask(Color blinkingColor, Color color) {
this.foregroundColor = color == null ? component.getForeground() : color;
this.blinkingColor = blinkingColor;
}
@Override
public void run() {
if (blink) {
component.setForeground(foregroundColor);
} else if (blinkingColor == null) {
component.setForeground(component.getBackground());
} else {
component.setForeground(blinkingColor);
}
blink = !blink;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello!", JLabel.CENTER);
final JButton button = new JButton("Stop");
frame.add(label);
frame.add(button, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
BlinkingComponent blinkComponent = new BlinkingComponent(label); // si label est le label que tu as dans ton interface ça fonctionnera
button.addActionListener(new ActionListener() {
boolean blink = true;
@Override
public void actionPerformed(ActionEvent e) {
if (blink) {
blinkComponent.stop();
button.setText("Start");
} else {
blinkComponent.start(Color.RED, 500);
button.setText("Stop");
}
blink = !blink;
}
});
blinkComponent.start(500); // période = 500 ms
}
} |
Partager