我已经开发了一个Java Swing应用程序,我想制作它,以便在大约60秒钟不活动时自动注销。我尝试使用Java计时器,但是在尝试过的许多示例中,似乎没有一个起作用。

这是我尝试过的最新版本(也是唯一在代码中没有任何错误的代码):

int seconds;
    Timer timer;
    Toolkit toolkit;
    public void AutoLogout()
    {
        toolkit = Toolkit.getDefaultToolkit();
        timer = new Timer();
        timer.schedule(null, 5000);
        if(seconds == 0)
        {
            LoginPage lp = new LoginPage();
            lp.setVisible(true);
            this.dispose();
        }
    }


但是,当我运行该应用程序时,它将在堆栈跟踪中获得以下输出:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at java.util.Timer.sched(Timer.java:399)
    at java.util.Timer.schedule(Timer.java:193)
    at AdminMainPage.AutoLogout(AdminMainPage.java:1078)
    at AdminMainPage.<init>(AdminMainPage.java:23)
    at AdminMainPage$35.run(AdminMainPage.java:1289)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)


我已经尝试了Stackoverflow的几个示例,但是没有一个起作用。在闲置60秒后,如何使系统自动注销?

最佳答案

检出Application Inactiviy一个简单的类,该类将在给定的时间段后调用Action。

该代码使用AWTEventListener侦听事件。每次生成事件时,都会重新启动Swing Timer。当Swing Timer触发时,将调用您指定的Action

07-24 21:05