LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 05-23-2004, 01:00 PM   #1
alaios
Senior Member
 
Registered: Jan 2003
Location: Aachen
Distribution: Opensuse 11.2 (nice and steady)
Posts: 2,203

Rep: Reputation: 45
Java Timer


Hi do u know how i can make a textbox to show the time? I also want to update the values at each sec
 
Old 05-23-2004, 05:22 PM   #2
eric.r.turner
Member
 
Registered: Aug 2003
Location: Planet Earth
Distribution: Linux Mint
Posts: 216

Rep: Reputation: 31
Use the java.swing.Timer class. The Timer needs a class that implements the ActionListener interface, so basically you write a class that implements that interface. In the actionPerformed method you just increment the seconds of a Calendar object, and use the DateFormat class to format the date for the text field. An example is probably easier than trying to explain it. Here's a JPanel that does what you need:

Code:
// TimeTestPanel.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;

public class TimeTestPanel extends JPanel {

   private static final int delay = 1000; // milliseconds
   private static final int textFieldWidth = 20;

   private JTextField        textField = null;
   private Timer             timer = null;

   public TimeTestPanel() {

      textField = new JTextField( textFieldWidth );
      timer = new Timer( delay , new TimerListener() );

      add( textField );
      timer.start();
   }


   class TimerListener implements ActionListener {

      private Calendar calendar = null;
      private DateFormat time = null;

      public TimerListener() {
         calendar = new GregorianCalendar();
         time = DateFormat.getDateTimeInstance();
      }

      public void actionPerformed( ActionEvent event ) {
         calendar.add( Calendar.SECOND , 1 );
         textField.setText( time.format( calendar.getTime() ) );
      }

   }

}
You need to add the panel to a JFrame, so here's the JFrame:

Code:
// TimeTestFrame.java

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import javax.swing.JFrame;

public class TimeTestFrame extends JFrame {

   public TimeTestFrame() {

      Toolkit toolKit = Toolkit.getDefaultToolkit();
      Dimension screenSize = toolKit.getScreenSize();

      Point frameLocation = new Point( screenSize.width/4 ,
                                       screenSize.height/4 );

      setSize( screenSize.width/2 , screenSize.height/2 );
      setLocation( frameLocation );

      setDefaultCloseOperation( EXIT_ON_CLOSE );
   }

}
This is the main application class that creates the frame and panel, and adds the panel to the frame:

Code:
// TimeTest.java

public class TimeTest {

   public static void main( String[] args ) {

      TimeTestFrame frame = new TimeTestFrame();
      TimeTestPanel panel = new TimeTestPanel();
      frame.getContentPane().add( panel );
      frame.show();

   }

}

Last edited by eric.r.turner; 05-23-2004 at 05:29 PM.
 
Old 05-23-2004, 05:42 PM   #3
german
Member
 
Registered: Jul 2003
Location: Toronto, Canada
Distribution: Debian etch, Gentoo
Posts: 312

Rep: Reputation: 30
This does it in a lot less code:

Code:
import javax.swing.*;
import java.text.SimpleDateFormat;
import java.util.Date;
                                                                                    
public class timer extends Thread {
        private static final String format = "HH:mm:ss a";
        private SimpleDateFormat sdf;
        private JTextField field;
                                                                                    
        public timer(JTextField field) {
                this.sdf = new SimpleDateFormat(format);
                this.field = field;
        }
                                                                                    
	public void run() {
		while(true) {
			SwingUtilities.invokeLater(
				new Runnable() {
					public void run() {
						long time = System.currentTimeMillis();
						Date now = new Date(time);
						field.setText(sdf.format(now));
					}
				}
			);
			try { Thread.sleep(1000); } 
			catch(InterruptedException e) {}			
		}
	}
                                                                                    
        public static void main(String[] args) throws Exception {
                JFrame frame = new JFrame("Timer!");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(300,50);
                JTextField field = new JTextField();
                frame.getContentPane().add(field);
                frame.setVisible(true);
                new timer(field).start();
        }
}

Last edited by german; 05-24-2004 at 10:12 AM.
 
Old 05-24-2004, 11:52 AM   #4
german
Member
 
Registered: Jul 2003
Location: Toronto, Canada
Distribution: Debian etch, Gentoo
Posts: 312

Rep: Reputation: 30
Quote:
Originally posted by eric.r.turner

Code:
      public void actionPerformed( ActionEvent event ) {
         calendar.add( Calendar.SECOND , 1 );
         textField.setText( time.format( calendar.getTime() ) );
      }
This code does not guarantee any relevance to the actual system time, and it will probably lose time since java does not have real-time capabilities. For instance, if the swing event queue has enough stuff in it that the actual time the method gets called is 10ms after exactly 1 second (which is considered an acceptable latency by swing standards, since it has to be called out of the thread which handles all other painting operations), it will start losing seconds and after an hour the time it reflects will be noticeably different than the system time. You're better off setting the time from System.getCurrentTimeMillis() because it gets the value from the native platform's real-time clock (I believe).
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
First timer Cyberian Linux From Scratch 3 04-19-2005 12:27 PM
How do you stop this particular timer? JAVA randomx Programming 4 07-24-2004 05:36 AM
Java Timer alaios Programming 2 05-24-2004 01:39 PM
java timer mcshen Programming 11 03-30-2004 04:07 PM
First timer, help!!!!! jcniest5 Linux - Newbie 7 02-24-2004 08:32 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:44 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration