我试图在我的JFrame上看到我的时钟,但它一直在写自己的顶部

时间:2016-08-28 10:25:42

标签: java

我正在研究JFrame中的时钟,但它会继续覆盖自身并导致屏幕上出现模糊。

//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);
    }
}

1 个答案:

答案 0 :(得分:0)

以下代码是如何在JFrame上更新JLabel的工作示例。我使用了你的代码并添加了一些东西。看起来你有一些不同的问题,因为我的JLabel每秒都在更新。请复制代码并运行它。我希望这可以帮助你找到问题。

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);
    }
}

}