当我单击 JOptionPane.showMessageDialog 中的 OK 按钮时,Java 程序退出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3170177/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:39:49  来源:igfitidea点击:

Java program exits when I click OK button in JOptionPane.showMessageDialog

javajframejoptionpane

提问by Haxed

when I click the OKbutton in second.java program, the program exit the program. I want it not to exit (since there is a thread running). I tried removing setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE).

当我在 second.java 程序中单击OK按钮时,程序退出程序。我希望它不要退出(因为有一个线程正在运行)。我尝试删除setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

alt text

替代文字



CODE

代码



import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class second extends JFrame implements ActionListener {

JLabel enterName;
JTextField name;
JButton click;
String storeName;

public second(){

    setLayout(null);
    setSize(300,250);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    enterName = new JLabel("Enter Your Name: ");
    click = new JButton("Click");
    name = new JTextField();
    enterName.setBounds(60,30,120,30);
    name.setBounds(80,60,130,30);
    click.setBounds(100,190,60,30);
    click.addActionListener(this);
    add(click);
    add(name);
    add(enterName);

}

public void actionPerformed(ActionEvent e) {

    if(e.getSource() == click) {

        storeName = name.getText();
        JOptionPane.showMessageDialog(null, "Hello" + storeName);
        System.exit(0);
    }
}

public static void main(String args[]){

    second s = new second();
    s.setVisible(true);
}
}


Many Thanks

非常感谢

回答by icktoofay

You'll need to remove the System.exit(0);line. That's all.

您需要删除该System.exit(0);行。就这样。