Event when closing a window, but not closing it

I want to show the "Confirm Close" window when closing the main application window, but without it disappearing. Right now I am using a windowsListenermore specific event windowsClosing, but when using this event, the main window closes, and I want it to be open.

Here is the code I'm using:

To register a listener

this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                thisWindowClosing(evt);
            }
        });

Implementation of the processing event:

private void thisWindowClosing(WindowEvent evt) {
    new closeWindow(this);
}

I also tried using this.setVisible(true)in the method thisWindowClosing(), but it does not work.

Any suggestions?

+3
source share
1 answer
package org.apache.people.mclark.examples;
import java.awt.event.*;
import javax.swing.*;

public class ClosingFrame extends JFrame {

    public ClosingFrame() {
        final JFrame frame = this;
        // Setting DO_NOTHING_ON_CLOSE is important, don't forget!
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                int response = JOptionPane.showConfirmDialog(frame,
                        "Really Exit?", "Confirm Exit",
                        JOptionPane.OK_CANCEL_OPTION);
                if (response == JOptionPane.OK_OPTION) {
                    frame.dispose(); // close the window
                } else {
                    // else let the window stay open
                }
            }
        });
        frame.setSize(320, 240);
        frame.setLocationRelativeTo(null);
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClosingFrame().setVisible(true);
            }
        });
    }
}
+3
source

Source: https://habr.com/ru/post/1772016/


All Articles