关于Java中timer的一个简单实例应用

效果展示

在这里插入图片描述

核心代码:

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();//
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_41549033/article/details/83176770