0

How can I set the timeout for a JDialog when it is idle for example 90 seconds?

It exits once no action, movement ,selection is done in the JDialog for 90 seconds.

This thread gives timeouts but no idle condition - Can I set a timer on a Java Swing JDialog box to close after a number of milliseconds

Thanks!

Community
  • 1
  • 1
Philip Morris
  • 459
  • 1
  • 9
  • 26

2 Answers2

1

Okay, so the biggest problem will be getting enough information about interaction from the user. You could try using AWTEventListener, which is a way to monitor AWTEvents going through the EventQueue and should, for the most part, give you enough information about possible interactions.

Because not ALL events go through the EventQueue, there might be some times when this might not always work in which case, you will need to attach additional listeners to the components giving you trouble and reset the timer manually...

Timeout Dialog

import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                IdleDialog dialog = new IdleDialog(5, (Window) null, "Testing");
                dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                dialog.add(new TestPane());
                dialog.pack();
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            add(new JLabel("This is a bad idea"), gbc);
            add(new JButton("Don't tell me"), gbc);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

    public class IdleDialog extends JDialog {

        private long timeOut = 90 * 1000;
        private long startTime;
        private Timer timer;
        private String originalTitle;

        public IdleDialog(long timeOut) {
            init(timeOut);
        }

        public IdleDialog(long timeOut, Frame owner) {
            super(owner);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Frame owner, boolean modal) {
            super(owner, modal);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Frame owner, String title) {
            super(owner, title);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Frame owner, String title, boolean modal) {
            super(owner, title, modal);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Frame owner, String title, boolean modal, GraphicsConfiguration gc) {
            super(owner, title, modal, gc);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Dialog owner) {
            super(owner);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Dialog owner, boolean modal) {
            super(owner, modal);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Dialog owner, String title) {
            super(owner, title);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Dialog owner, String title, boolean modal) {
            super(owner, title, modal);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Dialog owner, String title, boolean modal, GraphicsConfiguration gc) {
            super(owner, title, modal, gc);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Window owner) {
            super(owner);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Window owner, ModalityType modalityType) {
            super(owner, modalityType);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Window owner, String title) {
            super(owner, title);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Window owner, String title, ModalityType modalityType) {
            super(owner, title, modalityType);
            init(timeOut);
        }

        public IdleDialog(long timeOut, Window owner, String title, ModalityType modalityType, GraphicsConfiguration gc) {
            super(owner, title, modalityType, gc);
            init(timeOut);
        }

        protected void init(double timeOutValue) {

            this.timeOut = Math.round(timeOutValue * 1000);

            timer = new Timer(1000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    long runningTime = System.currentTimeMillis() - startTime;
                    System.out.println(runningTime + "/" + timeOut);
                    if (runningTime >= timeOut) {
                        timer.stop();
                        dispose();
                    } else {
                        String title = originalTitle + " [" + (((timeOut - runningTime) / 1000) + 1) + "]";
                        setTitle(title);
                    }
                }
            });

            originalTitle = getTitle();
            String title = originalTitle + " [" + ((timeOut / 1000)) + "]";
            setTitle(title);
            addPropertyChangeListener("title", new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (!timer.isRunning()) {
                        originalTitle = (String) evt.getNewValue();
                    }
                }
            });

            addWindowListener(new WindowAdapter() {
                @Override
                public void windowOpened(WindowEvent e) {
                        timer.start();
                }

                @Override
                public void windowClosed(WindowEvent e) {
                    timer.stop();
                }

            });

            Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
                @Override
                public void eventDispatched(AWTEvent event) {
                    Object source = event.getSource();
                    if (source instanceof Component) {
                        Window win = null;
                        if (!(source instanceof Window)) {
                            win = SwingUtilities.getWindowAncestor((Component) source);
                        } else {
                            win = (Window) source;
                        }
                        if (IdleDialog.this.equals(win)) {
                            if (win.isVisible() && timer.isRunning()) {
                                resetTimeout();
                            }
                        }
                    }
                }
            }, AWTEvent.ACTION_EVENT_MASK
                            | AWTEvent.ADJUSTMENT_EVENT_MASK
                            | AWTEvent.COMPONENT_EVENT_MASK
                            | AWTEvent.CONTAINER_EVENT_MASK
                            | AWTEvent.FOCUS_EVENT_MASK
                            | AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK
                            | AWTEvent.HIERARCHY_EVENT_MASK
                            | AWTEvent.INPUT_METHOD_EVENT_MASK
                            | AWTEvent.INVOCATION_EVENT_MASK
                            | AWTEvent.ITEM_EVENT_MASK
                            | AWTEvent.KEY_EVENT_MASK
                            | AWTEvent.MOUSE_EVENT_MASK
                            | AWTEvent.MOUSE_MOTION_EVENT_MASK
                            | AWTEvent.MOUSE_WHEEL_EVENT_MASK
                            | //                            AWTEvent.PAINT_EVENT_MASK |
                            AWTEvent.TEXT_EVENT_MASK
                            | AWTEvent.WINDOW_EVENT_MASK
                            | AWTEvent.WINDOW_FOCUS_EVENT_MASK
                            | AWTEvent.WINDOW_STATE_EVENT_MASK
            );
        }

        public void resetTimeout() {
            timer.restart();
            startTime = System.currentTimeMillis();
            String title = originalTitle + " [" + ((timeOut / 1000)) + "]";
            setTitle(title);
        }

    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • now I encountered your warning. What other classes can I add other than AWTEvent? – Philip Morris Aug 11 '15 at 13:23
  • What component is causing you an issue? – MadProgrammer Aug 11 '15 at 20:59
  • apparently , Im implementing it in a POS system. so basically no mouse. User told me that sometimes it times out even using it – Philip Morris Aug 11 '15 at 23:40
  • I will add KeyEvent and see. what else do you suggest to add – Philip Morris Aug 11 '15 at 23:43
  • Given the fact that it should be detecting keyboard events, I'd need to see a running example of it not working. – MadProgrammer Aug 11 '15 at 23:43
  • I added a `JTextField` to the example, and so long as I was typing, the `Timer` was reset... – MadProgrammer Aug 11 '15 at 23:45
  • yea it is working perfectly to me too. The thing is when the JDialog is disposed, I set a boolean value isTimedOut to true and then this value will be evaluated by a method call. Is this a wrong approach? – Philip Morris Aug 11 '15 at 23:55
  • I guess it would depend on "how" it was disposed and what you were doing with the resulting value. For example, if the user closes the dialog manually ([X] close button or some other control), that wouldn't be a timed out event. The only time you should be setting a timed out flag is when the `Timer` decides to `dispose` of the dialog – MadProgrammer Aug 11 '15 at 23:59
  • If it turns out to be something stupid I did, let me know ;) – MadProgrammer Aug 12 '15 at 00:03
  • I am having issues with my boolean isTimedout. it is ok in the first parts but as it goes on it malfunctions. is this thread safe? I placed it in if (runningTime >= timeOut) { timer.stop(); setIsTimedout(true); dispose(); – Philip Morris Aug 13 '15 at 04:28
  • I suspect it should be between the `timer.stop()` and `dispose()` calls (but definitely before the `dispose` call) – MadProgrammer Aug 13 '15 at 04:29
  • do I need to clear any field here when it is used in multithreaded app – Philip Morris Aug 13 '15 at 04:31
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/86845/discussion-between-philip-morris-and-madprogrammer). – Philip Morris Aug 13 '15 at 04:34
1

You can also check out Application Inactivity for a more general purpose solution that you can use on any window (frame, dialog).

You just provide an Action you want to invoke after a certain time of inactivity and the Action will automatically be invoked.

camickr
  • 321,443
  • 19
  • 166
  • 288