如何在按下JButton时关闭GUI界面?

20

有人知道怎样让一个JButton关闭GUI吗?我认为应该是类似于System.CLOSE(0);这样,但是没有起作用。也可能是exitActionPerformed(evt);,但这也没有起作用。只需要一行代码就可以。

编辑:不用了,答案是System.exit(0);。谢谢大家的帮助!

7个回答

27

添加您的按钮:

JButton close = new JButton("Close");

添加一个ActionListener:

close.addActionListner(new CloseListener());

添加一个实现ActionListener接口的Listener类,并覆盖其主函数:

private class CloseListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        //DO SOMETHING
        System.exit(0);
    }
}

这可能不是最好的方法,但它是一个起点。例如,该类可以被设置为公共类而不是作为另一个类中的私有类。


close.addActionListner(new CloseListener()); is misspelled. should be close.addActionListener(new CloseListener()); - A. Larsson

9
使用System.exit(0);会关闭整个进程。这是您想要的吗?还是您只想关闭GUI窗口并允许进程继续运行?
最简单、最快速、最可靠的方法是在JButton上添加actionListener,当点击JButton时,将执行下面的代码行以简单关闭JFrame或JPanel:
this.dispose();

如果你正在使用NetBeans GUI设计器,添加这个actionListener最简单的方法是进入GUI编辑器窗口并双击JButton组件。这样做将自动创建一个actionListener和actionEvent,可以由您手动修改。


谢谢您提供dispose()建议。但是,在dispose()指令之后,您如何实际终止GUI线程呢? - Employee

7

1
设置了EXIT_ON_CLOSEDISPOSE_ON_CLOSE之后,您可以调度一个WINDOW_CLOSING事件,如此处所示。 - trashgod
如果我们需要逐一关闭框架怎么办? - OldSchool
@Rouftantical 你显然连代码都没试过。 - Andrew Thompson

4
您可以使用 Window#dispose() 方法来释放所有本地屏幕资源、子组件和其拥有的所有子级。 System.exit(0) 将终止当前正在运行的 Java 虚拟机。

3

在Java 8中,你可以使用Lambda表达式使代码更简洁。

关闭应用程序

JButton btnClose = new JButton("Close");
btnClose.addActionListener(e -> System.exit(0));

关闭窗口

JButton btnClose = new JButton("Close");
btnClose.addActionListener(e -> this.dispose());

有什么区别? - Adrian Simionescu
System.exit()JFrame.dispose()的区别在此:https://dev59.com/GmYr5IYBdhLWcg3w1NhY - ciri-cuervo

2
创建一个方法并调用它来关闭JFrame窗口,例如:
public void CloseJframe(){
    super.dispose();
}

0
JButton close = new JButton("Close");
close.addActionListener(this);
public void actionPerformed(ActionEvent closing) { 
// getSource() checks for the source of clicked Button , compares with the name of button in which here is close .     
if(closing.getSource()==close)
   System.exit(0);
   // This exit Your GUI 
}
/*Some Answers were asking for @override which is overriding the method the super class or the parent class and creating different objects and etc which makes the answer too long . Note : we just need to import java.awt.*; and java.swing.*; and Adding this command : class className implements actionListener{} */

请您提供一些书面信息,说明这段代码如何回答了原帖的问题,以及为什么它与其他已发布的答案不同或更好? - wahwahwah
当然,有些答案要求使用@override来覆盖超类或父类的方法,并创建不同的对象等,这使得答案过长。 注意:我们只需要导入java.awt.;和java.swing.;并添加此命令:class className implements actionListener{}。 - Niamatullah Bakhshi
把那个放在你的答案里,不要放在评论里 :) - wahwahwah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接