Frage

i have create JOptionPane to display simple yes/no dialog box. But i have no idea how to configure my Yes/no button output.

public static void button1(){

  //Custom button text
Object[] options = {"Yes",
                    "No",};

int n = JOptionPane.showOptionDialog(frame,
"Do you want cake?  ",
"Cake",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[1]);

}

Desired Output :

JOptionPane box prompt Yes and No button
if user mouse click ok button display system.out.printf("I Like Cake, Yes")
otherwise system.out.printf("I dont like cake, no")

my current code only display jdialog message with default yes and no button. but do not have meaningful function currently.

My Tutorial Reference : Oracle Java

War es hilfreich?

Lösung 2

Use showConfirmDialog, intead of showOptionDialog

import javax.swing.JOptionPane;

public class TestDialog {
    public static void main(String[] args) {
       int cake =  JOptionPane.showConfirmDialog(null,
             "Do you want Cake?", "Cake", JOptionPane.YES_NO_OPTION);

       if (cake == JOptionPane.YES_OPTION) {
           System.out.println("I Like Cake, Yes");
       } else if (cake == JOptionPane.NO_OPTION) {
           System.out.println("I dont like cake, no");
       }
    }
}

Take a look at JOptionPane API. They give example usages of the different showXxxDialog

Andere Tipps

Add this code at last in your function.

    if (n == 0) {
        System.out.println("I Like Cake");
    } else if (n == 1) {
        System.out.println("I dont like cake");
    }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top