首页 > 编程知识 正文

为什么java窗口关不掉(java怎么关闭窗口)

时间:2023-12-20 12:40:57 阅读:318218 作者:YJSW

本文目录一览:

关于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实现了对应监听器接口的所有方法,只是方法体内为空,只需要调用需要的方法即可。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。