标题更新与图形不同

时间:2013-09-15 17:53:47

标签: java swing awt

我一直致力于一个简单的程序来输入一个时间列表,并显示在此之前剩下的小时,分​​钟和秒数。我有一个延迟问题,即JFrame没有与标题同时更新。

图片:http://i.imgur.com/se08bXm.png

这是我的源代码:

import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;

public class Schedule extends JFrame {

public String out = "";


public static void main(String[] args) throws FileNotFoundException, InterruptedException {
    new Schedule();
}

public Schedule() throws FileNotFoundException, InterruptedException {

    setSize(300, 60);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Calendar now = new GregorianCalendar();

    Scanner in = new Scanner(new File("schedule"));

    ArrayList<Calendar> list = new ArrayList<Calendar>();
    ArrayList<String> list2 = new ArrayList<String>();

    while(in.hasNextInt()) {
        Calendar then = new GregorianCalendar();
        then.set(Calendar.HOUR_OF_DAY, in.nextInt());
        then.set(Calendar.MINUTE, in.nextInt());
        then.set(Calendar.SECOND, in.nextInt());
        list.add(then);
        list2.add(in.nextLine());
    }

    while(true) {
        now = new GregorianCalendar();
        int i = 0;
        for (Calendar c : list) {
            if (c.compareTo(now) > 0) {
                out = (difference(now, c) + list2.get(i));
                setTitle(out);
                long t = System.currentTimeMillis();
                while (System.currentTimeMillis() - t < 1000);
                repaint();
                break;
            }
            i++;
        }
    }
}

private String difference(Calendar now, Calendar then) {
    String out = "";
    int seconds = (int) ((then.getTimeInMillis() - now.getTimeInMillis()) / 1000);
    int minutes = seconds / 60;
    seconds %= 60;
    int hours = minutes / 60;
    minutes %= 60;
    return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}

@Override
public void paint(Graphics g) {
    g.setColor(Color.BLUE);
    g.fillRect(0, 0, 300, 60);
    g.setColor(Color.YELLOW);
    g.setFont(new Font("", 0, 32));
    g.drawString(out, 5, 50);
}

}

如何修复我的代码,以便JFrame在标题的同时更新? 我试过删除     while(System.currentTimeMillis() - t&lt; 1); 所以它不断更新,但这只会使文本快速闪烁。

有什么想法吗?感谢。

0 个答案:

没有答案