如何在推送JButton时关闭GUI

有谁知道如何使jbutton关闭gui? 我认为它就像System.CLOSE(0); 但那没用。 它也可以是exitActionPerformed(evt); ,但这也不起作用。 只需要代码行就可以了。

编辑:别介意人。 答案是System.exit(0); 。 谢谢你的帮助!

添加按钮:

 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); } } 

这可能不是最好的方式,但它是一个重点。 例如,类可以公开,而不是另一个类中的私有类。

请参见JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE) 1 。 您也可以使用EXIT_ON_CLOSE ,但最好明确清理任何正在运行的线程,然后当最后一个GUI元素变得不可见时,EDT和JRE将结束。

调用此操作的“按钮”已在框架上。

  1. 请参阅如何最好地定位Swing GUI的 答案 ? 用于演示。 DISPOSE_ON_CLOSEfunction。

    单击X按钮关闭所有3帧后,JRE将结束。

通过使用System.exit(0); 你会关闭整个过程。 这是你想要的,或者你打算只关闭GUI窗口并允许进程继续运行?

通过单击JButton简单地关闭JFrame或JPanel的最快,最简单和最健壮的方法是向JButton添加一个actionListener,它将在单击JButton时执行下面的代码行:

 this.dispose(); 

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

您可以使用Window#dispose()方法释放所有本机屏幕资源,子组件及其所有子级。

System.exit(0)将终止当前运行的Java虚拟机。

在Java 8中,您可以使用Lambda表达式使其更简单。

关闭申请

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

关闭窗口

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

创建一个方法并调用它来关闭JFrame,例如:

 public void CloseJframe(){ super.dispose(); } 
 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{} */