JDialog disposing another window

2019-09-11 14:19发布

问题:

I'm currently working on a java game which opens up with a "start screen" frame. In the startscreen, I have a button called buttonLogin. Once you press buttonLogin, a login dialog launched by a LoginDialog class will pop up asking you for a username and password. In the dialog there are two buttons, login and cancel. Once you press login, my game will open, but the start screen is still visible.

My problem is that I do not know how to write code in the actionPerformed method of my LoginDialog class to close the existing StartScreen window.

Keep in mind that I am writing in the LoginDialog class and not the StartScreen class.

回答1:

Depending on what you want to achieve, you can use the setVisible method or the dispose method.

If needed, you can just pass your StartScreen instance as a parameter to your LoginDialog class.

Another approach would be to give your LoginDialog class a setter for an 'after-login' action. The StartScreen can then create and set an action which disposes the startscreen.

Edit

To make the 'after-login' action a bit more clear, I meant something along the lines of

public class LoginDialog{
  Action afterLoginAction;
  public void setAfterLoginAction( Action action ){
    afterLoginAction = action;
  }
  public void loginButtonPressed(){
    //do your stuff
    if ( afterLoginAction != null ){
      afterLoginAction.actionPerformed( new ActionEvent( ... ) );
    }
  }
}

public class StartScreen extends JWindow{
  public void showLoginScreen(){
    LoginDialog loginDialog = new LoginDialog();
    loginDialog.setAfterLoginAction( new Action(){
       @Override
       public void actionPerformed( ActionEvent e ){
           StartScreen.this.dispose();
       }
     } );
    loginDialog.setVisible( true );
  }
}


回答2:

use dispose(); method of JDialog class