Remove "X" button in Swing JDialog

Remove "X" button in Swing JDialog

To remove the "X" button (close button) from a Swing JDialog window, you can customize the dialog's WindowListener and handle the window closing event by intercepting it and preventing the default action. Here's how you can do it:

import javax.swing.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class NoCloseButtonDialog { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("Main Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton openDialogButton = new JButton("Open Dialog"); openDialogButton.addActionListener(e -> { showDialog(frame); }); frame.add(openDialogButton); frame.setSize(300, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); }); } private static void showDialog(JFrame parentFrame) { JDialog dialog = new JDialog(parentFrame, "Dialog", true); dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); // Add a custom window listener to handle the closing event dialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // Handle the closing event (e.g., show a confirmation dialog) int result = JOptionPane.showConfirmDialog(dialog, "Are you sure you want to close this dialog?", "Confirmation", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { // Close the dialog dialog.dispose(); } } }); JLabel label = new JLabel("This is a custom dialog."); dialog.add(label); dialog.pack(); dialog.setLocationRelativeTo(parentFrame); dialog.setVisible(true); } } 

In this example:

  1. We create a JFrame as the main application window with a button to open the JDialog.

  2. In the showDialog method, we create a JDialog and set its default close operation to JDialog.DO_NOTHING_ON_CLOSE. This prevents the "X" button from closing the dialog.

  3. We add a custom WindowListener to the JDialog using addWindowListener. In the windowClosing method of the listener, we can implement custom logic to handle the closing event. In this example, we show a confirmation dialog and close the JDialog only if the user confirms.

By setting the default close operation to JDialog.DO_NOTHING_ON_CLOSE and adding a custom WindowListener, you can control the behavior of the "X" button and implement your own closing logic.


More Tags

eslintrc createjs utc uwsgi xvfb custom-font playframework-2.0 repo exponent domain-name

More Java Questions

More Investment Calculators

More Biochemistry Calculators

More Animal pregnancy Calculators

More General chemistry Calculators