I am working on a clock in a JFrame but it keeps on overwriting itself and causing a blur on the screen.
//starting new Thread which will update time
new Thread(new Runnable() {
public void run() {
try {
updateTime();
} catch (Exception ie) {}
}
}).start();
}
public void updateTime() {
try {
while (true) { // geting Time in desire format
time.setText(new SimpleDateFormat("hh:mm:ss a").format(new java.util.Date()));
// Thread sleeping for 1 sec
Thread.currentThread().sleep(1000);
}
} catch (Exception e) {
System.out.println("Exception in Thread Sleep : " + e);
}
}
The below code is a working example of how to update a JLabel on JFrame. I used your code and added a few things on top of it. Looks like you have some different problem since my JLabel is being updated every second. Please copy the code and run it. I hope this will help you find the problem.
import java.text.SimpleDateFormat;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class teset {
private static JFrame frame = new JFrame("FrameDemo");
private static JLabel time = new JLabel();
public static void main(String[] args) {
frame.add(time);
frame.pack();
frame.setVisible(true);
new Thread(new Runnable() {
public void run() {
try {
updateTime();
} catch (Exception ie) {
}
}
}).start();
}
public static void updateTime() {
try {
while (true) {
time.setText(new SimpleDateFormat("hh:mm:ss a").format(new java.util.Date()));
Thread.currentThread().sleep(1000);
}
} catch (Exception e) {
System.out.println("Exception in Thread Sleep : " + e);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.