设置关闭jdialog时,某布尔值改变
时间: 2024-05-11 08:14:21 浏览: 80
在关闭 JDialog 时改变某布尔值的方法如下:
1. 在 JDialog 类中定义一个布尔类型的成员变量,例如:
```java
public class MyDialog extends JDialog {
private boolean isDialogClosed = false;
// ...
}
```
2. 在 JDialog 的关闭事件监听器中设置该布尔值为 true,例如:
```java
// 添加关闭事件监听器
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
isDialogClosed = true;
dispose(); // 关闭对话框
}
});
```
3. 在需要使用该布尔值的地方进行判断,例如:
```java
MyDialog dialog = new MyDialog(parentFrame, "My Dialog", true);
dialog.setVisible(true);
if (dialog.isDialogClosed()) {
// do something
}
```
完整的代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyDialog extends JDialog {
private boolean isDialogClosed = false;
public MyDialog(JFrame parent, String title, boolean modal) {
super(parent, title, modal);
setSize(200, 100);
setLocationRelativeTo(null);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
isDialogClosed = true;
dispose();
}
});
}
public boolean isDialogClosed() {
return isDialogClosed;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Main Window");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Open Dialog");
button.addActionListener(e -> {
MyDialog dialog = new MyDialog(frame, "My Dialog", true);
dialog.setVisible(true);
if (dialog.isDialogClosed()) {
JOptionPane.showMessageDialog(frame, "Dialog is closed.");
}
});
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
}
```
阅读全文