Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:优化while(true)循环_Java_Swing_Loops_Time - Fatal编程技术网

Java:优化while(true)循环

Java:优化while(true)循环,java,swing,loops,time,Java,Swing,Loops,Time,我正在创建一个程序来获取时间并将其显示在JFrame中(它还将背景更新为#[HOUR][MIN][SEC]颜色,如on)。我的问题是计时器只能每2-4秒更新一次(在低端机器上)。我有代码,我想知道如何去优化一个已经很小的程序 请容忍糟糕的编码实践,因为我仍然不完全理解Java 下面是我的代码-Window.java: import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.InputS

我正在创建一个程序来获取时间并将其显示在JFrame中(它还将背景更新为#[HOUR][MIN][SEC]颜色,如on)。我的问题是计时器只能每2-4秒更新一次(在低端机器上)。我有代码,我想知道如何去优化一个已经很小的程序

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

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

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

    }

}
import javax.swing.*;
导入java.awt.*;
导入java.io.IOException;
导入java.io.InputStream;
导入java.util.Calendar;
导入java.util.concurrent.TimeUnit;
公共类窗口{
/**
*基于网站的简单变色时钟
*
*@作者里斯·佩里
*/
公共静态void main(字符串[]args)引发IOException、FontFormatException、InterruptedException{
//导入字体
InputStream in=Window.class.getResourceAsStream(“Lato Hairline.ttf”);
Font Font=Font.createFont(Font.TRUETYPE_Font,in).deriveFont(50f);
//初始化框架、面板和标签
JFrame=新JFrame(“十六进制时钟”);
JPanel面板=新的JPanel();
panel.setLayout(新的FlowLayout());
JLabel标签=新的JLabel();
label.setFont(字体);
label.setPreferredSize(新尺寸(200350));
标签。设置前景(颜色。白色);
//合并框架、面板和“这是一个测试”)标签。使窗口可见
面板。添加(标签);
框架。添加(面板);
框架。设置尺寸(700400);
frame.setLocationRelativeTo(空);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//设置日历
日历;
//初始化一些与时间管理有关的变量
字符串格式化时间;
字符串formattedmin;
字符串格式化秒;
//主循环获取时间并更新背景广告标签
while(true){
//得到小时,分钟和秒
calendar=calendar.getInstance();
int hour=calendar.get(calendar.hour/OF\u DAY);
如果(小时<10){formattedhour=“0”+hour;}否则{formattedhour=hour+“”;}
int min=calendar.get(calendar.MINUTE);
如果(min<10){formattedmin=“0”+min;}否则{formattedmin=min+“”;}
int sec=calendar.get(calendar.SECOND);
如果(秒<10){formattedsec=“0”+sec;}否则{formattedsec=sec+“”;}
//格式化并更新必要的组件
字符串时间=formattedhour+“:“+formattedmin+”“+formattedsec;
label.setText(时间);
字符串十六进制=“#”+formattedhour+formattedmin+formattedsec;
面板背景(彩色解码(十六进制));
panel.repaint();
}
}
}

您可以改用javax.swing.Timmer。它在一段时间后重复执行一项任务


你不需要“优化”那个while循环,你需要摆脱它。彻底地相反,在Swing GUI中使用适当的工具来重复代码。请查看教程链接。您最好摆脱繁忙的循环,使用
计时器更新屏幕。例如,在.Dude中,您的代码会消耗CPU,打开任务管理器,并在运行此任务时检查CPU使用情况。这就是为什么现在看到实际变化有点晚了。Thx,我来看看**每一个有经验的程序员可能都讨厌这种代码——从不使用0作为计时器延迟。使用有意义的、合理的值。你可能还想改进一下你的答案,让它更充实一些。我为我的愚蠢感到抱歉,但我似乎无法让它发挥作用。如何使在actionPerformed()外部定义的变量在actionPerformed()内部工作?为类创建全局变量。或者我一直喜欢的最好的方法是在类中创建一个公共函数,并在actionPerformed()中调用它。
   ActionListener taskPerformer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            //...Perform a task...

        }
    };
    Timer timer = new Timer(10 ,taskPerformer);
    timer.start();