java swing 窗口不用时定时关闭 博客分类: java swing WindowEventswing定时关闭窗口不用时关闭空闲时关闭
程序员文章站
2024-03-25 17:47:10
...
我写了一些java swing客户端程序,我想达到一个效果:长时间不用时自动关闭.
如何实现呢?
启动主窗口时,调用如下方法,给Frame添加监听事件:
private void init33() { this.addWindowListener(new WindowAdapter() { @Override public void windowActivated(WindowEvent e) { System.out.println("window Activated"); if (task != null) { task.cancel(); task = null; } super.windowActivated(e); } @Override public void windowDeactivated(WindowEvent e) { System.out.println("window Deactivated"); if (isLocked) {// over three times and is still locked,meanwhile use // try to log in if (task != null) { task.cancel(); task = null; } } else {// first into this if clause(if (timesFail >= // LoginUtil.MAX_LOGIN_FAIL_TIMES )) task = null; } if (timer == null) { timer = new Timer(); } if (task == null) { task = new MyTask(QRCodeApp.this); } timer.schedule(task, Constant.MILLISECONDS_WAIT_WHEN_FAIL); System.out.println("开始计时"); isLocked = true; super.windowDeactivated(e); } @Override public void windowGainedFocus(WindowEvent e) { System.out.println("window GainedFocus"); super.windowGainedFocus(e); } @Override public void windowLostFocus(WindowEvent e) { System.out.println("window LostFocus"); super.windowLostFocus(e); } }); }
MyTask 源码:
package com.qr.yj.common; import com.qr.yj.QRCodeApp; public class MyTask extends java.util.TimerTask{ private QRCodeApp frame; public MyTask(QRCodeApp frame) { super(); this.frame=frame; } @Override public void run() { frame.setLocked(false); System.out.println("$$$$$"); frame.dispose(); System.exit(0); } }
说明:
(1)Constant.MILLISECONDS_WAIT_WHEN_FAIL 的值600000 ,int类型,单位是:毫秒,即600秒.
(2)QRCodeApp 继承了JFrame,有如下成员变量:
private Timer timer = new Timer(); private MyTask task = null; private boolean isLocked = false;
后台日志:
window Activated
window Deactivated
开始计时
window Activated
window Deactivated
开始计时
$$$$$
程序源代码见附件:qrcode_swing.zip
依赖的jar包:io0007-find_progess-0.0.8.4-SNAPSHOT.jar,
注意:程序采用maven 构建