【发布时间】:2011-12-26 03:14:49
【问题描述】:
有人知道如何让 jbutton 关闭 gui 吗?我认为它就像System.CLOSE(0); 但那不起作用。它也可能是exitActionPerformed(evt);,但这也不起作用。只需这行代码即可。
编辑:别介意伙计们。答案是System.exit(0);。不过感谢您的帮助!
【问题讨论】:
标签: java swing user-interface jbutton
有人知道如何让 jbutton 关闭 gui 吗?我认为它就像System.CLOSE(0); 但那不起作用。它也可能是exitActionPerformed(evt);,但这也不起作用。只需这行代码即可。
编辑:别介意伙计们。答案是System.exit(0);。不过感谢您的帮助!
【问题讨论】:
标签: java swing user-interface jbutton
添加您的按钮:
JButton close = new JButton("Close");
添加一个 ActionListener:
close.addActionListner(new CloseListener());
为实现ActionListener接口的Listener添加一个类并覆盖其main函数:
private class CloseListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//DO SOMETHING
System.exit(0);
}
}
这可能不是最好的方法,但它是一个起点。例如,该类可以公开,而不是作为另一个类中的私有类。
【讨论】:
close.addActionListner(new CloseListener()); 拼写错误。应该是close.addActionListener(new CloseListener());
通过使用 System.exit(0);你会关闭整个过程。这是您想要的还是打算只关闭 GUI 窗口并允许进程继续运行?
通过单击 JButton 来简单地关闭 JFrame 或 JPanel 的最快、最简单和最可靠的方法是向 JButton 添加一个 actionListener,当单击 JButton 时它将执行以下代码行:
this.dispose();
如果您使用的是 NetBeans GUI 设计器,添加此 actionListener 的最简单方法是进入 GUI 编辑器窗口并双击 JButton 组件。这样做会自动创建一个actionListener和actionEvent,你可以手动修改。
【讨论】:
见JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)1。您也可以使用EXIT_ON_CLOSE,但最好显式清理所有正在运行的线程,然后当最后一个 GUI 元素变得不可见时,EDT 和 JRE 将结束。
调用此操作的“按钮”已经在框架上。
DISPOSE_ON_CLOSE 功能的一部分。【讨论】:
EXIT_ON_CLOSE 或DISPOSE_ON_CLOSE,您可以发送WINDOW_CLOSING 事件,如here 所示。
您可以使用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());
【讨论】:
System.exit() vs JFrame.dispose() 这里:stackoverflow.com/questions/13360430/…
创建一个方法并调用它来关闭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{} */
【讨论】: