Count down timer

sargent240
sargent240 used Ask the Experts™
on
I am writing an application to put a basketball scoreboard on a big screen TV.  I am having a little trouble with the clock.  I have written a count down timer that works fine but I can't stop the count if a team takes a time out.  Can someone help me with the code that will allow me to start and stop the clock.  I have a socket for communicating between two computers, one is attached to the big TV and the other is the machine use to control the scoreboard machine.  I connect through a socket and send commands to the scoreboard machine like "startClock" to start it and I would like to sent "stopClock" to stop it and then "startClock" once again to resume.  I have the communications working fine and when I send "startClock" to the scoreboard machine the clock starts as it should.  Any ideas how to toggle it on and off.  The timer code is below and I start it with:

            CountDownTimer c = new CountDownTimer(0, 8, 0);

It starts counting down from 8 minutes;


  Thanks.

       
    public class CountDownTimer implements ActionListener {
    private long count;
    private DateFormat df;
    private javax.swing.Timer t;

    public CountDownTimer(int hours, int minutes, int seconds) {
      // suppose to show as in 01 HR 30 MIN 30 SEC.
       count = 0;
       t = new javax.swing.Timer(1000, this);

      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.HOUR_OF_DAY, hours);
      cal.set(Calendar.MINUTE, minutes);
      cal.set(Calendar.SECOND, seconds);
       count = cal.getTime().getTime();
      df = new SimpleDateFormat("mm:ss");
      t.start();

    }
    public void actionPerformed(ActionEvent e) {
      // suppose to countdown till OO HR 00 MIN 00 SEC
      tfTime.setText(df.format(count));

      if(df.format(count).equals("00:00:00"))
          t.stop();
      count -= 1000;
    }
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
You have to implement something like the following code:
The button I have put in your class should be something like that, but of course it shoud resides on other place, where is the applicatin that sends the commands ot the scoreboard. I only added the button...

import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.text.DateFormat;
import java.util.Calendar;

public class CountDownTimer implements ActionListener {
    private long count;
    private DateFormat df;
    private javax.swing.Timer t;
    private JButton button = new JButton("Stop"); // because the timer is started by default

    public CountDownTimer(int hours, int minutes, int seconds) {
      // suppose to show as in 01 HR 30 MIN 30 SEC.
       count = 0;
       t = new javax.swing.Timer(1000, this);
       button.addActionListener(this);

      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.HOUR_OF_DAY, hours);
      cal.set(Calendar.MINUTE, minutes);
      cal.set(Calendar.SECOND, seconds);
       count = cal.getTime().getTime();
      df = new SimpleDateFormat("mm:ss");
      t.start();

    }

    public void actionPerformed(ActionEvent e) {
      if (e.getSource() instanceof JButton) {
          if (t.isRunning()) {
              t.stop();
              button.setText("Start");
          } else {
              t.start();
              button.setText("Stop");
          }
      } else {
          // suppose to countdown till OO HR 00 MIN 00 SEC
          tfTime.setText(df.format(count));

          if(df.format(count).equals("00:00:00")) t.stop();
          count -= 1000;
      }
    }
}
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.text.DateFormat;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.awt.Dimension;
import java.awt.TextField;
import java.awt.BorderLayout;

public class CountDownTimer extends JFrame  implements ActionListener {
    private long count;
    private DateFormat df;
    private javax.swing.Timer t;
    private JButton button = new JButton("Stop"); // because the timer is started by default
    private TextField tf;

    public CountDownTimer(int hours, int minutes, int seconds) {
this.setLayout(new BorderLayout());
      // suppose to show as in 01 HR 30 MIN 30 SEC.
       count = 0;
       t = new javax.swing.Timer(1000, this);
       button.addActionListener(this);
	tf = new TextField(10);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

this.setSize(new Dimension(50,150));

	this.add(button,BorderLayout.NORTH);
	this.add(tf);

      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.HOUR_OF_DAY, hours);
      cal.set(Calendar.MINUTE, minutes);
      cal.set(Calendar.SECOND, seconds);
       count = cal.getTime().getTime();
      df = new SimpleDateFormat("mm:ss");
      t.start();
this.setVisible(true);
    }


public static void main(String[] args){

new CountDownTimer(1,30,30);

}
    public void actionPerformed(ActionEvent e) {
      if (e.getSource() instanceof JButton) {
          if (t.isRunning()) {
              t.stop();
              button.setText("Start");
          } else {
              t.start();
              button.setText("Stop");
          }
      } else {
          // suppose to countdown till OO HR 00 MIN 00 SEC
        // button.setText(df.format(count));
tf.setText(df.format(count));
          if(df.format(count).equals("00:00:00")) t.stop();
          count -= 1000;
      }
    }
}

Open in new window

Leon TealeSenior Penetration Tester

Commented:
<script language=javascript>

<!--//
//Javascript Countdown Timer.
//set the amount of time click
//start timer and the clock will
//count down until it reaches zero 
//Jason Russo http://thescriptcenter.com
var message = "Complete.";
//do not edit below this line.//
var parselimit=0;
var st=0;
var limit,curhour,curmin,cursec;
function set_limit(strtstop) {
//prevent multiple settimeouts
if(st) { clearTimeout(st); }
 
if(document.getElementById("pause").value == 1) {
limit=document.getElementById("show_timer").innerHTML;
} else {
limit=document.getElementById("hours").value + ":" + document.getElementById("min").value + ":" + document.getElementById("sec").value;
}
parselimit=limit.split(":");
// take the minutes x 60 add it to the seconds;
parselimit=parselimit[0]*3600+parselimit[1]*60+parselimit[2]*1;
//exit if timer wasn't set. //
if(parselimit <= 0) { return; }
 
if(strtstop == 1) {
clearTimeout(st);
} else {
st = setTimeout("begintimer()",1000);
 }
}
 
function begintimer(){
if (parselimit==1) {
//ding ding ding
document.getElementById("show_timer").innerHTML = message;
alert(message);return;
} else{ 
parselimit-=1;
curhour=Math.floor(parselimit/3600);
//alert(parselimit)
/* greater than an hour divide by
60 but subtract the hours. */
if(parselimit > 3600) {
//first convert hours back into seconds
curmin = curhour * 3600;
//subtract that from total to get minutes left.
curmin = parselimit - curmin;
curmin = Math.floor(curmin/60);
//alert(curmin);
} else {
curmin = Math.floor(parselimit/60);
}
cursec=parselimit%60;
 
}
curmin += "";
 if(curmin.length == 1 || curmin==9) {
 curmin = "0" + curmin;
 }
cursec += "";
//alert(cursec);
 if(cursec.length == 1 || cursec==9) {
 cursec = "0" + cursec;
  }
curtime = curhour + ":" + curmin + ":" + cursec;
 
//alert(document.getElementById("show_timer").innerHTML);
document.getElementById("show_timer").innerHTML = curtime;
st=setTimeout("begintimer()",1000);
}
 
function add_time_clock(x,frmelm) {
var ter = document.getElementById(frmelm).value;
  /* add time */
 if(x==1) {
 ter = eval(ter) + 1;
   //if greater than 60 go to zero. i'm maxing out the hours at 60 too.
  if(ter >= 60) {
  ter='00';
   }
  } else {
  /* subtract time */
 ter = eval(ter)-1;
   //if greater than 60 go to zero. i'm maxing out the hours at 60 too.
  if(ter <= 0) {
  ter = '00';
   }
 }
ter = "" + ter;
if(ter.length == 1) { 
ter = "0" + ter;
}
 document.getElementById(frmelm).value = ter;
}
function rset_tmr() {
document.getElementById('show_timer').innerHTML = "00:00:00";
document.getElementById('pause').value=0;
 }
function show_hide(div) {
if(document.getElementById(div).style.display=='none') {
 document.getElementById(div).style.display='';
 } else {
 document.getElementById(div).style.display='none';
   }
 }
//-->
</script>
 
<div id="set_timer" style="">
<input id="pause" type="hidden" value="0" /><br />
<table border="1" bordercolor="#000000" cellspacing="0">
<tbody>
<tr>
<td align="center" colspan="3" height="25">
<b><span id="show_timer">00:00:00</span></b></td>
</tr>
<tr>
<td>
Hrs</td>
<td>
Min</td>
<td>
Sec</td>
</tr>
<tr>
<td>
<input id="hours" maxlength="2" size="1" type="text" value="00" />:</td>
<td>
<input id="min" maxlength="2" size="1" type="text" value="00" />:</td>
<td>
<input id="sec" maxlength="2" size="2" type="text" value="00" /></td>
</tr>
<tr>
<td>
[<a href="javascript:add_time_clock('1','hours')" data-cke-saved-href="javascript:add_time_clock('1','hours')">+</a>] [<a href="javascript:add_time_clock('2','hours')">-</a>]</td>
<td>
[<a href="javascript:add_time_clock('1','min')">+</a>] [<a href="javascript:add_time_clock('2','min')">-</a>]</td>
<td>
<a href="javascript:add_time_clock('1','sec')">+</a> <a href="javascript:add_time_clock('2','sec')">-</a>]</td>
</tr>
<tr>
<td align="center" colspan="3">
<input onclick="set_limit()" type="button" value="Start" /> <input onclick="set_limit('1'),document.getElementById('pause').value=1" type="button" value="Pause" /> <input onclick="rset_tmr()" type="button" value="Reset" /></td>
</tr>
</tbody>
</table>
<br />
 </div>

Open in new window

Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Leon TealeSenior Penetration Tester

Commented:
sorry my bad i miss-read completely.

Author

Commented:
Valeri,

The control for the timer is coming from another computer.  There is no operator at the computer that is displaying the scoreboard info.  A big screen TV is hanging on the wall about 16 feet in the air and the person running the control is doing it from a computer the is communicating with the scoreboard computer via wireless lan so I would not be able to use a button.  How would I work around that?  Thanks!

Cheers - Al

Author

Commented:
Here is another piece of code that might help.  I open up a socket between two machines and the machine that is displaying the scoreboard info has this code in it's program.  This code is what controls what goes on the scoreboard.

   
    public ReceiveMessage(DataInputStream d, JTextArea a) {
        this.dis = d;
        this.txt_area = a;
    }    
    public void run()
    {
        while(true)
        {
            try {                
                msg = dis.readUTF();
                txt_area.append("\n" + this.getName() + msg);
            } catch (IOException ex) {
                Logger.getLogger(scoreboard.ReceiveMessage.class.getName()).log(Level.SEVERE, null, ex);
            }
            String player = "";
            if (msg.substring(0,8).equals("homeFoul")) {

                player = msg.substring(8, msg.length());
                msg = msg.substring(0,8);
            }
            switch (msg) {
                case "home1" : homeScore(1);
                    break;
                case "home2" : homeScore(2);
                    break;
                case "home3" : homeScore(3);
                    break;
                case "visitor1" : visitScore(1);
                    break;
                case "visitor2" : visitScore(2);
                    break;
                case "visitor3" : visitScore(3);
                    break;
                case "startClock" : CountDownThread c = new CountDownThread(0,8,0);
                                    c.start();
                    break;
                case "homeFoul" : fouls(msg, player);
                    break;
                case "stopClock" :
                    break;
                default: msg = "";
            }
        }
    }        
 
 
 }

Author

Commented:
Problem solved.  Thank you all!
Hope you got valeri's code to compile.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial