×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Yts 95
Added: Feb 28, 2021 12:59 PM
Views: 4764
Tags: no tags
  1. import java.awt.AWTEvent;
  2. import java.awt.Toolkit;
  3. import java.awt.event.AWTEventListener;
  4. import java.awt.event.ActionEvent;
  5. import java.awt.event.ActionListener;
  6.  
  7. import javax.swing.JFrame;
  8. import javax.swing.JOptionPane;
  9. import javax.swing.JScrollPane;
  10. import javax.swing.JTextArea;
  11. import javax.swing.SwingUtilities;
  12. import javax.swing.Timer;
  13. import javax.swing.WindowConstants;
  14.  
  15. public class SessionHandlerExample implements ActionListener {
  16.  
  17.     private static final int SESSION_TIMEOUT = 30 * 1000; // 30 sec timeout for testing purposes
  18.     private final Timer invalidationTimer = new Timer(SESSION_TIMEOUT, this);
  19.     private final JFrame frm = new JFrame("Session test frame");
  20.     /**
  21.      *
  22.      */
  23.     public SessionHandlerExample() {
  24.         initUI();
  25.     }
  26.  
  27.     /**
  28.      *
  29.      */
  30.     private void initUI() {
  31.         final JTextArea text = new JTextArea(20, 80);
  32.         frm.add(new JScrollPane(text));
  33.         frm.pack();
  34.         frm.setLocationRelativeTo(null);
  35.         frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  36.         frm.setVisible(true);
  37.         invalidationTimer.setRepeats(false);
  38.         invalidationTimer.restart();
  39.  
  40.         // register listener to get all mouse/key events
  41.         final AWTEventListener l = new AWTEventListener() {
  42.  
  43.             @Override
  44.             public void eventDispatched(AWTEvent event) {
  45.                 // if any input event invoked - restart the timer to prolong the session
  46.                 invalidationTimer.restart();
  47.             }
  48.         };
  49.         Toolkit.getDefaultToolkit().addAWTEventListener(l, AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK);
  50.     }
  51.  
  52.     /**
  53.      * {@inheritDoc}
  54.      */
  55.     @Override
  56.     public void actionPerformed(ActionEvent e) {
  57.         // provide session invalidation here (show login dialog or do something else)
  58.         JOptionPane.showMessageDialog(frm, "Your session is invalide");
  59.         invalidationTimer.restart();
  60.     }
  61.  
  62.     public static void main(String[] args) {
  63.         SwingUtilities.invokeLater(new Runnable() {
  64.  
  65.             @Override
  66.             public void run() {
  67.                 new SessionHandlerExample();
  68.             }
  69.         });
  70.     }
  71. }