Search code examples
javaswingjframejdialog

How to close a JDialog after a certain period of timeopened from a Jframe


So I am trying to make a shopping cart app using Java Swing forms with MYSQL JDBC Connectivity, In one part of the app, when a user clicks a button like "View Product", it takes time for the machine to load the information from the database and output in the app, so in that time I want to show a loading icon until the work is done.To achieve this I created a separate JDialog to be used to show a loading gif, and open it from a JFrame on the ActionPerformed event of a button. Here's my work:

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        JDialog dialog = new loader(this, true);
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
        Timer timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                dialog.dispose();
            }
        });
        timer.setRepeats(false);
        timer.start();
    }

But using a Swing Timer to close the JDialog after 1sec, as suggested by other QA on Stack Overflow, doesn't work as expected, so is there any way to achieve this task, that is, to closethe JDialog window after a certain period of time?


Solution

  • Your dialog is modal. So the setVisible(true) method call doesn't return until the dialog has been closed. So the timer is only created once the dialog is closed.

    You need to create it and start it before making the dialog visible.