首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java:优化while(true)循环

Java:优化while(true)循环
EN

Stack Overflow用户
提问于 2018-09-15 02:45:33
回答 1查看 93关注 0票数 0

我正在创建一个获取时间并将其显示在JFrame中的程序(它还将背景更新为颜色#HOURSEC,就像在 rhysperry.co.nf 上一样)。我的问题是计时器接缝每2-4秒才更新一次(在低端机器上)。我有代码,我想知道如何去优化一个已经很小的程序。

请容忍糟糕的编码实践,因为我仍然不能完全理解Java。

以下是我的代码- Window.java:

代码语言:javascript
复制
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;


public class Window {
    /**
     * Simple color changing clock based on the website the website <a href="http://rhysperry.co.nf">rhysperry.co.nf</a>
     *
     * @author Rhys Perry
     */
    public static void main(String[] args) throws IOException, FontFormatException, InterruptedException {

        //Import font
        InputStream in = Window.class.getResourceAsStream("Lato-Hairline.ttf");
        Font font = Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(50f);

        //Initialise the Frame, Panel and label
        JFrame frame= new JFrame("Hex Clock");

        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());

        JLabel label = new JLabel();
        label.setFont(font);
        label.setPreferredSize(new Dimension(200, 350));
        label.setForeground(Color.WHITE);

        //Merge Frame, Panel and "This is a test")Label. Make window visible
        panel.add(label);
        frame.add(panel);
        frame.setSize(700, 400);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        //Setup calendar
        Calendar calendar;

        //Initialise some variables to do with time management
        String formattedhour;
        String formattedmin;
        String formattedsec;

        //Main loop to get the time and update the background ad Label
        while(true) {
            //Get hours, minutes and seconds
            calendar = Calendar.getInstance();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            if (hour < 10) { formattedhour = "0" + hour; } else { formattedhour = hour + "";}
            int min = calendar.get(Calendar.MINUTE);
            if (min < 10) { formattedmin = "0" + min; } else { formattedmin = min + "";}
            int sec = calendar.get(Calendar.SECOND);
            if (sec < 10) { formattedsec = "0" + sec; } else { formattedsec = sec + "";}

            //Format and update the necessary components
            String time = formattedhour + ":" + formattedmin + " " + formattedsec;
            label.setText(time);
            String hex = "#" + formattedhour + formattedmin + formattedsec;
            panel.setBackground(Color.decode(hex));
            panel.repaint();
        }

    }

}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52337685

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档