Solved

time displayed in JLabel

Posted on 2002-07-02
15
421 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
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Checkbox and ListView in Android Layout 4 65
sites similar to codingbat to improve coding hanson skills 3 49
map related example 6 47
hibernate example for saving data 19 37
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…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
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…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

786 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