zoukankan      html  css  js  c++  java
  • 用JLabel显示时间-- JAVA初学者遇到的一个困难

    问题:用一个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+"" );
    		}
    	}
    
    }
    
  • 相关阅读:
    SPI 1
    运算符
    移位运算
    Comet OJ
    图论 最短路 基础
    CF div3 582 C. Book Reading
    Comet OJ
    VScode 标记“&&”不是此版本中的有效语句分隔符。
    Educational Codeforces Round 63 (Rated for Div. 2)
    1223:An Easy Problem
  • 原文地址:https://www.cnblogs.com/Emerald/p/4278061.html
Copyright © 2011-2022 走看看