Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JOptionPane YES/No Options Confirm Dialog Box Issue

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) {      } } 
like image 584
Sobiaholic Avatar asked Dec 31 '11 16:12

Sobiaholic


People also ask

How do I add options to JOptionPane in Java?

You can use any of the JOptionPane's option constants, you just need to supply a options array of size 4: public static void main(String[] args) { String[] options = new String[] {"Yes", "No", "Maybe", "Cancel"}; int response = JOptionPane. showOptionDialog(null, "Message", "Title", JOptionPane.

How do you make a dialogue box in Java?

How to Create a Dialog Box in Java. There are several ways in which a developer can create a dialog box in Java. Programmers can use JDialog, JOptionPane, or ProgressMonitor. To create a standard dialog, you can simply use the JOptionPane class.


1 Answers

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

like image 126
ziesemer Avatar answered Sep 18 '22 12:09

ziesemer