Question

How is the X button represented in a JOptionPane?

when my program starts, a JOptionPane comes up and straight after that a JFrame comes up. What is want is, when the user presses the X button, for the system to exist and don't show any JFrame, instead close both the JOptionPane and don't show the JFrame.

so something like this but I don't know how to represent the X button;

if (reply == JOptionPane.NO_OPTION){
        System.exit(ABORT);
        }
Was it helpful?

Solution

You could just test it yourself:

public static void main(String[] args) {
  int result = JOptionPane.showConfirmDialog(null, "This is a test",
        "Test", JOptionPane.OK_CANCEL_OPTION);

  System.out.println("result: " + result);
}

It depends on which JOptionPane you use, but for showConformDialog, you'll find that it returns -1 which is the same as JOptionPane.CLOSED_OPTION. This is well described in the JOptionPane API which states:

public static final int CLOSED_OPTION
Return value from class method if user closes window without selecting anything, more than likely this should be treated as either a CANCEL_OPTION or NO_OPTION.


Edit
You ask about JOptionPane with Yes/No option, again, test it yourself. e.g.,

import javax.swing.JOptionPane;

public class TestOptionPane {
   public static void main(String[] args) {
      int result = JOptionPane.showConfirmDialog(null, "This is a test",
            "Test", JOptionPane.YES_NO_OPTION);

      System.out.println("result: " + result);

      switch (result) {
      case JOptionPane.YES_OPTION:
         System.out.println("Yes Pressed");
         break;
      case JOptionPane.NO_OPTION:
         System.out.println("No Pressed");
         break;
      case JOptionPane.CLOSED_OPTION:
         System.out.println("Dialog closed");
         break;    
      default:
         System.out.println("Default");
         break;
      }
   }
}

Edit 2
You state:

I have tried that but it is not working. when I press the X button at the right top corner, it still brings up the JFrame.

Then your logic is wrong.

What if you used the switch above and instead of println's closed the application if the user aborts.

OTHER TIPS

the JFrame has a method dedicated for this

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); will tell the application that when the X is pressed that the frame should be closed and the compiler told to stop

another function is that you could set the JFrame visibility to false

frame.setVisible(false);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top