我目前正在开发一个具有始终存在的主JFrame的工作应用程序.我目前有一个孩子JDialog按下按钮出现.此框架有一个JMenu,其中包含一个“退出显示”的项目.当我按下显示选项的注销时,我的任务是确保这个孩子JDialog消失.注销发生时,主显示器通过以下方式设置为不可见:
mainFrame.setVisible(false);
子JDialog具有默认的关闭操作:
DISPONSE_ON_CLOSE
当用户重新登录时,首先要做的是:
mainFrame.setVisible(true);
发生这种情况时,子对话框会显示备份.看看JDialog Javadoc,这似乎是预期的行为.然而,我还没有找到一种方法来打破父/子关系或完全摧毁孩子JDialog.似乎JDialog将一直保留到GC,这可能不会及时发生.
这是一个模拟我所看到的行为的示例程序:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
public class WindowTest {
public static void createAndShowGUI() {
JFrame aFrame = new JFrame("LAUNCHER");
final JFrame aParent = new JFrame("PARENT");
final JDialog aChild = new JDialog(aParent);
aParent.setSize(200,200);
final JToggleButton showParentButton = new JToggleButton("HIDE");
showParentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showParentButton.setText(!showParentButton.isSelected() ? "SHOW": "HIDE");
aParent.setVisible(!showParentButton.isSelected());
}
});
aChild.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
aChild.setSize(200,200);
aParent.addComponentListener(new ComponentAdapter() {
public void componentHidden(ComponentEvent e) {
aChild.dispose();
aChild.setVisible(false);
}
});
aFrame.setContentPane(showParentButton);
aFrame.pack();
aFrame.setVisible(true);
aParent.setVisible(true);
aChild.setVisible(true);
}
public static void main(String [] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
createAndShowGUI();
}
});
}
}
当父母被隐藏时,孩子就会被处理掉.显示父级时,孩子会显示备份.真正奇怪的是,当我按下孩子的X时:当父母被隐藏然后再次显示时,孩子不显示备份.
我看到的唯一区别是单击X也会触发WindowClosing事件.我尝试在上面的componentHidden方法中调度even:
//Added into the constructor
//add to the imports: import java.awt.event.WindowEvent;
aParent.addComponentListener(new ComponentAdapter() {
public void componentHidden(ComponentEvent e) {
aChild.dispose();
aChild.setVisible(false);
WindowEvent closingEvent =
new WindowEvent(aChild, WindowEvent.WINDOW_CLOSING);
aChild.dispatchEvent(closingEvent);
}
});
这并没有解决问题.
目前看起来我唯一的选择是将子类型更改为JFrame.我只是想知道是否有一种处理儿童JDialog的正确方法.
我目前在Redhat Enterprise Linux Server 6.4版上运行Java版本:1.7.0_76 64位.