To stop a thread, you assign a signaling value to a variable tested inside
the run
method. In the following, for example, a mouse listener
assigns true
to the stopper
variable, which is tested each
time that run
loops inside the marquee thread. As soon as stopper
is true, run
returns. Thus, you can stop the marquee by clicking on
it.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Marquee extends JComponent { MarqueeThread thread; String message; int position, drop, initialPosition, delta, messageWidth; Font messageFont = new Font("TimesRoman", Font.BOLD, 24); boolean ready = false; boolean stopper = false; public Marquee (String s) { message = s; addMouseListener(new MarqueeListener()); thread = new MarqueeThread(this); thread.start(); } // Definition of decrementPosition as in Segment 886 // Definition of paint as in Segment 886 class MarqueeListener extends MouseAdapter { public void mouseClicked(MouseEvent e) { stopper = true; } } class MarqueeThread extends Thread { private Marquee marquee; public MarqueeThread (Marquee c) { marquee = c; } public void run () { while (true) { if (stopper) {return;} ChangeHandler changeHandler = new ChangeHandler(marquee); SwingUtilities.invokeLater(changeHandler); try{sleep(200);} catch (InterruptedException e) {} } } } class ChangeHandler implements Runnable { private Marquee marquee; public ChangeHandler (Marquee c) { marquee = c; } public void run() { marquee.decrementPosition(); } } public Dimension getMinimumSize() {return new Dimension(300, 50);} public Dimension getPreferredSize() {return new Dimension(300, 50);} }