java 一秒刷新,Java秒表每秒更新一次GUI?

I'm a Java beginner and I'm trying to build a simple stopwatch program that displays the time on a swing GUI. Making the stopwatch is easy, however I cannot find a way to make the GUI update every second and display the current time on the stopwatch. How can I do this?

解决方案

Something along these lines should do it:

import java.awt.EventQueue;

import java.util.Timer;

import java.util.TimerTask;

import javax.swing.JFrame;

import javax.swing.JLabel;

/** @see https://stackoverflow.com/a/11058263/230513 */

public class Clock {

private Timer timer = new Timer();

private JLabel timeLabel = new JLabel(" ", JLabel.CENTER);

public Clock() {

JFrame f = new JFrame("Seconds");

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.add(timeLabel);

f.pack();

f.setLocationRelativeTo(null);

f.setVisible(true);

timer.schedule(new UpdateUITask(), 0, 1000);

}

private class UpdateUITask extends TimerTask {

int nSeconds = 0;

@Override

public void run() {

EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

timeLabel.setText(String.valueOf(nSeconds++));

}

});

}

}

public static void main(String args[]) {

EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

final Clock clock = new Clock();

}

});

}

}

The timeLabel will always display the number of seconds the timer has been running.

You will need to correctly format it to display "hh:mm:ss"; one approach is shown here.

Create a container and add the label to it so that you can display it as part of the GUI.

Compare the result to this alternate using javax.swing.Timer.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值