java编写程序显示当前时间,Java显示当前时间

I have a code which shows me the current date and time when I run my application

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

Calendar cal = Calendar.getInstance();

System.out.println(dateFormat.format(cal.getTime()));

Now it shows me: 2012/12/11 00:36:53 when I run it.

But I want it to count the time during running it.

So by example now when I run it on 00:37:53 it shows this time, but I want 00:37:53 at starting and I stop running it on 00:40:55 . I want that it shows me 00:37:53, 00:37:54, 00:37:55 and so on.

Now how can I do this?

解决方案

How about using a timer, such as javax.swing.Timer? (Do not make mistake in the import, there are more Timer classes.)

public static void main(String... args) throws InterruptedException {

final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

int interval = 1000; // 1000 ms

new Timer(interval, new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

Calendar now = Calendar.getInstance();

System.out.println(dateFormat.format(now.getTime()));

}

}).start();

Thread.currentThread().join();

}

This will simply execute the body of the ActionListener every second, printing the current time.

The Thread.join call on the last line is not universally necessary, it's just needed for this example piece of code to run until the process is manually stopped. Otherwise, it would immediately stop.

In a real application, in case it's a Swing app, then the timer should handle threading by itself, so you won't have to worry about it.

Edit

Integrating the above sample into your application is fairly simple, just add it into the initGUI method and instead of printing the current time to System.out set change the text of the given label:

public void initGUI() {

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

setPreferredSize(new Dimension(800, 600));

setLayout(null);

Calendar now = Calendar.getInstance();

tijd = new JLabel(dateFormat.format(now.getTime()));

tijd.setBounds(100, 100, 125, 125);

window.add(tijd);

new Timer(1000, new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

Calendar now = Calendar.getInstance();

tijd.setText(dateFormat.format(now.getTime()));

}

}).start();

pack();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值