How do I dispose a frame after few seconds of delay in Swing?

611 Views Asked by At

I want to dispose of my 1st frame with a delay of 2 to 3 seconds and then open another frame. I am able to dispose of a frame using dispose() methods but I want it to be delay at least 2 seconds. How do I do it? Below is my login code to dispose of a frame Note: I am using GUI builder in NetBeans for swing

private void LoginActionPerformed(java.awt.event.ActionEvent evt) {                                      
        String userName = userField.getText();
        String password = passField.getText();
        if (userName.trim().equals("admin") && password.trim().equals("admin")) {
            message.setForeground(Color.green);
            message.setText(" Hello " + userName
                + "");
            dispose();
            Dashboard mydash = new Dashboard();
            mydash.setVisible(true);
        } else {
            message.setForeground(Color.red);
            message.setText(" Invalid user.. ");
        }
    }                               
1

There are 1 best solutions below

1
nullPointer On BEST ANSWER

The proper solution would be to use a javax.swing.Timer:

int delay = 3000;
Timer timer = new Timer( delay, new ActionListener(){
  @Override
  public void actionPerformed( ActionEvent e ){
      yourFrame.dispose();
      Dashboard mydash = new Dashboard();
      mydash.setVisible(true);
  }
});
timer.setRepeats(false);
timer.start();