James Selvakumar’s Blog

December 3, 2007

Implementing session timeout in swing apps

Filed under: java,swing — James @ 2:06 pm
Tags: , ,

If you are working in a web based project, the term “session” must be a frequently used one. “I want to implement a HttpSessionListener”, “How do I access http session?”, “Should i store my user state in http session or in a session bean?”.

But I just wondered, how to implement that in a swing application? (Sorry, i haven’t learn swing application framework yet)

Consider this typical scenario:
A user has logged into the swing application and has opened some 2 or three windows (JFrames). Now the user goes somewhere leaving the system idle.
How can we logout the user automatically here (for security reasons)?
How to close the opened resources?

I initially thought of writing a global event listener and implementing that in all the user interface classes. But that looked like a bad idea for me, because that would involve a lot of code changes.

So I searched through the net and found out a solution from a java forum (thanks camickr).
In contrast to my expectations, it was quite simple though. And here it is:

private void trackSystemEvents()
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener()
public void eventDispatched(AWTEvent event)
String eventText = event.toString();
if(eventText.indexOf(“PRESSED”) != -1 || eventText.indexOf(“RELEASED”) != -1)

Here, i want to track the user activity through a “global” listener kind of thing. And here the event listener is registered with AWTEvent.MOUSE_EVENT_MASK and AWTEvent.KEY_EVENT_MASK. That means, only mouse events and key events shall be tracked.

And i don’t want to track the mouse moved/entered events and that’s why the small “if” condition which checks only for “pressed/released” actions like key pressed, mouse released etc.

This will help you in implementing the logic to track session timeout.

