java定时器不执行_定时器在定时完成之前不执行

我正在尝试用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() 方法中 . 这也是我第一次制作计时器,所以欢迎任何建议 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值