在java中创建一个退出按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22286695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
create an exit button in java?
提问by user3355624
I'm a beginner in java, I'm practicing a Project that have should create an exit button that exit the program when we press it. But when I run this project in JDK the exit button is not working.
我是 Java 的初学者,我正在练习一个项目,该项目应该创建一个退出按钮,当我们按下它时退出程序。但是当我在 JDK 中运行这个项目时,退出按钮不起作用。
How can I make exit button work?
如何使退出按钮工作?
回答by Orel Eraki
There two ways for closing a window:
关闭窗口有两种方法:
- Xexit button at the top side of the window.
- Custom exit button.
- X窗口顶部的退出按钮。
- 自定义退出按钮。
Solution for 1
解决方案 1
To achieve it you should set for the JFrame the suitable default action you want to produce when clicking on X
.
要实现它,您应该为 JFrame 设置单击 时要生成的合适的默认操作X
。
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
Solution for 2
解决方案 2
this.dispose();
回答by blueygh2
If you want a JButton that closes the application, you would create the button:
如果您想要关闭应用程序的 JButton,您可以创建按钮:
JButton Button = new JButton("Close");
Then you would add a custom handler to the button:
然后,您将向按钮添加自定义处理程序:
Button.addActionListener (new ActionListener ()) {
public void actionPerformed (ActionEvent e) {
System.exit(0);
}
};
Then you would add the button to the frame or panel.
然后将按钮添加到框架或面板。
frame.add(button);
(If your frame is called frame)
(如果您的框架称为框架)
回答by Wajeeh Awan
if you want to create a message of yes_no option than follow the given code whenever u press the exit button you have created in J Frame so it will show a dialog message confirm if you want to Exit click yes so your app will be closed.
private void JbtnExitActionPerformed(java.awt.event.ActionEvent evt) {
如果你想创建 yes_no 选项的消息,而不是在你按下你在 J Frame 中创建的退出按钮时遵循给定的代码,这样它就会显示一个对话框消息,确认你是否要退出单击是,这样你的应用程序将被关闭。
私人无效JbtnExitActionPerformed(java.awt.event.ActionEvent evt){
Frame = new JFrame("Exit");
if (JOptionPane.showConfirmDialog( Frame,"confirm if you Want to Exit","Name of the Application or Title",
JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
System.exit(0);