0

I am trying to create a simple Timer with a Start Stop and Reset Button. I am new to using the Threads and ActionListeners. I have this working, and can get my timer to begin, and my button to change text from start to stop. But after that i am stuck. I need to stop the timer, and then start it again, if i press the start button. Then of course reset turns it back to zero. I do not want to use java.util.Timer, i just want to use threads. How would i get my thread once started, to pause and then resume. I tried using the built in methods, but i could not get it to compile right.

import javax.swing.*;
import java.awt.Font;
import java.lang.String;
import java.awt.*;

public class Timer extends JPanel {

  // Here are the fields from below!

  private static JLabel label = new JLabel("   0.00 seconds");
  private static javax.swing.JButton start = new javax.swing.JButton("Start");
  private static javax.swing.JButton reset = new javax.swing.JButton("reset");

  /**
   * Here is the Timer method- Begins with JLabel with medium alignment.
   */
  public Timer() {
    //new Thread(this).start();
    //label = new JLabel("   0.00 Seconds");
    //this.label = label;
    reset();
  }


  /**
   * Here is the Reset method- pressing this button from below will 
   * stop the thread and reset the text.
   */
  public static void reset() {
    label.setFont(new Font("Arial",Font.BOLD,36));
    label.setText("   0.00 Seconds");

  }

  public static void startStop() {
    //start.setText("stop");
    //validate();

  }

  public static void countDown() {
    int Msec=0,min=0,sec=0;
    while(sec < 60) {
          label.setText(min+":"+sec+":"+Msec);
          //label.setLayout(new BorderLayout.CENTER);
          //label.
          Msec++;
          if(Msec==60) {
            Msec=0;
            sec++;
            //label.setText(min+":"+sec+":"+Msec);
          }
          if(sec ==60) {
            Msec =0;
            sec = 0;
            min++;
          }
          try
        {
          Thread.sleep(10);
        }
        catch(Exception e)
        {}
      }
  }      

public static void main(String [] args) {

  // we need a JFrame to put these elements into
  javax.swing.JFrame win = new javax.swing.JFrame("Timer");
  // here we are instantating a new timer
  final Timer time = new Timer();

  //Annonymous inner class
  start.addActionListener(new java.awt.event.ActionListener() {
    // here is the action performed method to start this.
    public void actionPerformed(java.awt.event.ActionEvent e) {
      //here we are creating a new thread to run throwable
      // every click creates a new Thread ( so it goes faster)
      String text = (String)e.getActionCommand();
      if (text.equals("Start")){
        start.setText("Stop");
      }
      else{
        start.setText("Start");
      }
      Thread restart = new Thread(new Runnable() {
        public void run() {
          countDown();
          //startStop();
        }

      });
      restart.start();
    }
  });


  //Look at the below abstract actionlistener below to get reset to work
  javax.swing.JButton reset = new javax.swing.JButton("reset");

  // here we are creating a new annonomys inner class.... check the
  // curly braces
  reset.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent e) {
      Thread restart = new Thread(new Runnable() {
        public void run() {
          reset();
          //Thread.stop();
        }

      });
      restart.destroy();
    }
  });


  //label.setVisible(true);

  javax.swing.JPanel tb = new javax.swing.JPanel();
  tb.add(reset);
  tb.add(start);
  //tb.add(circle);
  win.add(tb,java.awt.BorderLayout.NORTH);
  win.setSize(300,300);
  //win.add(tb);
  win.add(label,java.awt.BorderLayout.CENTER);

  win.setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
  // hiding inside setVisible is borderLayout
  win.setVisible(true);
}
}
Jason Braucht
  • 2,358
  • 19
  • 31
CJ Powell
  • 35
  • 1
  • 11
  • *"I am new to using .. ActiveListeners.."* What's that? People with big ears and good attention span? – Andrew Thompson Apr 25 '12 at 20:54
  • If you haven't already done so, you should read [Threads and Swing](http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html) and [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) for a good introduction to multi-threading and Swing. – Jason Braucht Apr 25 '12 at 22:40
  • Thank you, that was some good reading on threading, and really helped me figure out my dilemna, and i was able to solve this. – CJ Powell Apr 26 '12 at 14:53

1 Answers1

1

It is admirable and a great goal that you want to practice and improve with threads, but this really isn't the arena for it. The problem is that Swing is single threaded - only the ui thread should ever update the graphical environment.

For doing operations involving graphics you should use a javax.swing.Timer and javax.swing.SwingWorker, as these are Thread Safe. In one way, you are learning about thread safety here, so you are making progress!

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • Ok, let me work this out using javax.swing.Timer, i didn't want to use java.util.timer i was not aware there was a javax.swing.timer. – CJ Powell Apr 25 '12 at 20:58