有人知道怎样让一个JButton关闭GUI吗?我认为应该是类似于System.CLOSE(0);
这样,但是没有起作用。也可能是exitActionPerformed(evt);
,但这也没有起作用。只需要一行代码就可以。
编辑:不用了,答案是System.exit(0);
。谢谢大家的帮助!
有人知道怎样让一个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);
}
}
这可能不是最好的方法,但它是一个起点。例如,该类可以被设置为公共类而不是作为另一个类中的私有类。
this.dispose();
如果你正在使用NetBeans GUI设计器,添加这个actionListener最简单的方法是进入GUI编辑器窗口并双击JButton组件。这样做将自动创建一个actionListener和actionEvent,可以由您手动修改。
查看JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)
1。你也可以使用EXIT_ON_CLOSE
,但最好明确清理任何运行中的线程,然后当最后一个GUI元素变得不可见时,EDT和JRE将结束。
触发此操作的“按钮”已经在一个框架上。
DISPOSE_ON_CLOSE
功能的演示,详见How to best position Swing GUIs?。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()
与JFrame.dispose()
的区别在此:https://dev59.com/GmYr5IYBdhLWcg3w1NhY - ciri-cuervopublic 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{} */
close.addActionListner(new CloseListener());
is misspelled. should beclose.addActionListener(new CloseListener());
- A. Larsson