Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button for closing a JDialog

I want to add a button (JButton) at the bottom of a JDialog which should close the JDialog when pressed. The problem is I don't know what to write in the ActionListener of that button. I don't want the button to exit the program, just close the dialog.

The JDialog is created by explicitly calling one of JDialog's constructors, not by calling one of the methods from JOptionPane.

I was extremely surprised that I was unable to find an answer to this using Google. I expected that a problem that is so often encoutered would be widely covered on a lot of programming sites. Pretty weird that it is not.

like image 495
SoboLAN Avatar asked Aug 06 '11 21:08

SoboLAN


People also ask

How do I close a JDialog box?

close only dialolg using dispose() method parent frame not closed. reason that JVM not terminated.

How do you close a button in Java?

If you want a JButton that closes the application, you would create the button: JButton Button = new JButton("Close");


2 Answers

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.

like image 111
Mohammed Aslam Avatar answered Sep 17 '22 12:09

Mohammed Aslam


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

like image 22
trashgod Avatar answered Sep 18 '22 12:09

trashgod