Java Swing 只关闭当前窗体

时间:2023-01-28 14:47:15

看到很多人都在询问怎么在java swing中只关闭当前的窗体,因此写下此文。

主界面主要是有两个JButton,一个是通过按钮事件调起另一个JFame,另一个是关闭当前窗体。

1、关闭当前窗体不能使用setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)方法,可以使用setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

2、通过JButton事件不能使用exit(),这样会使得整个程序的窗体全部关闭,可以使用dispose();这样就只关闭了当前窗体


具体实现如下:

NewFrame.java

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class NewFrame extends JFrame {

/**
* called another JFrame
* close this JFrame
* write by Jimmy.li
* time:2016/4/6 22:55
*/
private static final long serialVersionUID = 1L;

public NewFrame() {
// 普通按钮控件
JFrame jf = new JFrame("main");
Toolkit tk = this.getToolkit();// 得到窗口工具条
int width = 650;
int height = 500;
Dimension dm = tk.getScreenSize();
jf.setSize(300, 200);// 设置程序的大小
jf.setLocation((int) (dm.getWidth() - width) / 2,
(int) (dm.getHeight() - height) / 2);// 显示在屏幕*
jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jf.setVisible(true);
JPanel contentPane = new JPanel();
jf.setContentPane(contentPane);

// 创建两个按钮,并且将按钮添加到内容面板中

JButton another = new JButton("另起页面");

JButton close = new JButton("关闭");

contentPane.add(another);

contentPane.add(close);

another.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
new exit();
}
});

close.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
}

public static void main(String[] args)

{
new NewFrame();

}
}


效果图如下:

Java Swing 只关闭当前窗体       Java Swing 只关闭当前窗体


只关闭exit的窗体,而不涉及父窗体。

exit.java代码如下

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
* called another JFrame close this JFrame write by Jimmy.li time:2016/4/6 22:55
*/

public class exit {

private static final int WIDTH = 300;

private static final int HEIGHT = 200;

public exit() {
// 普通按钮控件
final JFrame jf = new JFrame("exit");
jf.setSize(WIDTH, HEIGHT);
jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jf.setVisible(true);
JPanel contentPane = new JPanel();
jf.setContentPane(contentPane);

// 创建两个按钮并添加到内容面板

JButton close1 = new JButton("关闭");
contentPane.add(close1);

close1.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
// System.exit(0);
jf.dispose();
}
});
}

public static void main(String[] args)

{
new exit();
}

}

这样通过点击关闭按钮,只关闭了当前的exit窗体,而父窗体还存在。




Good luck!

Write by Jimmy.li