Button for closing a JDialog

In the actionPerformed() method of ActionListener you'll want something like:

dialog.setVisible(false);

If you want to get rid of the dialog permanently (free it from memory) then you would also call:

dialog.dispose(); 

...where dialog is the name of your dialog. If dialog is a local variable, you'll need to make it final to access it in this way (or just make sure it's "effectively final" from Java 8 onwards).

If you're adding the button as part of a subclass of JDialog (i.e. if you've got class MyDialog extends JDialog and you're adding the action listener in MyDialog) you'll want:

MyDialog.this.setVisible(false);

In addition to other answers, you can set it as the default button for the dialog root pane:

JButton myButton = new JButton("Close");
myButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        dispose(); // Or whatever else
        setVisible(false);
    }
});
getRootPane().setDefaultButton(myButton);

That way, its ActionListener will be called whenever Enter is pressed.


You can have the ActionListener dispatch a WindowEvent.WINDOW_CLOSING, as shown here.


import java.awt.event.*;
import javax.swing.*;

public class YourDialog extends JDialog implements ActionListener {

  JButton button;

  public YourDialog() {
     button = new JButton("Close");
     button.addActionListener(this);
     add(button);
     pack();
     setVisible(true);
  }

  public void actionPerformed(ActionEvent e) {
      dispose();
  }
}
  • close only dialolg using dispose() method parent frame not closed. reason that JVM not terminated.