Reputation: 3
int confirmDialog = JOptionPane.showConfirmDialog(null, "You selected quit! \nAre you sure you want to quit?", "Selected Quit", JOptionPane.YES_NO_OPTION);
if(confirmDialog == 0)
System.exit(0);
//focus under this comment here
if(confirmDialog == 1) {
game.reset();
displayBoard();
}
I made a game with a board. I have a quit button to quit the game. When the user clicks the button they are prompted with the JOptionPane above. It is asking them if they are sure they want to quit. I am able to close the game, but my problem is when the user selects "no". I want the user to be able to click "no" and have it so the game resets which it does, I can see the board reseting. But the optionPane does not go away and i want the OptionPane to go away so they can play.
Upvotes: 0
Views: 304
Reputation: 17971
Since your confirm dialog has two possible outcomes you can write a simple if-else
block like this:
int confirmDialog = JOptionPane.showConfirmDialog(null, "You selected quit! \nAre you sure you want to quit?", "Selected Quit", JOptionPane.YES_NO_OPTION);
if(confirmDialog == JOptionPane.YES_OPTION) {
System.exit(0);
//focus under this comment here
} else {
game.reset();
displayBoard();
}
Note the use of static field JOptionPane.YES_OPTION makes your code more robust.
I can see the board reseting. But the optionPane does not go away and i want the OptionPane to go away so they can play.
Check if something in game.reset()
is blocking the Event Dispatch Thread (a.k.a. EDT). The EDT is a single and special thread where Swing components creation and update take place. If there's some time consuming task blocking the EDT your GUI may become unresponsive. See more in Concurrency in Swing trail.
About this line:
System.exit(0);
This method terminates the currently running JVM as stated in System.exit(int status) javadoc. This is actually a bad practice. When working with Swing you should call dispose() on your JFrame
and that should terminate the JVM if there's no pending threads working.
Upvotes: 4