Reputation: 316
I have developed a Java Swing Application and I want to make it so that if there is inactivity for about 60 seconds, it automatically logs out. I have tried using java timers but out of the many examples I have tried, none of them seem to work.
Here is the latest one I have tried (and the only one that did not have any errors in the code):
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();
}
}
However when I run the application it get the following output in the stack trace:
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)
I have tried several examples from Stackoverflow but none of them work. How else can I go about getting the system to logout automatically after 60 seconds of inactivity?
Upvotes: 2
Views: 1618
Reputation: 324118
Check out Application Inactiviy for a simple class that will invoke an Action after a given period of time.
The code uses an AWTEventListener
to listen for events. Every time an event is generated a Swing Timer
is restarted. When the Swing Timer
fires the Action
you specify is invoked.
Upvotes: 3
Reputation: 11934
If you take a look at the documentation, you will see:
throws a NullPointerException - if task is null
Which is exactly what you do in your line
timer.schedule(null, 5000);
That explains the Exception that's being thrown at you. I don't think a scheduler is the right way to go here since each user activity should reset the timer.
Upvotes: 2