Solved

time displayed in JLabel

Posted on 2002-07-02
15
422 Views
Last Modified: 2010-03-31
I would like to have a JLabel display the current time in an application.  I would like the time to update every second ie, i want it to basically function as a clock.  Currently, I have a JPanel with the label in it and I have the time displayed using the Date() class.  The only catch is that the time is not updated.  How do I go about gettig this done?  Thanks a lot.
0
Comment
Question by:dgal
  • 7
  • 4
  • 3
  • +1
15 Comments
 
LVL 2

Expert Comment

by:mzimmer74
ID: 7125780
What you'll have to do is have a separate thread that sleeps for a second, gets the current time (by creating a new Date object), and set the text to the JLabel.
0
 
LVL 1

Accepted Solution

by:
laax earned 100 total points
ID: 7125797


Write a thread something like this:
    class TimeKeeper extends Thread {
        private JLabel target;
        public TimeKeeper(JLabel comp) {
            target = comp;
        }

        public void run() {
            while ( true ) {
                target.setText("<Time string here...>");
                try {
                    // Update time for every second
                    sleep(1000);
                }
                catch ( InterruptedException e ) {
                }
            }
        }
    }

and attach your label with this thread object like this:

    TimeKeeper clock = new TimeKeeper(<Your label object>);
    clock.start();

Laax.
0
 
LVL 92

Expert Comment

by:objects
ID: 7125905
Laax,

Thats exactly what mzimmer74 said, proposed solutions are not supposed to duplicate a previous comment.
0
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
LVL 92

Expert Comment

by:objects
ID: 7125919
import javax.swing.*;
import java.util.*;

public class TimeLabel extends JLabel
   implements ActionListener
{
  private DateFormat Display = new SimpleDateFormat("hh:mm:ss");
  private Timer Tick = new Timer(1000, this);

  public TimeLabel()
  {
  }

  public void actionPerformed(ActionEvent event)
  {
    setText(Display.format(new Date());
  }
}
0
 
LVL 1

Expert Comment

by:laax
ID: 7126008
Hi objects,
>proposed solutions are not supposed to duplicate a previous comment.
   I too know that...but this time I failed check for
latest comments/answers before sending the code, since I
had a phone call...lost the flow :-)
0
 
LVL 92

Expert Comment

by:objects
ID: 7126039
ok, I'll let you off this time ;-)
0
 

Author Comment

by:dgal
ID: 7126290
Laxx-
  I am very new to Java and programming in general so I don't really understand what you mean by thread etc.  I'll check out your solution but do you think you could explain what the code you proposed is doing?  ie, what's a thread etc.  Thanks a lot.
0
 
LVL 92

Expert Comment

by:objects
ID: 7126303
My solutions hides you from the confusion of creating threads etc :-)
0
 
LVL 92

Expert Comment

by:objects
ID: 7126312
And contains a bug :-(
Should be:

import javax.swing.*;
import java.util.*;

public class TimeLabel extends JLabel
  implements ActionListener
{
 private DateFormat Display = new SimpleDateFormat("hh:mm:ss");
 private Timer Tick = new Timer(1000, this);

 public TimeLabel()
 {
   Tick.start();
 }

 public void actionPerformed(ActionEvent event)
 {
   setText(Display.format(new Date());
 }
}


All you need to do is add the custom label to your gui:

panel.add(new TimeLabel());
0
 

Author Comment

by:dgal
ID: 7126355
objects-
  while i like the idea of not using a thread, your code results in the following error "ActionListener of TimeLabel not found..."  Any ideas?  Thanks.
0
 
LVL 92

Expert Comment

by:objects
ID: 7126363
Add the following line to the top:

import java.awt.event.*;
0
 

Author Comment

by:dgal
ID: 7126365
objects-
  while i like the idea of not using a thread, your code results in the following error "ActionListener of TimeLabel not found..."  Any ideas?  Thanks.
0
 
LVL 92

Expert Comment

by:objects
ID: 7126376
Woops just noticed another missed import:

import javax.swing.*;
import java.util.Date;
import java.awt.event.*;
import java.text.*;

public class TimeLabel extends JLabel
 implements ActionListener
{
private DateFormat Display = new SimpleDateFormat("hh:mm:ss");
private Timer Tick = new Timer(1000, this);

public TimeLabel()
{
  Tick.start();
}

public void actionPerformed(ActionEvent event)
{
  setText(Display.format(new Date()));
}
}
0
 
LVL 1

Expert Comment

by:laax
ID: 7126386
Hi dgal,

   Thead is like your assistant.  You can assign him some task and continue your work(main control flow).

   Assistant expects you to assign the task(Code) inside
the function 'run'  [public void run()]

   Once you say 'Go' to your assistant [clock.start()] he would execute the instructions ( inside run() function)

   In my code, TimeKeeper is one such assistant decidcated
to update date in a given Label Component.  We have to
pass the Label component while creating the assistant
(thread), for him to update the label. [   TimeKeeper clock = new TimeKeeper(<Your label object>);]

   The run() function continously updates the label with latest time, at the interval of one second[ sleep(1000) -
1000 milli sec].

   I hope it helps for time being.  Read more about threads
when you find time.  :-}  Please let me know if you any other questions.

Laax.
0
 

Author Comment

by:dgal
ID: 7127503
Thank you Laxx.  Your solution seems to work.  Sorry objects but thank you VERY much for your help as well.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

830 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