Solved

Count down timer

Posted on 2012-12-20
9
592 Views
Last Modified: 2012-12-23
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;
    }
}
0
Comment
Question by:sargent240
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 16

Accepted Solution

by:
Valeri earned 450 total points
ID: 38712273
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;
      }
    }
}
0
 
LVL 16

Assisted Solution

by:krakatoa
krakatoa earned 50 total points
ID: 38712393
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

0
 
LVL 6

Expert Comment

by:Leon Teale
ID: 38712736
<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

0
Back Up Your Microsoft Windows Server®

Back up all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

 
LVL 16

Expert Comment

by:krakatoa
ID: 38712752
0
 
LVL 6

Expert Comment

by:Leon Teale
ID: 38712761
sorry my bad i miss-read completely.
0
 

Author Comment

by:sargent240
ID: 38713203
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
0
 

Author Comment

by:sargent240
ID: 38713249
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 = "";
            }
        }
    }        
 
 
 }
0
 

Author Comment

by:sargent240
ID: 38716594
Problem solved.  Thank you all!
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 38716715
Hope you got valeri's code to compile.
0

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This video teaches viewers about errors in exception handling.
Suggested Courses

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question