天天看点

java swing 窗口不用时定时关闭

如何实现呢?

启动主窗口时,调用如下方法,给frame添加监听事件:

java swing 窗口不用时定时关闭

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);  

            }  

            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 ))  

                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);  

            public void windowgainedfocus(windowevent e) {  

                system.out.println("window gainedfocus");  

                super.windowgainedfocus(e);  

            public void windowlostfocus(windowevent e) {  

                system.out.println("window lostfocus");  

                super.windowlostfocus(e);  

        });  

    }  

 mytask 源码:

java swing 窗口不用时定时关闭

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,有如下成员变量:

java swing 窗口不用时定时关闭

private timer timer = new timer();  

    private mytask task = null;  

    private boolean islocked = false;  

 后台日志:

window activated

window deactivated

开始计时

$$$$$

程序源代码见附件:qrcode_swing.zip

依赖的jar包:io0007-find_progess-0.0.8.4-snapshot.jar,

注意:程序采用maven 构建