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
| import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class LocalInnerClassTest
{
public static void main(String[] args)
{
TalkingClock clock = new TalkingClock();
clock.start(1000, true);
// keep program running until user selects "Ok"
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
/**
A clock that prints the time in regular intervals.
*/
class TalkingClock
{
/**
Starts the clock.
@param interval the interval between messages (in milliseconds)
@param beep true if the clock should beep
*/
public void start(int interval, final boolean beep)
{
// classs interne definissant un action listener
class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// affiche la date
Date now = new Date();
System.out.println("At the tone, the time is " + now);
// si un beep est souhaité (test du boolean beep) faire un beep
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
// instanciation d'un actionListener defini ci-dessus.
ActionListener listener = new TimePrinter();
// cree une instance Timer, c'est à dire un nouveau Thread
//(tache de fond si tu prefere...) qui au bout d'une durée de
// interval millisecond va activer le listener.
// cette instance comme tu la vu fonctionne en boucle.
Timer t = new Timer(interval, listener);
// l'instance Timer est initialisé mais non "lancée"
// cad elle ne compte pas le temps.
// la methode start lui dit de commencer.
t.start();
}
private int interval; // temps entre les beep
private boolean beep; // faire un beep ou non
} |
Partager