Java swing close window without exiting application

I have a small frame where I ask for the user and password. This frame will be opened by clicking on the button in the main window.

Then I have two buttons: ok and cancel.

When I click the Cancel button, I need to close this frame without leaving the application.

How can i do this?

+7
java button swing exit
source share
8 answers

You can use Frame.hide () or Frame.dispose (). I also recommend watching JDialog or JOptionPane

Correction: hide () is deprecated. SetVisible (false) should be used instead

+18
source share

You can call setVisible (false) in a frame.

You can also call setDefaultCloseOperation in a frame passing in HIDE_ON_CLOSE (information here: http://java.sun.com/javase/6/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation%28int%29 ). This will prevent the application from being dodged if the user clicks β€œX” on the JFrame to close it.

+3
source share

Perhaps a cleaner way is to simply change setDefaultCloseOperation from EXIT_ON_CLOSE to DISPOSE_ON_CLOSE:

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
+3
source share

Use this.dispose(); in the action listener method when the username / password is successful. eg:

 public void actionPerformed(ActionEvent ae) { if(ae.getSource()=="button you press to confirm username/password"){ if(userNameTf.getText().equals(username)&&isPassword(passwordTf.getPassword())){ new "window to be opened upon success" this.dispose(); // calls dispose on this object ie. // the login window } else{ userNameTf.setText(""); passwordTf.setText(""); JOptionPane.showMessageDialog(this, "Username and/or password is incorrect!", "Attention!", JOptionPane.WARNING_MESSAGE); } } } 

If you use inner classes to handle events, just replace this.dispose () 'with Super_Class_Name.this.dispose ();

+3
source share

Make sure you do not have:

 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
+2
source share

The setVisible method does not free memory resources and should be used only when the form should be used again.

The dispose method Releases all resources on the native screen used by this window, its subcomponents, and all its child users. That is, the resources for these Components will be destroyed, any memory that they consume will be returned to the OS, and they will be marked as not displayed.

+2
source share

Create a function in the outer class where you are executing the JFrame (you need to close by pressing the cancel button).
Write this.setVisible(false); in the implementation of this function. Finally, call this function in the ActionListener implementation when you want to close it.

+1
source share

You can do this in many ways, but these two methods are the most convenient to use. 1. write this.setVisible(false) inside the implemented ActionListener
Or
2. write this.dispose() inside the implemented ActionListener . Hope this helps you.

+1
source share

All Articles