倒計時窗口在很多程序裏面也很重要,今天我想分享一下如何製作一個簡易的倒計時窗口。
示例:製作一個五秒後會關閉的窗口並有倒計時顯示。
效果:
創建一個類AutoClose爲窗口的類:
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.*;
public class AutoClose{
static int i=5; //表示延遲時間
static JFrame j=new JFrame("2333");
static JLabel l=new JLabel("窗口將在"+AutoClose.i+"秒後關閉!"); //必須先設置文本,否則在一秒後纔會顯示文本!!!
public static void main(String[] args) {
j.setSize(350,150);
JPanel p=new JPanel();
l.setFont(new Font("宋體", Font.PLAIN, 30));
l.setBounds(23, 37, 282, 46);
p.setLayout(null);
p.add(l);
j.getContentPane().add(p);
new DelayTest().t();
j.show();
}
}
再創建一個類 DelayTest,用於計時和延時:
import java.util.Timer;
import java.util.TimerTask;
public class DelayTest {
public void t() {
if(AutoClose.i>0) { //判斷:時間大於0時---執行延時語段
Timer timer=new Timer();
timer.schedule(new TimerTask() {
public void run() {
AutoClose.i=AutoClose.i-1; //窗口上顯示的時間減1
AutoClose.l.setText("窗口將在"+AutoClose.i+"秒後關閉!"); //重設窗口的顯示時間
if(AutoClose.i==0) { //判斷:時間到時---關閉窗口
AutoClose.j.dispose();
}else { //否則:返回,再計時一秒
new DelayTest().t();
}
}
}, 1000); //延遲一秒
}
}
}
其原理是:窗口顯示出來後,會執行延遲類(DelayTest)裏的延時方法,延時方法每一秒會將時間變量(i)減1並刷新窗口上的文本,再判斷時間是否到了,時間沒到會再返回並重新執行延時方法,直到時間變量減爲零爲止。判斷時間變量爲0,便關閉窗口。