JOptionPane YES / No Options Confirm dialog box Problem -Java

I created JOptionPane and it has only two YES_NO_OPTION buttons.

After JOptionPane.showConfirmDialog pops up, I want to press YES BUTTON to continue opening JFileChooser , and if I pressed NO BUTTON , it should cancel the operation.

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

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){ } } 
+46
java swing jfilechooser
Dec 31 '11 at 16:14
source share
3 answers

You need to look at the return value of the call on 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 tested against the dialogButton that you used to set the buttons that should appear in the dialog box, and this variable was never updated - so dialogButton would never be anything other than JOptionPane.YES_NO_OPTION .

In Javadoc for showConfirmDialog :

Returns: an integer indicating the option selected by the user

+85
Dec 31 '11 at 16:16
source share

Try it,

 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"); } 
+23
Feb 09 '13 at 4:33
source share
 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"); } 
+6
Apr 7 '14 at 2:29
source share



All Articles