温馨提示×

如何在Java中处理对话框关闭事件

小樊
81
2024-08-30 07:14:10
栏目: 编程语言

在Java中,处理对话框关闭事件通常涉及到使用JDialog组件和监听器

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

public class DialogCloseExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGUI());
    }

    private static void createAndShowGUI() {
        // 创建一个 JFrame
        JFrame frame = new JFrame("Dialog Close Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setLocationRelativeTo(null);

        // 创建一个 JButton,点击时打开对话框
        JButton openDialogButton = new JButton("Open Dialog");
        openDialogButton.addActionListener(e -> {
            JDialog dialog = new JDialog(frame, "My Dialog", true);
            dialog.setSize(200, 100);
            dialog.setLocationRelativeTo(frame);

            // 添加一个按钮,点击时关闭对话框
            JButton closeDialogButton = new JButton("Close Dialog");
            closeDialogButton.addActionListener(evt -> dialog.dispose());
            dialog.getContentPane().add(closeDialogButton, BorderLayout.CENTER);

            // 处理对话框的关闭事件
            dialog.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.out.println("Dialog is closing...");
                    // 在这里添加其他关闭事件相关的操作
                }
            });

            dialog.setVisible(true);
        });

        frame.getContentPane().add(openDialogButton, BorderLayout.CENTER);

        frame.setVisible(true);
    }
}

在这个示例中,我们首先创建了一个包含JButton的主窗口。当单击该按钮时,将打开一个模态对话框。对话框中有一个名为“关闭对话框”的按钮,单击该按钮将关闭对话框。

我们使用WindowAdapter类来处理对话框的关闭事件。当对话框关闭时,windowClosing方法将被调用。在这个方法中,你可以添加处理关闭事件所需的任何操作。在本示例中,我们只是在控制台上打印一条消息。

0