简体   繁体   中英

Having trouble with JOPtionPane

I'm a beginner to Java and I'm having some difficulty with a problem. I am using JOPtionPane to ask the user some questions. However, my difficulties are coming from the fact that I don't know how to handle exceptions properly when the user clicks the X or cancel anywhere in the program. Also, when I looked at the Java API and saw how to implement titles, I tried it but now what should be titles are being placed in the text field instead.

Quitting from other parts of the program also yields exceptions in main thread so I would like to be able to catch those and exit gracefully instead of erroring. Also, in the inputdialogs the title "Investment Advisor" is showing up inside the text field instead. I have looked at the API and it seems I am using proper form but obviously not. Same thing for the icons with the inputdialogs. I don't want them to show but the program doesn't compile and says cannot find symbol if I put them within the inputdialogs. It works for the optiondialog though.

ABOVE IS FROM BEFORE PROBLEM WAS SOLVED

Greatly appreciate those who are taking the time to read this.

Here is the code (note investment1 and investment2 are just simple static methods with the proper formulas):

EDITED BELOW CODE; JUST TRYING TO ADD ERROR CHECKING FOR EMPTY STRINGS

public static void main(String[] args) 
{  
String initialAmt_Str, targetAmt_Str, interestPct_Str, years_Str, result;
double principle = 0, target = 0, interest = 0;
int again = JOptionPane.NO_OPTION, time = 0;

NumberFormat fmt = NumberFormat.getCurrencyInstance();

do {  
     Object[] options = {"Compute years to reach target amount",
        "Compute target amount given number of years"};

     int choice = JOptionPane.showOptionDialog(null, "Please choose what you would like to do.",
            "Investment Advisor", JOptionPane.YES_NO_OPTION,
            JOptionPane.PLAIN_MESSAGE, null, options, null);

     if (choice != JOptionPane.CANCEL_OPTION) 
     {

        if (choice == 1) 
        {        
           initialAmt_Str = JOptionPane.showInputDialog (null, "Enter the principle:", "Investment Advisor", 
           JOptionPane.PLAIN_MESSAGE);

           if (initialAmt_Str != null) 
              principle = Double.parseDouble(initialAmt_Str);

           else 
              System.exit(0);


           interestPct_Str = JOptionPane.showInputDialog (null, "Enter the interest rate as a"
                        + " percentage (without the percent sign):", "Investment Advisor", JOptionPane.PLAIN_MESSAGE); 

           if (interestPct_Str != null) 
              interest = Double.parseDouble(interestPct_Str);

           else 
              System.exit(0); 


           years_Str = JOptionPane.showInputDialog (null, "Enter the amount of years:", "Investment Advisor", 
           JOptionPane.PLAIN_MESSAGE);

           if (years_Str != null) 
              time = Integer.parseInt(years_Str);

           else 
              System.exit(0);  

           result = "Your target amount given the number of years is " + 
              fmt.format(investment2(principle, interest, time)) + ".";

           JOptionPane.showMessageDialog (null, result, "Investment Advisor", JOptionPane.PLAIN_MESSAGE);

           again = JOptionPane.YES_OPTION;
        }
     }

     else 
        again = JOptionPane.NO_OPTION;


     if (choice == 0) 
     {
        initialAmt_Str = JOptionPane.showInputDialog (null,"Enter the principle:","Investment Advisor",
        JOptionPane.PLAIN_MESSAGE);

        if (initialAmt_Str != null) 
           principle = Double.parseDouble(initialAmt_Str);

        else 
           System.exit(0);


        interestPct_Str = JOptionPane.showInputDialog (null, "Enter the interest rate as a"
                        + " percentage (without the percent sign):", "Investment Advisor", JOptionPane.PLAIN_MESSAGE); 

        if (interestPct_Str != null) 
           interest = Double.parseDouble(interestPct_Str);

        else 
           System.exit(0); 


        targetAmt_Str = JOptionPane.showInputDialog (null, "Enter your target amount:", "Investment Advisor", 
        JOptionPane.PLAIN_MESSAGE);


        if (targetAmt_Str != null)
           target = Double.parseDouble(targetAmt_Str);

        else
           System.exit(0);

        result = "You will reach your target amount in " + 
              investment1(principle, target, interest) + 
              (investment1(principle, target, interest) == 1 ? " year." : " years.");

        JOptionPane.showMessageDialog (null, result, "Investment Advisor", JOptionPane.PLAIN_MESSAGE);

        again = JOptionPane.YES_OPTION;

     }

     if (again != JOptionPane.NO_OPTION) 
        again = JOptionPane.showConfirmDialog(null, "Find Another?", "", JOptionPane.YES_NO_OPTION, 
        JOptionPane.PLAIN_MESSAGE); 

} while (again == JOptionPane.YES_OPTION);
}  

