我正在创建一个获取时间并将其显示在JFrame中的程序(它还将背景更新为颜色#HOURSEC,就像在 rhysperry.co.nf 上一样)。我的问题是计时器接缝每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();
}
}
}
发布于 2018-09-15 02:55:16
您可以改用javax.swing.Timmer。它在一段时间后重复执行一项任务。https://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
Timer timer = new Timer(10 ,taskPerformer);
timer.start();
https://stackoverflow.com/questions/52337685
复制相似问题