Java
Swing - GUIs LESSON NOTE TIMERS Timers
are very simple objects. You provide
an amount of time and then start them.
In a separate thread, they wait the specified amount of time and then
trigger an action event. They then trigger
again after that same amount of time. If
needed, you can easily stop the timer and restart it as needed. EXAMPLE - TIMER COUNTER Here
is a simple example of a GUI containing only a text field. Inside the text field is the number
zero. Every second (1000
milliseconds), the timer triggers an event which leads to the number in the text
field getting increased. The
code is below. The lines related to
the Timer object are highlighted.
EXAMPLE – APPEARING BUTTONS Here
is an example of an empty GUI that has a button added to it every 2
seconds. This is all done by a Timer
object that triggers an event every 2000 milliseconds. And, in the actionPerformed(ActionEvent e) method, we add a button to the GUI and restart
the timer. The
code is below. Notice that the
Container cp is a datafield
so that we can access it from the actionPerformed() method lower down.
EXAMPLE
3 – ALPHABET COUNTDOWN In
this example, a counter starts at 15 and gradually goes down to 0. The user
has to type the alphabet in in order to win this simple game. The timer update the countdown. Also, the time is stopped once the
countdown is at zero. The
code is below.
|
|||
|