【问题标题】:How to close child jFrames automatically when i close the parent?关闭父级时如何自动关闭子级jFrame?
【发布时间】:2016-07-04 13:47:12
【问题描述】:

我在包 JFrame 中有一个父 JFrame 和两个“子”JFrame。想象一下,我打开父 JFrame,然后是子 JFrame——目前所有 3 个表单都是打开的。现在我关闭父 JFrame。

如何在关闭父 JFrame 后自动关闭所有子框架?
这是我的代码:

班级家长:
公共类父扩展 JFrame {

public Parent() {

    JButton child1 = new JButton("child1");
    child1.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new Child1().setVisible(true);;
        }
    });

    JButton child2 = new JButton("child2");
    child2.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new Child2().setVisible(true);
        }
    });
    JButton closeAllJframe = new JButton("closeAllJframe");
    closeAllJframe.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            dispose();
        }
    });

    this.setBounds(500, 200, 400, 200);
    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            dispose();
        }
    });
    JPanel jPanel = new JPanel();
    jPanel.add(child1);
    jPanel.add(child2);
    jPanel.add(closeAllJframe);
    this.add(jPanel);
}

@Override
public void dispose() {
    super.dispose();
}

public static void main(String[] args) {
    new Parent().setVisible(true);
}}  

类 Child1:

公共类 Child1 扩展 JFrame {

public Child1() {
    this.setBounds(200, 300, 300, 200);
    this.setTitle("child 1");
}}

类 Child2:

公共类 Child2 扩展 JFrame {

public Child2() {
    this.setBounds(200, 300, 300, 200);
    this.setTitle("child 1");
}}

【问题讨论】:

  • forms?你是说jframes吗?
  • 如果是jframes,则添加窗口监听器并在窗口关闭事件上调用子jframes上的dispose。
  • 1) 提示:添加@FastSnail(或重要的@)以通知此人有新评论。 2) 为了尽快获得更好的帮助,请发布minimal reproducible example 或Short, Self Contained, Correct Example。 3) 见The Use of Multiple JFrames, Good/Bad Practice? 提示:“子框架”应该是对话框。
  • @FastSnail:是的,我愿意。你能解释更多吗?谢谢。
  • “你和我在一起吗?” 我收到了新评论的通知,如果你是这个意思的话..

标签: java swing jframe


【解决方案1】:

给框架添加一个窗口监听器然后实现windowClosed(WindowEvent e)方法Javadoc about WindowListener

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多