在JOptionPane中设置默认关闭操作

时间:2017-12-14 08:08:05

标签: java swing joptionpane

如何设置红色' X'按钮关闭应用程序?我知道如何在JFrame中完成它,但我不知道如何在JOptionPane中设置它。

目前,点击红色' X'初始化游戏而不是退出应用程序。

JOptionPane.showMessageDialog(null, panel, "Let's Play!", JOptionPane.QUESTION_MESSAGE, icon);

2 个答案:

答案 0 :(得分:0)

使用ConfirmDialog。根据操作,您将获得不同的值(-1,0,1)。

int i = JOptionPane.showConfirmDialog(null, "Test", "test", JOptionPane.YES_NO_OPTION);
System.out.println(i);

" X"返回-1,"是"返回0和"否"返回1。现在您可以根据值

选择是否应该开始游戏

答案 1 :(得分:0)

编写自己的JOptionDialog并观察结束事件:

import javax.swing.*;
import java.awt.event.*;

public class MyOwnCloseOption extends JOptionPane{

    //just to keep the names compliant
    public static String panel = "Your Message!";

    private Runnable closingRoutine;

    public MyOwnCloseOption(Runnable closingRoutine){
        super(panel, JOptionPane.QUESTION_MESSAGE);
        this.closingRoutine = closingRoutine;

    }

    public void showMessage(){
        JDialog dialog = createDialog("Let's Play!");
        dialog.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e){
                closingRoutine.run();
            }
        });
        //From Documentation (Java SE7): java.awt.Dialog:
        //"setVisible(true): If the dialog is not already visible, this call will not return until the dialog is hidden by calling setVisible(false) or dispose"
        dialog.setVisible(true);
        dialog.dispose();
    }

    public static void main(String[] args){
        //The Original code
        //JOptionPane.showMessageDialog(null, panel, JOptionPane.QUESTION_MESSAGE);
        MyOwnCloseOption myOwnCloseOption = new MyOwnCloseOption(new Runnable(){
            @Override
            public void run(){
                System.out.println("Okay. -______-");
                System.exit(0);
            }
        });
        myOwnCloseOption.showMessage();
        System.out.println("Starting the Game!");
        //something keeps the application still alive?
        System.exit(0);
    }
}