Java - 如何为Yes和No选项添加JOptionPane

min*_*ino 3 java swing actionlistener joptionpane

所以,我已经阅读了Java API,但似乎仍无法就如何做到这一点做出正面或反面.相信我,我已经尝试过了.我想要一个ActionListener来生成一个带有"你真的想要退出吗?"文本的消息框,其中选项是和否,退出程序或不退出,具体取决于所选按钮.

在我开始使用消息框打破它之前,这是ActionListener的内容:

exitItem.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent arg0) {
                        window.dispose();
                    }
                }
                );
Run Code Online (Sandbox Code Playgroud)

我怎样才能适当改变它以满足我的要求?

r3n*_*nj1 13

我想你想在你的内心做这样的事情ActionListener:

int selectedOption = JOptionPane.showConfirmDialog(null, 
                                  "Do you wanna close the window?", 
                                  "Choose", 
                                  JOptionPane.YES_NO_OPTION); 
if (selectedOption == JOptionPane.YES_OPTION) {
    window.dispose();
}
Run Code Online (Sandbox Code Playgroud)


nid*_*hin 6

final JOptionPane optionPane = new JOptionPane(
"The only way to close this dialog is by\n"
+ "pressing one of the following buttons.\n"
+ "Do you understand?",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述