CIS 260 Using threads

Now that we have seen the problem and been told that the solution (well... a solution) is threads, the question becomes: How do we use threads to make our user interface more responsive? The next example shows one approach.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TThread3 extends JFrame {
   Counter ctr = null;
   JButton btnStart, btnStop;
   JLabel lblNum;
   int count = 0;
   boolean running = false;

   private class Counter extends Thread {
      public void run() {
         while (count++ < 10000) {
            if (!running) break;
            lblNum.setText(Integer.toString(count));
            try {
               sleep(100);
            } catch (InterruptedException e) {
               System.out.println("Application Interrupted");
            }
         }
      }
   }

   public static void main(String[] args) {
      TThread3 app = new TThread3();
      app.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
      app.init();
      app.pack();
      app.setVisible(true);
   }

   public void init() {
      Container c = this.getContentPane();
      c.setLayout(new GridLayout(3,1));
      lblNum = new JLabel("Running Total");
      btnStart = new JButton("Start");
      btnStop = new JButton("Stop");
      btnStop.setEnabled(false);

      btnStart.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            btnStart.setEnabled(false);
            btnStop.setEnabled(true);
            running = true;
            ctr = new Counter();
            ctr.start();
         }
      });

      btnStop.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            if (ctr != null) {
               running = false;
               btnStart.setEnabled(true);
               btnStop.setEnabled(false);
            }
         }
      });

      c.add(lblNum);
      c.add(btnStart);
      c.add(btnStop);
   }
}

Previous: creating threads

Next: the Runnable interface