user2863138
user2863138

Reputation: 41

Automatically closing Jdialog without user action

I'm creating an application in which I test a certain number of interface features, and when an error occurs I would like an error message to show.
Then the application should take a screenshot of the entire screen, and finally the error message closes without any help from the user.

To this end, I tried to use JDialog as below:

    JOptionPane pane = new JOptionPane("Error message", JOptionPane.INFORMATION_MESSAGE);
    JDialog dialog = pane.createDialog("Error");
    dialog.addWindowListener(null);
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dialog.setVisible(true);
    Application.takeScreenshot();
    dialog.setVisible(false);

I was wondering if there is a specific method to close it. I looked up the documentation and I can't seem to find it. I tried to find a relevant question on SO, but couldn't find one that addresses my problem.

I wonder if there is a way to get the window handle, and then close it using that, or simply send a "CLOSE" or "Press_ok" event to the window?

Edit: It seems to me as if the code entirely stops running when the messagebox shows, as if there was a Thread.sleep() until window is closed manually by the user.

If possible, a code sample would be helpful.

Thanks

Upvotes: 3

Views: 5513

Answers (2)

Maxim Shoustin
Maxim Shoustin

Reputation: 77910

Try to use ScheduledExecutorService. Something like:

    JDialog dialog = pane.createDialog("Error");
    dialog.addWindowListener(null);
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

ScheduledExecutorService sch = Executors.newSingleThreadScheduledExecutor();     
sch.schedule(new Runnable() {
    public void run() {
        dialog.setVisible(false);
        dialog.dispose();
    }
}, 10, TimeUnit.SECONDS);

dialog.setVisible(true); 

[EDIT]

Regards to camickr comment, the documentation does not mention that a ScheduledExedcutorService executes on the Event Dispatch Thread. So better to use swing.Timer

JDialog dialog = pane.createDialog("Error");
 dialog.addWindowListener(null);
 dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

Timer timer = new Timer(10000, new ActionListener() { // 10 sec
            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
                dialog.dispose();
            }
        });

        timer.start();

        dialog.setVisible(true); 

Upvotes: 3

user2863138
user2863138

Reputation: 41

I've managed to fix it. It seems that by default, JDialog is Modal, meaning that it interrupts everything else until it's closed by the user. To fix this, I used the method:

dialog.setModalityType(Dialog.ModalityType.MODELESS);

When this is active, a simple .setVisible(false); is enough. Anyways thanks for the help sorry for creating an unecessary question but I had been at it for hours until i found it. Hope it can help others.

Upvotes: 1

Related Questions