Search code examples
javaswingjoptionpane

JOptionPane.JOptionDialog get value of input for use in if statements


I have a program that has 2 options in an option dialog and one option should execute one part, the other should execute another part. (I will do this with if statements)

Object reply1;  //Variable that Should be not an object???

    Object[] option = { "Choose a Random Number", "Input a Number"};   //option labels

    JOptionPane pane1;
    pane1 = new JOptionPane.showOptionDialog(null,
        "Text explaining which option to choose\n",
        "Title",
        JOptionPane.YES_NO_OPTION,
        JOptionPane.PLAIN_MESSAGE,
        null,
        option,
        option[0]);

           reply1 = pane1.getInputValue();  //this is the problem.

How do I set a variable to equal a the option chosen and what type of variable should it be?

It has been initialized as an int, String, and Object when I was debugging.


Solution

  • You can simply use an int return value:

    int reply1 = JOptionPane.showOptionDialog(null,
       "Text explaining which option to choose\n",
       "Title",
       JOptionPane.YES_NO_OPTION,
       JOptionPane.PLAIN_MESSAGE,
       null,
       option,
       option[0]);
    
       if (reply1 == JOptionPane.YES_OPTION) {
          // option 1
       } else if (reply1 == JOptionPane.NO_OPTION) {
          // option 2
       }
    

    Related: JOptionPane