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+"" );
    		}
    	}
    
    }
    
  • 相关阅读:
    实现AB值对换的两种方法
    Spring文件上传Demo
    CentOS 查看系统 CPU 个数、核心数、线程数
    InvocationTargetException异常
    在 Excel 中设置图片
    JavaScript写入文件到本地
    Semaphore初探
    MySQL连接服务端的几种方式
    超链接导致window.location.href失效的解决办法
    在 CentOS7 上安装 swftools
  • 原文地址:https://www.cnblogs.com/Emerald/p/4278061.html
Copyright © 2011-2022 走看看