If the user clicks the "x" close button JOptionPane will return JOptionPane.CLOSED_OPTION

You should start by checking for this...

if (choice != JOptionPane.CLOSED_OPTION) {
    // Do the normal stuff
} else {
    // Break out of the do loop
    break;
}

You should also beware, that using the JOptionPane.showOptionDialog the way you have, the JOptionPane will return the index of the option selected by the user.

That means that a return value of 0 means that the user selected "Compute years to reach target" and a return value of 1 means that the user selected "Compute target given number of years"

Using JOptionPane.NO_OPTION or JOptionPane.YES_OPTION may not net the results you are expecting...

Updated with example

Your restructure allows for a slightly "sneaky" option, instead of using break, I simple set the again variable to JOptionPane.NO_OPTION when the user closes the option dialog...

public static void main(String[] args) {
        String initialAmt_Str, targetAmt_Str, interestPct_Str, years_Str, result;
        double principle, target, interest;
        int again, time;

        NumberFormat fmt = NumberFormat.getCurrencyInstance();

        do {
            Object[] options = {"Compute years to reach target",
                "Compute target given number of years"};

            int choice = JOptionPane.showOptionDialog(null, "Please choose what you would like to do.",
                    "Investment Advisor", JOptionPane.YES_NO_OPTION,
                    JOptionPane.PLAIN_MESSAGE, null, options, null);

            if (choice != JOptionPane.CANCEL_OPTION) {

                if (choice == 1) {
                    JOptionPane.showMessageDialog(null, "Compute target given number of years");
                } else if (choice == 0) {
                    JOptionPane.showMessageDialog(null, "Compute years to reach target");
                }

                again = JOptionPane.showConfirmDialog(null, "Find Another?");

            } else {
                again = JOptionPane.NO_OPTION;
            }
        } while (again == JOptionPane.YES_OPTION);
    }

Updated with additional example to handle cancelled input

So, if the user clicks the "x" button on the input dialogs, they will return null . At this point, you need to check for the null result and make choices about how you want to handle it. In the example below, I simply set the again to equal JOptionPane.NO_OPTION

public static void main(String[] args) {
    String initialAmt_Str, targetAmt_Str, interestPct_Str, years_Str, result;
    double principle, target, interest;
    int again, time;

    NumberFormat fmt = NumberFormat.getCurrencyInstance();

    do {
        Object[] options = {"Compute years to reach target",
            "Compute target given number of years"};

        int choice = JOptionPane.showOptionDialog(null, "Please choose what you would like to do.",
                "Investment Advisor", JOptionPane.YES_NO_OPTION,
                JOptionPane.PLAIN_MESSAGE, null, options, null);

        if (choice != JOptionPane.CANCEL_OPTION) {

            again = JOptionPane.YES_OPTION;
            if (choice == 1) {
                String input = JOptionPane.showInputDialog("Enter the principle:", "Investment Advisor");
                if (input != null) {
                    // Process further...
                    System.out.println("Continue processing...");
                } else {
                    again = JOptionPane.NO_OPTION;
                }
            } else if (choice == 0) {
                String input = JOptionPane.showInputDialog("Enter your target amount:", "Investment Advisor");
                if (input != null) {
                    // Process further...
                    System.out.println("Continue processing...");
                } else {
                    again = JOptionPane.NO_OPTION;
                }
            }

            if (again != JOptionPane.NO_OPTION) {
                again = JOptionPane.showConfirmDialog(null, "Find Another?");
            }

        } else {
            again = JOptionPane.NO_OPTION;
        }
    } while (again == JOptionPane.YES_OPTION);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM