Search code examples
javabooleanjoptionpane

Using Boolean True/False with JOptionPane.YES_NO_OPTION


I have a series of four yes/no choices in four separate dialog boxes, the cumulative results of which will lead to one of twelve separate links (e.g., Yes/Yes/Yes/No -> link A, Yes/No/No/Yes -> link B, etc). The branching logic uses boolean values.

Here's what I have so far...just the first dialog box and printing the results for validation.

public class OutageGuideSelector{
    public static void main(String[] args){
        boolean contactServerUp;
        boolean vistaUp;
        boolean stormOutage;
        boolean vistaCSUp;
//
        int contactServerEntry = JOptionPane.showConfirmDialog(null,
                                 "Is the contact server up", "Please select",
                                 JOptionPane.YES_NO_OPTION);
        System.out.println("result from entry " + contactServerEntry);
        if(contactServerEntry==1) 
           contactServerUp = true;
        else
          if(contactServerEntry==0)
             contactServerUp = false; 
        /* System.out.println(contactServerUp); */
       }}

Right now, the results of clicking YES reults in a 0 being returned, NO results in a 1. Is this normal, seems counterintuitive, and there's nothing at docs.oracle.java that shows a clear example of the output values except this which seems to suggest that the public static final int YES_NO_OPTION default in 0.

Additionally, the line System.out.println(contactServerUp); comes back with an error that the field contactServerUp might not have been initialized when I un-comment it, so I can't see if my convert-int-to-boolean is working.

First: It appears that JOptionPane method does not include any boolean returns...except getWantsInput() which returns the value of the wantsInput property...so I assume I'm already being the most efficient I can with this. I'd like to know if there's an easier way.

Second, what am I missing that prevents my console output statement from recognizing the contactServerUp? Where's my misplaced semicolon?


Solution

  • According to the javadoc, when one of the showXxxDialog methods returns an integer, the possible values are:

    • YES_OPTION
    • NO_OPTION
    • CANCEL_OPTION
    • OK_OPTION
    • CLOSED_OPTION

    You should test against those constants:

    contactServerUp = (contactServerEntry == JOptionPane.YES_OPTION);