JOptionPane showConfirmDialog example

Here's some sample code that demonstrates how to use the Java JOptionPane showConfirmDialog method. I've included the method call in the context of a real containing method (doExitAction()) so you can see how it might be used in real-world code.

Java JOptionPane showConfirmDialog example

public void doExitAction()
{
  // if the output area is empty just quit, otherwise prompt before leaving
  if (textAreaController.getTextAreaText().trim().equals(""))
  {
    System.exit(0);
  }
  else
  {
    String message = "There are commands in the output buffer - really quit?";
    String title = "Really Quit?";
    // display the JOptionPane showConfirmDialog
    int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
    if (reply == JOptionPane.YES_OPTION)
    {
      System.exit(0);
    }
  }
}

The doExitAction() method basically says "If the text area is blank just go ahead and quit, but if there is text in there prompt the user before quitting. If the user says they are sure they're ready to quit, go ahead and exit." As you can see the method call returns an int value, which you can test to see which button the user selected.