Java Swing How to - Close JFrame after user inactivity








Question

We would like to know how to close JFrame after user inactivity.

Answer

import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//from   ww  w  . j ava  2s.c  o  m
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Main {

  public static void main(String[] args) {
    new Main();
  }

  private Timer timer;
  private JLabel label;
  private JFrame frame;

  public Main() {
    label = new JLabel("Waiting...");
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(label);
    frame.setSize(200, 200);
    frame.setVisible(true);

    Toolkit.getDefaultToolkit().addAWTEventListener(
        new AWTEventListener() {
          int count;
          @Override
          public void eventDispatched(AWTEvent event) {
            Object source = event.getSource();
            if (source instanceof Component) {
              Component comp = (Component) source;
              Window win = null;
              if (comp instanceof Window) {
                win = (Window) comp;
              } else {
                win = SwingUtilities.windowForComponent(comp);
              }
              if (win == frame) {
                timer.restart();
                label.setText("Interrupted..." + (++count));
              }
            }
          }
        },
        AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK
            | AWTEvent.MOUSE_MOTION_EVENT_MASK
            | AWTEvent.MOUSE_WHEEL_EVENT_MASK);

    timer = new Timer(5000, new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        frame.dispose();
      }
    });
    timer.start();
  }
}