我想要做的是有一个JButton
,当您点击它时,它将关闭JFrame
/应用程序。我有一个JButton
,但我想知道如何使它关闭当前打开的窗口。使用JButton关闭当前打开的应用程序
回答
只需使用JFrame的dispose()方法即可。见Javadoc。
附录:另外,您可能希望将JFrame的默认关闭操作设置为“退出”,而不是默认的“隐藏”。当你创建你的框架时做。
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// Do whatever your application does.
frame.dispose(); // With this you close the frame.
*“..”退出“,而不是默认的”隐藏“。”*更好的是'DISPOSE_ON_CLOSE'。它将只在所有非守护线程完成运行后退出虚拟机。如果虚拟机在帧关闭后一直运行无限,这是程序员需要明确清理/关闭的线程的迹象。 –
在JButton
的actionPerformed()
,只需添加System.exit(0)
。你已准备好出发。
@AndrewThompson哦,是的。非零意味着异常终止。 –
@AndrewThompson有点难以摆脱MR。但是..我认为你应该在那里留下'噪音'。 –
呃(耸耸肩)如果这个人编辑的答案包括建议(这是我的偏好),评论就变成了噪音。 –
将一个监听器注册到您的按钮,然后在单击按钮上调用System.exit(0)。
JButton button = new JButton("Close");
button.addActionLister(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
*“可能会因为我在没有IDE的情况下编写此代码而发生语法更改”*不错,给出您从..memory,experience ..类型输入的内容。在使用我的编译器检查细节之后,我做了一些调整。 –
谢谢@AndrewThompson :) – dinukadev
见从Closing an Application的ExitAction
。
这种方法与其他建议有点不同,因为它会将windowClosing()事件分派给Window。这将导致窗口基于窗口的关闭选项关闭,并将调用您可能已添加到窗口以处理windowClosing()事件的任何窗口侦听器。
使从包含的JFrame应用程序中的类的对象,然后dispose
它在一个按钮事件监听器:
为前。
public class Application extends JFrame {
private static final long serialVersionUID = 1L;
static Application app= new Application();
public Application{
setLayout(new FlowLayout());
Container pane =this.getContentPane();
JPanel right = new JPanel();
right.setLayout(new GridLayout(4,1));
ButtonEvent = new JButton("Button");
right.add(whiteList);
pane.add(right);
}
public class ButtonEvent implements ActionListener{
public void actionPerformed (ActionEvent event){
app.dispose();
dispose();
}
}
public static void main(String args[]){
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
app.setTitle("Application");
app.setSize(700,500);
app.setLocation(350, 100);
}
}
- 1. 关闭当前的应用程序,打开另一个
- 2. 打开外部应用程序并关闭当前应用程序
- 3. WPF关闭应用程序并重新打开当前窗口
- 4. 应用程序关闭前/应用程序打开前的Swift iOS 9+
- 5. 如何关闭当前打开的应用程序,当点击推送通知
- 6. 关闭之前打开的应用程序
- 7. 当另一个应用程序关闭时打开应用程序
- 8. 使用cmd打开和关闭程序
- 9. 检查当前应用程序打开或关闭时的Android alarmreceiver错误
- 10. WiX在卸载前关闭应用程序 - 关闭打开的应用程序消息
- 11. 使用VBS关闭打开的OneNote应用程序
- 12. 应用程序当前关闭关闭窗口提示
- 13. 如何在用户关闭当前应用程序时打开另一个应用程序?
- 14. 在windows上使用C++打开和关闭应用程序
- 15. 使用蓝牙和应用程序打开/关闭设备
- 16. 关闭当前打开的选项卡
- 17. 扩展程序获取当前打开的应用程序
- 18. 当应用程序打开时调用哪个方法?当应用程序关闭?
- 19. 关闭通用应用程序中打开的文件
- 20. 如何关闭其他用户打开的Outlook应用程序
- 21. 关闭delphi应用程序以及它打开的另一个应用程序
- 22. 使用ui开关关闭应用程序中的声音xcode
- 23. 当我的应用程序开启和关闭时,如何打开和关闭WP7中的gps?
- 24. 用地图放大当前位置打开的应用程序
- 25. 如何获取用户当前打开的应用程序?
- 26. 使文件在当前WPF应用程序中打开
- 27. 应用程序是否允许用户打开或关闭iCloud?
- 28. 当应用程序B关闭时关闭应用程序A:Mac OS X 10.7.3
- 29. 在Python中按顺序打开和关闭应用程序
- 30. 使用bash打开和关闭进程
1)使用['setDefaultCloseOperation(DISPOSE_ON_CLOSE)'](http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation%28int%29 )。 “按钮”(框架右上方)内置。 2)*“谢谢,诺亚”*噪音,不要说了。 –