Pixel
Pixel

Reputation: 369

Handle yes or no in JOptionPane correctly? - in Java

Got a JOptionPane which contains a "Continue" button and a "Close procedure" button. How do i handle these buttons in a if / else statement,

So if you click continue , nothing will happens in the if, but if you click "close procedure" it much runs the code i have written.

my code so far:

public void getConfirmation() {

    JFrame frame = new JFrame();        
    Object[] options = {"Continue","Stop procedure"};

    int n = JOptionPane.showOptionDialog(null,
            "Would you like to continue or stop procedure?","Please confirm",
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null,options,options[0]); 

    frame.toFront();
    frame.repaint();
    frame.setAlwaysOnTop(true);

    if(JOptionPane.YES_OPTION == 1) {

        // Program will keep going
    }

    else if (JOptionPane.NO_OPTION == 0) {

        System.out.println(" ");
        System.out.println("Procedure terminated" + "\n");
        menu.getMenu();
    }



}

Upvotes: 1

Views: 96

Answers (1)

fonZ
fonZ

Reputation: 2479

You should use n to compare, as you store the result in there.

int n = JOptionPane.showOptionDialog(null,
        "Would you like to continue or stop procedure?","Please confirm",
        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,null,options,options[0]); 

...
if (n == JOptionPane.YES_OPTION) {
    ...
}
else if (n == JOptionPane.NO_OPTION) {
    ...
}

Upvotes: 1

Related Questions