關於Java中timer的一個簡單例項應用
阿新 • • 發佈:2018-11-08
效果展示
核心程式碼:
Timer timer = new Timer();//新增定時器
timer.schedule(
new TimerTask(){//重寫定時任務
public void run(){
button2.setText("取消"+String.valueOf(time));//更新倒計時時間
time--;
if(time <= 0)//操作時間介紹自動跳轉頁面
new ThreadButton_cancel();
}
}, 0, 1000);//延遲時間為0秒,即立即開始,每隔1000ms執行一次
完整程式碼中的程式碼解析:
1.第1行到第9行為所需要載入的包
2.第12行到17行為頁面所需的屬性定義
3.第19行到44行為頁面佈局程式碼
4.第46到56為實現倒計時的關鍵程式碼
5.第58到75為事件監聽事件
完整程式碼:
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax. swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class ThreadButton extends JFrame{
private JPanel tb;
private JButton button1;
private static JButton button2;
private Container contentPane = this.getContentPane();
private static int time = 60;
Timer timer = new Timer ();//新增定時器
public ThreadButton(){
tb = new JPanel();
tb.setLayout(null);//設定空佈局
button1 = new JButton("確定");
button1.setBounds(100, 100, 100, 30);
//將按鈕上的倒計時設為變數time便於更新
button2 = new JButton("取消"+String.valueOf(time));
button2.setBounds(100, 150, 100, 30);
tb.add(button1);
tb.add(button2);
contentPane.add(tb);
//設定視窗屬性
super.setTitle("這是一個操作倒計時頁面");
super.setSize(600, 410);
super.setVisible(true);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ButtonListener Listener = new ButtonListener();//新增按鈕監聽事件
button1.addActionListener(Listener);
button2.addActionListener(Listener);
timer.schedule(
new TimerTask(){//重寫定時任務
public void run(){
button2.setText("取消"+String.valueOf(time));//更新倒計時時間
time--;
if(time <= 0)//操作時間超過顯示自動跳轉到上一個頁面
JOptionPane.showMessageDialog(null, "操作時間超時,將跳轉到上一個操作介面");
}
}, 0, 1000);//延遲時間為0秒,即立即開始,每隔1000ms執行一次
}
class ButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object source = e.getSource();
if(source instanceof JButton) {//如果該Listener是Button相應的
String text = ((JButton) source).getText();//獲取發生點選事件的按鈕名稱
if(text.equals("確定")){
JOptionPane.showMessageDialog(null, "你點選了確定按鈕,將跳轉到下一個操作介面");
timer.cancel();//關閉計時器
}
else{
JOptionPane.showMessageDialog(null, "你點選了取消按鈕,將跳轉到上一個操作介面");
timer.cancel();//關閉計時器
}
}
}
}
public static void main(String[] args){
new ThreadButton();//
}
}