<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">在编程之中,碰见的一个问题,感觉很简单,但是却由于那点知识的欠缺才会出错。</span>
我碰见的有两种情况子窗口关闭导致父窗口也关闭!下面简单介绍一下。。
一种是常规的,java原装类库引起的最常见的:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ParentFrame extends JFrame implements ActionListener {
private JButton jb = new JButton("显示子窗口");
public ParentFrame() {
super("父窗口");
this.add(jb);
jb.addActionListener(this);
this.setBounds(100, 100, 200, 300);
this.setVisible(true);
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
new ChildFrame();
}
public static void main(String[] args) {
new ParentFrame();
}
}
import javax.swing.JFrame;
public class ChildFrame extends JFrame {
public ChildFrame() {
super("子窗口");
this.setBounds(200, 200, 200, 300);
this.setVisible(true);
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
}
public static void main(String[] args) {
new ChildFrame();
}
}
这种情况是setDefaultCloseOperation()参数选择的问题。
EXIT_ON_CLOSE做参数的时候使用的是System.exit方法退出应用程序。故会关闭所有窗口。
而HIDE_ON_CLOSE参数表示调用已注册的WindowListener对象后自动隐藏窗体。
第二种是用地方放类库jfreeChart,在做图标的时候出现的。下面举例
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ParentFrame extends JFrame implements ActionListener {
private JButton jb = new JButton("显示子窗口");
public ParentFrame() {
super("父窗口");
this.add(jb);
jb.addActionListener(this);
this.setBounds(100, 100, 200, 300);
this.setVisible(true);
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
new ChildFrame();
}
public static void main(String[] args) {
new ParentFrame();
}
}
import javax.swing.JFrame;
public class ChildFrame extends ApplicationFrame {
public ChildFrame() {
super("子窗口");
this.setBounds(200, 200, 200, 300);
this.setVisible(true);
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
}
public static void main(String[] args) {
new ChildFrame();
}
}
注意第二种情况,不管怎么set
DefaultCloseOperation都会全关闭,因为子窗口是继承了ApplicationFrame即整个应用。故所有父窗口都会关闭。