我正在尝试用Java创建一个计时器应用程序,但在计数过程中,它不会执行main(也打开窗口),直到计数器完成 . 这就是我的意思:
long timeElapsed = 0;
long timeStart = System.currentTimeMillis();
for (long counter=0;counter<5;++counter) {
TimeUnit.SECONDS.sleep(1);
timeElapsed = (System.currentTimeMillis() - timeStart)/1000;
display.setText(Long.toString(timeElapsed));
}
String myString = Long.toString(timeElapsed);
程序将不会在 for 语句完成之前创建一个窗口,这是不好的,因为它没有显示完成之前的时间,这不是我的目标 . 窗口更新在运行时是否有任何方法可以让程序显示已经过的时间?
我的代码:
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.util.concurrent.TimeUnit;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JButton;
public class TimerGUI {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TimerGUI window = new TimerGUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* @throws InterruptedException
*/
public TimerGUI() throws InterruptedException {
initialize();
}
/**
* Initialize the contents of the frame.
* @throws InterruptedException
*/
private void initialize() throws InterruptedException {
JLabel display = new JLabel("a");
// TIME
long timeElapsed = 0;
long timeStart = System.currentTimeMillis();
for (long counter=0;counter<5;++counter) {
TimeUnit.SECONDS.sleep(1);
timeElapsed = (System.currentTimeMillis() - timeStart)/1000;
display.setText(Long.toString(timeElapsed));
}
String myString = Long.toString(timeElapsed);
//WINDOW
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
// LABEL
//display = new JLabel(myString);
display.setBounds(165, 64, 89, 54);
frame.getContentPane().add(display);
//BUTTON
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(165, 169, 89, 32);
frame.getContentPane().add(btnNewButton);
}
}
注意:我还没有使用程序的Button部分,而且我试图修复的代码在 Initialize() 方法中 . 这也是我第一次制作计时器,所以欢迎任何建议 .