JOptionPane YES/No Options Confirm Dialog Box Issue

JavaSwingJfilechooser

Java Problem Overview


I've created a JOptionPane and it only has two buttons YES_NO_OPTION .

After JOptionPane.showConfirmDialog pops out , I want to click YES BUTTON to continue opening the JFileChooser and if I clicked NO BUTTON it should cancel the operation.

It seems pretty easy but I'm not sure where is my mistake.

Code Snippet:

if (textArea.getLineCount() >= 1) {  //The condition to show the dialog if there is text inside the textArea

    int dialogButton = JOptionPane.YES_NO_OPTION;
    JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);

    if (dialogButton == JOptionPane.YES_OPTION) { //The ISSUE is here
					
    JFileChooser saveFile = new JFileChooser();
    int saveOption = saveFile.showSaveDialog(frame);
    if(saveOption == JFileChooser.APPROVE_OPTION) {

    try {
    	BufferedWriter fileWriter = new BufferedWriter(new FileWriter(saveFile.getSelectedFile().getPath()));
    	fileWriter.write(textArea.getText());
    	fileWriter.close();
    } catch(Exception ex) {

    }
}

Java Solutions


Solution 1 - Java

You need to look at the return value of the call to showConfirmDialog. I.E.:

int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){
  // Saving code here
}

You were testing against dialogButton, which you were using to set the buttons that should be displayed by the dialog, and this variable was never updated - so dialogButton would never have been anything other than JOptionPane.YES_NO_OPTION.

Per the Javadoc for showConfirmDialog:

> Returns: an integer indicating the option selected by the user

Solution 2 - Java

Try this,

int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
  System.out.println("Yes option");
} else {
  System.out.println("No Option");
} 

Solution 3 - Java

int opcion = JOptionPane.showConfirmDialog(null, "Realmente deseas salir?", "Aviso", JOptionPane.YES_NO_OPTION);

if (opcion == 0) { //The ISSUE is here
   System.out.print("si");
} else {
   System.out.print("no");
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSobiaholicView Question on Stackoverflow
Solution 1 - JavaziesemerView Answer on Stackoverflow
Solution 2 - JavaALVView Answer on Stackoverflow
Solution 3 - Javaaxlfire1View Answer on Stackoverflow