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

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

 

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

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

1
2
3
4
5
6
try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}          
    timeLeft --;

 Thread.sleep( n )

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

 

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

其实JLabel有这样一个方法:

1
void setText( String )

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

 

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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+"" );
        }
    }
 
}

 

posted @   Emerald  阅读(790)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示