And spice it up with “observer” pattern to notify your user interfaces to close the opened resources.


  1. thanks this helped alot i am writing a kiosk program and when theres no activity for a while i can now return to the main menu.

    Comment by Jetlag — February 3, 2008 @ 1:40 pm | Reply

  2. Hi

    I have one question …
    From where will i get the jar containing “SessionMonitor” class ?

    Comment by Abhay — March 20, 2008 @ 8:06 am | Reply

  3. Hi Abhay,
    You need to write the SessionMonitor yourself. It’s just a singleton class with few methods buddy. If you want further information, I can help you with some sample code.

    Comment by James Selvakumar — March 20, 2008 @ 8:19 am | Reply

    • can you please help me by providing “SessionMonitor” class

      Comment by Ashutosh Anand — May 25, 2017 @ 11:38 am | Reply

  4. Hi,
    I want to store the details of user login in the home page and on subsequent pages, I want to use those values. To be clear, I am authenticating an user with user name and password in an Java Swing application and on successful authentication, I have to store the user name and password in session. If I want the details of user name and password, I have to retrieve that from the session. How I can achieve that in Java Swing. If you have any sample code, send me to elamaran24@gmail.com.

    Thanks a Lot.
    Elamaran Krishnamurthy

    Comment by Elamaran — January 5, 2009 @ 10:32 am | Reply

  5. Hi Elamaran,
    There are many ways to do it.
    The simplest possible way is to store it as a system property. For example,
    System.setProperty("application.userName", myUserName);
    Then you can fetch it anywhere from your application very easily. For example, you can use
    System.getProperty("application.userName"); to retrieve the user name.

    Another option is to store it in a hash map or value object and setting that object in the same way as above.

    But why would you need to store the password of the user in the system? It is not advisable.

    Comment by James — January 12, 2009 @ 2:37 am | Reply

  6. Thanks James…

    I am going to use only the user name and not the password. In the same way I am going to store some values in the session for future retrieval. Thanks for the info. It will be very useful for my application development.

    Elamaran Krishnamurthy

    Comment by Elamaran — January 12, 2009 @ 4:12 am | Reply

  7. Thanks, this is exactly what I want to do.
    Check for activity in a Java Swing app and log the user out if no activity after a certain amount of time
    How do I implement this if I have multiple windows open?
    Do I have a superclass containing the above code which my jframes will extends?
    Can you also give me sample code for SessionMonitor? Does this have some kind of Timer thread which time out if no activity are detected?

    Comment by Viet Bui — September 2, 2009 @ 3:47 pm | Reply

  8. Thanks a lot, James!

    Comment by Anastasia — January 21, 2011 @ 1:59 pm | Reply

    • Am murit de ras la rapoartele fetelor. Mi-a placut si mie cartea, dar parca a lipsit putintel descrierea 🙂 oricum, a fost geniala. Bex si Liz, va vreau ca pretneieee!!! Mi-a placut de Cammie si am apreciat ca in final a ales ceea ce as fi ales si eu, adica prietenia si o viata de spion! Adica de ce sa vrei sa fi normala cand e clar ca esti nascuta sa fi super? Imi place recenzia ta 😀

      Comment by Storm — May 19, 2017 @ 2:57 am | Reply

  9. Hey James i have the same problem as Elamaran. I want implement a session in JAVA Swing. With displaying username at all times. Please aend me sample code at deepak_maranello@yahoo.co.in

    Thanks a lot

    Comment by Anonymous — June 22, 2011 @ 7:07 am | Reply

    • Seriously, get over yourself, Mr. Instant Ultimate Loyalty. The “Red Bulls” have only existed for, like, three years now? And they have not exactly been the easiest of teams to root for.A lot of us love the game and are looking for teams here in the USA to support that play a brand of soccer that inspires something other than facepalms and frustration, but the Metr#Stars&o8230;er, Red Bulls, aren’t exactly there yet….

      Comment by Lakeisha — May 19, 2017 @ 3:29 am | Reply

  10. Hi can i Have the sample code? kksecret11@gmail.com

    thank you

    Comment by Anonymous — August 3, 2011 @ 2:28 am | Reply

  11. Hi James,

    Thanks for your post. Can you please send me a sample working code for this example, it would really help a lot 🙂

    Comment by jm04 — September 13, 2011 @ 3:55 am | Reply

  12. This is really interesting, You are a very skilled blogger.
    I have joined your feed and look forward to seeking more of your magnificent post.

    Also, I have shared your website in my social networks!

    Comment by successful project completion — April 3, 2013 @ 12:29 am | Reply

  13. Thanks for your post. Can you please send me a sample working code for this example, it would really help a lot
    Am struck with a Task need to proceed, Please guide me,

    Comment by Kowthal Ganesh — April 5, 2013 @ 7:18 am | Reply

    • Євген Чекаю з ÐÃÐõт½ÂµÃ‘€Ð¿Ñ–н½ÑÐ¼ на фільм. Небагато Незалежна Україна випустила фільмів. Тому так дуже приємно дивитись своє кіно.

      Comment by Chris — May 19, 2017 @ 4:31 am | Reply

  14. my id was kowthalganesh.kowthalraj@gmail.com

    Comment by Kowthal Ganesh — April 5, 2013 @ 7:19 am | Reply

  15. Hi there, thanks for this code. Could you please send a working version at joelonomo@yahoo.fr i have been trying to make it work on my swing app but nothing…

    Comment by Joel — April 22, 2013 @ 7:44 am | Reply

  16. Never mind, I got it…

    Comment by Joel — April 22, 2013 @ 8:20 am | Reply

    • Les forêts méditerranéennes ont déjà été détruites plusieurs fois par l’homme, avec l’élevage, l’agriculture, la construction de flottes, les incendies volontaires ou non, etc.Ainsi, les anciens parlaient d’une forêt de platanes autour d’Olympie. Mais, au XXe siècle, il n’y avait déjà plus (depuis longtemps) qu’une forêt de pins, bien moins rafraîchissante en érit.Aujou©d’huÃ, que reste-t-il?

      Comment by Lynell — May 19, 2017 @ 4:14 am | Reply

  17. juni 4, 20bb&n2sp;&n1sp;8:49 am I enjoy what you guys are up too. This kind of clever work and reporting! Keep up the superb works guys I’ve you guys to blogroll.

    Comment by Latesha — May 19, 2017 @ 2:55 am | Reply

  18. Hi,
    Can you please help me by providing the Sessionmonitor class

    Comment by Ashutosh Anand — May 25, 2017 @ 11:37 am | Reply

  19. plzz send me this working code mail_Id- kailu7936@gmail.com

    Comment by kailas biradar — June 24, 2017 @ 10:23 am | Reply

  20. How to write Session monitor class setLastActionTime(System.currentTimeMillis());
    how to write this method

    Comment by venkat — September 6, 2017 @ 9:01 am | Reply

RSS feed for comments on this post. TrackBack URI

Leave a Reply to Elamaran Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: