me_new
asked on
Simple Clock---Threads
The Thread runs just once.
It Simply Displays the Date once.
It Does not refresh...Why?
Here's the Code
import javax.swing.*;
import java.util.*;
public class Clock2 extends JPanel implements Runnable
{
JLabel label;
Thread thread;
public Clock2()
{
label=new JLabel();
addLabel();
}
public void addLabel()
{
add(label);
thread=new Thread(this,"Clock");
thread.start();
}
public void run()
{
Thread mythread=Thread.currentThr ead();
if (mythread==thread)
{
System.out.println("In");
Calendar cal=Calendar.getInstance() ;
label.setText(cal.getTime( ).toString ());
try{ Thread.sleep(200); System.out.println("Up");}
catch(Exception e){}
}
}
public static void main(String args[])
{
JFrame frame=new JFrame();
frame.getContentPane().add (new Clock2());
frame.setSize(300,300);
frame.setVisible(true);
}
}
It Simply Displays the Date once.
It Does not refresh...Why?
Here's the Code
import javax.swing.*;
import java.util.*;
public class Clock2 extends JPanel implements Runnable
{
JLabel label;
Thread thread;
public Clock2()
{
label=new JLabel();
addLabel();
}
public void addLabel()
{
add(label);
thread=new Thread(this,"Clock");
thread.start();
}
public void run()
{
Thread mythread=Thread.currentThr
if (mythread==thread)
{
System.out.println("In");
Calendar cal=Calendar.getInstance()
label.setText(cal.getTime(
try{ Thread.sleep(200); System.out.println("Up");}
catch(Exception e){}
}
}
public static void main(String args[])
{
JFrame frame=new JFrame();
frame.getContentPane().add
frame.setSize(300,300);
frame.setVisible(true);
}
}
Add the label every time you update it and validate the frame's content pane with frame.getContentPane().val idate(). That should do it. :)
Also note: label.setText(cal.getTime( ).toString ()) will need to be in a loop or timer. It should look something like this (though this is an infinite loop):
JFrame frame; //Declare frame at the top so it isn't local
while (true)
{
label.setText(cal.getTime( ).toString ());
frame.add(label);
frame.getContentPane().val idate();
}
You might want to use a timer instead, firing once every second...
JFrame frame; //Declare frame at the top so it isn't local
while (true)
{
label.setText(cal.getTime(
frame.add(label);
frame.getContentPane().val
}
You might want to use a timer instead, firing once every second...
Oh, oops. You're adding the label to the Panel. In that case, just make frame.add(label) (in the above example) into add(label). That should do it...
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You don't need to call
>>Calendar cal=Calendar.getInstance() ;
in each loop in run. Just call it once in the ctor
>>Calendar cal=Calendar.getInstance()
in each loop in run. Just call it once in the ctor