首页 > 编程语言 > 详细

用JLabel显示时间-- JAVA初学者遇到的一个困难

时间:2015-02-06 23:00:19      阅读:375      评论:0      收藏:0      [点我收藏+]

问题:用一个JLabe,显示秒数,每过一秒数字自动减少1

 

问题看似很简单,但对初学JAVA的我来说,还真费了一点劲。

首先是如何即时,可以采用线程的方法:

try {
	Thread.sleep(1000);
} catch (InterruptedException e) {
	e.printStackTrace();
}			
	timeLeft --;

 Thread.sleep( n )

代表过n个毫秒之后再接着走下一步程序,也就是说n为1000时,在这停一秒再继续走接下去的步骤。相当于计时一秒。

 

那怎么样让JLabel显示时间呢?

其实JLabel有这样一个方法:

void setText( String )

 将要显示的部分变成一个String,然后就能改变JLabel的内容

 

那这样子就能简单的用JLabel显示时间了:

package Pra12;

import java.awt.*;

import javax.swing.*;

public class SimpleTimer extends JFrame implements Runnable {

	int timeLeft = 10;
	JLabel jl = null;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SimpleTimer st = new SimpleTimer();
	}
	
	public SimpleTimer() {
		// TODO Auto-generated constructor stub
		jl = new JLabel();
		jl.setText( "10" );
		
		Thread th = new Thread( this );
		th.start();
		
		this.add( jl );
		this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		this.setSize( 200 , 100);
		this.setVisible( true );
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while( true ) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			timeLeft --;
			if( timeLeft == -1 ) {
				timeLeft = 10;
			}
			jl.setText( timeLeft+"" );
		}
	}

}

 

用JLabel显示时间-- JAVA初学者遇到的一个困难

原文:http://www.cnblogs.com/Emerald/p/4278061.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!