What is the correct action to take when closing a window in Java / swing?
•
Java
I wrote this test code in my customuipanel class:
public static void main(String[] args) { final JDialog dialog = CustomUIPanel.createDialog(null,CustomUIPanel.selectFile()); dialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); }
If customuipanel Main () is the entry point of the program. It works normally, but it makes me wonder what: if another class is called customuipanel What about main()? So I'm right about system The call to exit (0) is incorrect
If there is no top-level window, is there any way to tell the swing event sending thread to exit automatically?
If not, what does jdialog / JFrame do when it closes if the program exits with all top-level windows closed?
Solution
You can use jdialog's setdefaultcloseoperation() method to specify dispose_ ON_ CLOSE:
setDefaultCloSEOperation(JDialog.DISPOSE_ON_CLOSE);
See 12.8 program exit
Appendix: combined with @ camickr's help answer, this example exits when the window is closed or the close button is pressed
import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; /** @see https://stackoverflow.com/questions/5540354 */ public class DialogClose extends JDialog { public DialogClose() { this.setLayout(new GridLayout(0,1)); this.add(new JLabel("Dialog close test.",JLabel.CENTER)); this.add(new JButton(new AbstractAction("Close") { @Override public void actionPerformed(ActionEvent e) { DialogClose.this.setVisible(false); DialogClose.this.dispatchEvent(new WindowEvent( DialogClose.this,WindowEvent.WINDOW_CLOSING)); } })); } private void display() { this.setDefaultCloSEOperation(JDialog.DISPOSE_ON_CLOSE); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); } public static void main(String[] args) { EventQueue.invokelater(new Runnable() { @Override public void run() { new DialogClose().display(); } }); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码