实验十四

 

一、源代码

 

package TestCountDow

 

import java.awt.

import java.awt.event.ActionEvent

import java.awt.event.ActionListener

import javax.swing.*

public class CountDown extends JFrame 

JButton jButton

JLabel jLabel

int time=60

public CountDown() 

FlowLayout fl=new FlowLayout(FlowLayout.CENTER)

this.setLayout(fl)

//为按钮jButton添加监听器,实现点击时倒计时重新开

jButton=new JButton("重新开始")

jButton.addActionListener(new ActionListener() 

@Overrid

public void actionPerformed(ActionEvent arg0) 

dispose();//关闭当前窗

new CountDown();//新建一个窗

 

 

}

//匿名创建一个线程内部类来实现时间倒计时,这是整篇代码的核

jLabel=new JLabel()

new Thread()

public void run() 

while(time>0) 

time--

if(time<6) {//当时间只剩5秒时闪

jLabel.setForeground(Color.RED)

 

jLabel.setText(time+"秒")

try 

Thread.sleep(1000)

} catch (InterruptedException e) 

e.printStackTrace()

 

 

 

 

}.start(

 

this.add(jButton

this.add(jLabel)

this.setTitle("倒计时")

this.setSize(300, 200)

this.setResizable(true)

this.setVisible(true)

this.setDefaultCloseOpe;this.setDefaultCloseOperation(EXIT_ON_CLOSE);

}

 

public static void main(String[] args) {

 

三、心得

 

1、使用java.lang.Thread类或者java.lang.Runnable接口编写代码来定义、实例化和启动新线程。

 

2、Java中,每个线程都有一个调用栈,即使不在程序中创建任何新的线程,线程也在后台运行着。

posted @ 2019-06-30 19:28  cxm&  阅读(134)  评论(0编辑  收藏  举报