📜  java swing on close - Java (1)

📅  最后修改于: 2023-12-03 15:15:57.847000             🧑  作者: Mango

Java Swing on Close

Java Swing is a powerful toolkit for building graphical user interfaces (GUIs). One important aspect of any GUI application is handling the closing of the window or frame. The onClose() method is used to handle the closing of a Swing window or frame.

How to use onClose()

To handle the closing of a Swing window or frame, you need to add a WindowListener to it. You can do this by calling the addWindowListener() method on the window or frame and passing in a new instance of the WindowAdapter class.

The WindowAdapter class is a convenience class that implements the WindowListener interface with empty methods. This allows you to only implement the methods that you need for your specific use case.

Here is an example of how to use the onClose() method:

import javax.swing.*;
import java.awt.event.*;

public class MyFrame extends JFrame {
    public MyFrame() {
        setTitle("My Frame");
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onClose();
            }
        });
        setVisible(true);
    }

    private void onClose() {
        int option = JOptionPane.showConfirmDialog(this, "Are you sure you want to close?");
        if (option == JOptionPane.YES_OPTION) {
            dispose();
        }
    }

    public static void main(String[] args) {
        new MyFrame();
    }
}

In this example, we create a new JFrame called MyFrame. We set the title, size, and default close operation. We add a WindowAdapter to the frame, and we override the windowClosing() method to call onClose(). The onClose() method displays a confirmation dialog asking the user if they want to close the frame. If the user selects "Yes," the dispose() method is called to close the frame.

Conclusion

Handling the closing of a Swing window or frame is an important aspect of any GUI application. By using the onClose() method and the WindowListener interface, you can create a customized closing behavior for your application.