如何从父对话框 Java Swing 中删除子 jdialog 引用



我想从父对话框中删除子对话框,而无需单击子对话框。 并且无需编辑父对话框创建源代码。父对话框正在重复使用,并且仅创建一次。

我希望这是你的答案:

package stack;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DialogShower implements WindowListener {
JFrame frame;
JButton showButton;
ParentDialog parentDialog;
boolean fristTimeOpen = true;
public DialogShower() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
parentDialog = new ParentDialog();
parentDialog.addWindowListener(this);
showButton = new JButton("Show me");
showButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (fristTimeOpen) {
parentDialog.childDialog.setVisible(true);
}
parentDialog.setVisible(true);
}
});
frame.getContentPane().add(showButton);
frame.setSize(100, 100);
frame.setVisible(true);
}
public class ParentDialog extends JDialog {
ChildDialog childDialog;
public ParentDialog() {
super(frame, "ParentDialog", true);
childDialog = new ChildDialog();
}
public class ChildDialog extends JDialog {
JLabel label;
public ChildDialog() {
super(ParentDialog.this, "childDailg", false);
label = new JLabel("Notification : Dialog");
getContentPane().add(label);
setLocation(300, 300);
}
}
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("2");
}
@Override
public void windowClosing(WindowEvent e) {
fristTimeOpen = false;
parentDialog.childDialog.dispose();
}
@Override
public void windowDeactivated(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowOpened(WindowEvent e) {
}
public static void main(String[] args) {
new DialogShower();
}
}

当您单击按钮Show me打开父对话框和子对话框时,我创建了两个对话框。关闭父对话框时,它会自动关闭子对话框。我使用WindowListener对父对话框关闭执行操作。当您再次打开父对话框时,它不会打开子对话框;

最新更新