本文目錄一覽:
關於java窗口關閉的問題
我碰見的有兩種情況子窗口關閉導致父窗口也關閉!下面簡單介紹一下。。
一種是常規的,java原裝類庫引起的最常見的:
[java] view plain copy
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,在做圖標的時候出現的。下面舉例
[java] view plain copy
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();
}
}
注意第二種情況,不管怎麼setDefaultCloseOperation都會全關閉,因為子窗口是繼承了ApplicationFrame即整個應用。故所有父窗口都會關閉。
為什麼JAVA運行窗口關不掉?
因為你的代碼裡面沒有控制關閉的時間,你可以假如Windows.closer()進行關閉
JAVA運行的窗口關不上,怎麼解決
frm.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
添加窗口監聽器,還有推薦使用對應的Adapter比較好,因為實現介面的話要實現所有方法,Adapter實現了對應監聽器介面的所有方法,只是方法體內為空,只需要調用需要的方法即可。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/303330.html