Solved

time displayed in JLabel

Posted on 2002-07-02
15
419 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
Comment Utility
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
Comment Utility


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
Comment Utility
Laax,

Thats exactly what mzimmer74 said, proposed solutions are not supposed to duplicate a previous comment.
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
Comment Utility
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
Comment Utility
ok, I'll let you off this time ;-)
0
 

Author Comment

by:dgal
Comment Utility
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 92

Expert Comment

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

Expert Comment

by:objects
Comment Utility
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
Comment Utility
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
Comment Utility
Add the following line to the top:

import java.awt.event.*;
0
 

Author Comment

by:dgal
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thank you Laxx.  Your solution seems to work.  Sorry objects but thank you VERY much for your help as well.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Performance issue while iterating with streams 5 39
firstChar challenge 13 83
Python Assistance 7 31
github account with ecipse 1 15
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

744 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now