Basic Java Swing, how to exit and dispose of your application/JFrame

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ClosingFrame extends JFrame { private JMenuBar MenuBar = new JMenuBar(); private JFrame frame = new JFrame(); private static final long serialVersionUID = 1L; private JMenu File = new JMenu(“File”); private JMenuItem Exit = new JMenuItem(“Exit”); public ClosingFrame() { File.add(Exit); MenuBar.add(File); Exit.addActionListener(new ExitListener()); WindowListener exitListener = new WindowAdapter() … Read more

How to capture a JFrame’s close button click event?

import javax.swing.JOptionPane; import javax.swing.JFrame; /*Some piece of code*/ frame.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { if (JOptionPane.showConfirmDialog(frame, “Are you sure you want to close this window?”, “Close Window?”, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){ System.exit(0); } } }); If you also want to prevent the window from closing unless the user chooses ‘Yes’, you can … Read more