26.9. Review Questions

 
[Page 780]

24.5. Example: Flashing Text

The use of a Timer object to control animations was introduced in §14.6, "Animation Using the Timer Class." You can also use a thread to control animation. Listing 24.2 gives an example that displays a flashing text on a label, as shown in Figure 24.6.

Figure 24.6. The text Welcome blinks.

Listing 24.2. FlashingText.java
 1   import   javax.swing.*;  2  3   public class    FlashingText extends JApplet   implements   Runnable  {  4   private   JLabel jlblText =   new   JLabel(   "Welcome"   , JLabel.CENTER);  5  6   public   FlashingText() {  7      add(jlblText);  8    new   Thread(   this   ).start();  9    } 10 11  /** Set the text on/off every 200 milliseconds */  12    public void   run() {  13   try   { 14   while   (   true   ) { 15   if   (jlblText.getText() ==   null   ) 16            jlblText.setText(   "Welcome"   ); 17   else   18            jlblText.setText(   null   ); 19 20  Thread.sleep(   200   );  21        } 22      } 23   catch   (InterruptedException ex) { 24      } 25    } 26  } 

FlashingText implements Runnable (line 3), so it is a task class. Line 8 wraps the task in a thread and starts the thread. The run method dictates how to run the thread. It sets a text in the label if the label does not have a text (line 15), and sets its text null (line 17) if the label has a text. The text is set and unset to simulate a flashing effect.

You can use a timer or a thread to control animation. Which one is better? A timer is a source component that fires an ActionEvent at a "fixed rate." When an action event occurs, the timer invokes the listener's actionPerformed method to handle the event. The timer and event-handling run on the same event dispatcher thread. If it takes a long time to handle the event, the actual delay time between two events will be longer than the requested delay time. In this case, you should run event-handling on a separate thread. The next section will give an example to illustrate the problem and fix it by running the event-handling on a separate thread. In general, threads are more reliable and responsive than timers. If you need a precise delay time or a quick response, it is better to use a thread. Otherwise, using a timer is simpler and more efficient than using a thread. Timers consume fewer system resources than threads because timers run on the GUI event dispatcher thread so you don't need to spawn new threads for timers.


[Page 781]
 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net