I'm using this code to confirm the user whether wants to quit or not when he CLICKS THE RED CROSS CLOSE BUTTON OF JFrame (right upper corner)
Object[] options = {"Quit, My Computing Fellow", "No, I want to Work more"};
int Answer = JOptionPane.showOptionDialog(null, "What would you like to do? ","Quit:Continue", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options,options[1]);
if(Answer == JOptionPane.YES_OPTION){
System.exit(0);
}
else if (Answer == JOptionPane.CANCEL_OPTION) {
return;
}
but the problem is if the user clicks CANCEL_OPTION the Frame Closes at all, but i want the user to still open the Frame and not allow the Frame to close. Guide me If I'm doing the blunder or something else?
just do this:
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
You can try something like this:
import javax.swing.*;
import java.awt.event.*;
public class MyFrame extends JFrame
{
public MyFrame()
{
setTitle("Close Me");
setSize(200,200);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent evt)
{
Object[] options = {"Quit, My Computing Fellow", "No, I want to Work more"};
int answer = JOptionPane.showOptionDialog(MyFrame.this, "What would you like to do? ","Quit:Continue", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options,options[1]);
if(answer == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
});
}
public static void main(String st[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
MyFrame mf = new MyFrame();
mf.setVisible(true);
}
});
}
}
As a side note I would suggest you to stick with java naming conventions. For example the variable name should never start with capital letter, class name should always start with capital letter .. And many more. Have a look at here Code Conventions for the Java Programming Language
try something like this:
{
...
yourFrame.setDefaultCloseOperation(close());
...
}
private int close() {
if(yourCondition)
return JFrame.DO_NOTHING_ON_CLOSE;
else
return JFrame.EXIT_ON_CLOSE;
}
I have a Real blunder
Object[] options = {"Quit, My Computing Fellow", "No, I want to Work more"};
int Answer = JOptionPane.showOptionDialog(null, "What would you like to do?","Quit:Continue", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options,options[1]);
if(Answer == JOptionPane.YES_OPTION){
System.exit(0);
}
else if (Answer == JOptionPane.CANCEL_OPTION) {
return;
}
It was clear that I have two Options i.e YES_NO_OPTION and I was calling the CANCEL_OPTION that was a real blunder so, the else-if should be changed to:
else if (Answer == JOptionPane.NO_OPTION) {
this.setDefaultCloseOperation(myclassreference.DO_NOTHING_ON_CLOSE);
}
after this; its bingo !!! I've done!
Related
public static int clickOnExit() {
int dialogButton=JOptionPane.YES_NO_OPTION;
JOptionPane.showConfirmDialog(null, sharedConstants.exitMessage,"Confirm",dialogButton);
if(dialogButton == JOptionPane.YES_OPTION){return JFrame.EXIT_ON_CLOSE;}
else{return JFrame.DO_NOTHING_ON_CLOSE;}
}
for confirm(YES) it works, but i am not sure if cancel option is solved properly. i just want to cancel JOptionPane and keep frame opened.
You need to do three things:
Set your main application frame to do nothing on close.
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
Register a WindowListener that listens to the windowClosing event.
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
maybeExit(); // Will not return if user clicks yes.
super.windowClosing(e);
}
});
Write code to conditionally call System.exit if the user confirms they wish to exit the application.
private void maybeExit() {
int yesNo = JOptionPane.showConfirmDialog(this, "Are you sure you wish to exit?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (yesNo == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
Some suggestions were useful. I solved it in this way:
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
if (HandlingDialogBox.clickOnExit(frame) == 0) {
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
} else {
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
}
}
});
}
AND
public static int clickOnExit(final JFrame frame) {
return JOptionPane.showConfirmDialog(frame,sharedConstants.exitMessage,"Confirm",
JOptionPane.YES_NO_OPTION);
}
Sorry for bit messy parenthesis use, will clean that up later ...
I want to Stop accidentally closings in my project. I'm using JFrame Form as Home page. When I click Home window's close button I put Exit cord in Yes Option. I want to stop closing when I click No Option. Is there any way. Here is my cord. I'm using netbeans 7.3
private void formWindowClosing(java.awt.event.WindowEvent evt) {
int i= JOptionPane.showConfirmDialog(null, "Are you sure to exit?");
if (i == JOptionPane.YES_OPTION) {
System.exit(0);
} else{
new Home().setVisible(true);
}
}
How about
class MyGUI extends JFrame {
public MyGUI() {
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);// <- don't close window
// when [X] is pressed
final MyGUI gui = this;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int i = JOptionPane.showConfirmDialog(gui,
"Are you sure to exit?", "Closing dialog",
JOptionPane.YES_NO_OPTION);
if (i == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
setSize(200, 200);
setVisible(true);
}
//demo
public static void main(String[] args) {
new MyGUI();
}
}
You can simply do that like this
Integer opt = JOptionPane.showConfirmDialog(null, "This application cannot continue without login to the database\n Are you sure you need to exit...?", "Application X", JOptionPane.YES_NO_OPTION);
if(opt== JOptionPane.NO_OPTION){
this.setVisible(true);
}else{
System.exit(0);
}
I have a simple game in which I have a JOptionPane popup giving the choice of YES or NO.
So if the user hits NO then the game shuts down ofcourse however if the user hits YES I want the game to restart.
I have got this to work by the following : (Just by calling the main() method again.
main.Main.main(null);
The problem :
It's starting another instance of the game however the previous instead is there as well.
How can I close the previous instance before starting a new instance? or what other ways are there to get around this?
Here is the class code with the JOptionPane
public void popupWinMessage(String message)
{
//default icon, custom title
int n = JOptionPane.showConfirmDialog(
null,
message,
"",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
JOptionPane.showMessageDialog(null, "Alright, here we go again");
main.Main.main(null);
}
else {
JOptionPane.showMessageDialog(null, "Thanks for playing the battleships game");
System.exit(0);
}
Here is my updated main method (I'm still pretty confused on what is going on):
package main;
imports
public class Main {
public Controller theController = new Controller(new Game(), new Frame());
/**
* #param args
*/
public static void main(String[] args)
{
newGame();
}
public static void newGame()
{
theController.;
}
}
The directory of my whole game looks like this
http://i.imgur.com/7iKJQwu.png
The method where the JOption pane is located is in the view's Frame class.
public Controller(final Game newGame, final Frame newView)
{
this.game = newGame;
this.view = newView;
this.view.setVisible(true);
//Gets the board arrays into these local variables here for us to use
playerBoard = newGame.DisplayPlayerBoard();
computerBoard = newGame.DisplayCompBoard();
colourGrids();
this.view.addGridActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
Object o = ae.getSource();
if(o instanceof JButton)
{
JButton btn = (JButton) o;
int xValue = (Integer) btn.getClientProperty("row");
int yValue = (Integer) btn.getClientProperty("column");
int tempShipType = computerBoard[xValue][yValue];
newGame.tryHitComputer(xValue, yValue);
btn.setEnabled(false);
if(tempShipType != -1)
{
if(newGame.checkShipStatus(tempShipType) == true)
{
System.out.println(shipDowns[tempShipType]);
newView.popupMessage(shipDowns[tempShipType]);
}
}
//Code here for the computer to try hit your ships
newGame.tryHitPlayer();
colourGrids();
System.out.println(newGame.isGameWon());
if (newGame.isGameWon() == true)
{
System.out.println("Game has been won, do something to stop it at some point");
newView.popupWinMessage("Game has been won\nDo you wish to play again?");
}
if (newGame.isGameLost() == true)
{
System.out.println("Game has been lost, the silly AI has beaten you\nDo you wish to play again?");
newView.popupWinMessage("Game has been lost, the silly AI has beaten you\nDo you wish to play again?");
}
}
else
{
System.out.println("The listener was not attached to a JButton as expected - " + o.getClass());
}
}
});
}
Don't call the main method again. Have a start() method which starts your game and get the dialog to call that when the answer is "yes"
One option is to add a restartGame() method to your Controller class. Since you call popupWinMessage() from the Controller constructor, you can modify it to take a Controller object and pass it the this reference. Then popupWinMessage() method can simply call the restartGame() method on the instance that is passed to it.
I have a Java program. When I run the program, it will give me a GUI which as I attached.
When I want to close it, it will prompt out a confirm dialog. If I press the Yes button, it will quit the program using System.exit().
public static void main(String args[])
{
ButtonTest app = new ButtonTest( );
app.addWindowListener(
new WindowAdapter( )
{
public void windowClosing (WindowEvent e)
{
String message = " Really Quit ? ";
String title = "Quit";
int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
}
);
}
If I don't want to quit the program, what can I do? System.continued() ?
You Don't need the else in this case
Try setting this,
app.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE)
[Edited]
So, your code will become something like this,
public static void main(String args[]) {
ButtonTest app = new ButtonTest();
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int reply = JOptionPane.showConfirmDialog(null,
"Really Quit ?", "Quit", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
System.exit(0);
}
});
app.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
app.setSize(640, 480);
app.setVisible(true);
}
[Explanation]
You might be thinking that why it is like that. The behaviour of windows close button for JFrame, unlike Frame,is to hide the window. Therefore, it will hide/close the window anyway. But when you specify that it must also exit the program, when the user click yes. Then, besides closing the window, it also exits the program. And when user clicks no, it does nothing but closes the window anyway. Hence, you must tell it explicitly that DO_NOTHING_ON_CLOSE.
[Docs]
Unlike a Frame, a JFrame has some notion of how to respond when the
user attempts to close the window. The default behavior is to simply
hide the JFrame when the user closes the window. To change the default
behavior, you invoke the method setDefaultCloseOperation(int). To make
the JFrame behave the same as a Frame instance, use
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE).
Ref: JFrame docs
If you will ask me, I will go with, on YES SELECTION instead of abruptly closing my Application with System.exit(0), I will choose the gracious way of closing my Application, by using frameObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) and on NO SELECTION , I will go for frameObject.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE). Here is one sample program for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ApplicationCloseExample
{
private void displayGUI()
{
final JFrame frame = new JFrame("Application Close Example");
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
int result = JOptionPane.showConfirmDialog(
frame, "Do you want to Exit ?"
, "Exit Confirmation : ", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
else if (result == JOptionPane.NO_OPTION)
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
});
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ApplicationCloseExample().displayGUI();
}
});
}
}
If you want the program to continue when you press NO, place the rest of your code in else block or call the function where you have placed the rest of your code.
Removing else block is also an option if you don't want to place any action on the NO button because the JOptionPane.showConfirmDialog() will close anyways. You can continue with rest of your code after the if statement.
FYI- There is no System.continue(). The program pretty much does that on it's own.
You can add an else block. if you want to run the main method again (which I assume you do) it should look like this. You should have some method which you run if the user chooses no, whether it is the main method main(null) or another method.
public static void main(String args[])
{
ButtonTest app = new ButtonTest( );
app.addWindowListener(
new WindowAdapter( )
{
public void windowClosing (WindowEvent e)
{
String message = " Really Quit ? ";
String title = "Quit";
int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
System.exit(0);
}
else
{
//whatever you plan on running instead here, instead of quitting,
//main(null) to run the main method, or put another method if you want
}
}
}
);
}
I seem to have the reverse problem to most people. I have the following pretty standard code to see if the user wants to do some saves before closing the window:
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
boolean close = true;
// check some files, asking if the user wants to save
// YES and NO handle OK, but if the user hits Cancel on any file,
// I want to abort the close process
// So if any of them hit Cancel, I set "close" to false
if (close) {
frame.dispose();
System.exit(0);
}
}
});
No matter what I try, the window always closes when I come out of windowClosing. Changing WindowAdapter to WindowListener doesn't make any difference. What is weird is that the documentation explicitly says "If the program does not explicitly hide or dispose the window while processing this event, the window close operation will be cancelled," but it doesn't work that way for me. Is there some other way of handling the x on the frame? TIA
I've just tried this minimal test case:
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class Test {
public static void main(String[] args) {
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
//frame.dispose();
}
});
frame.setVisible(true);
}
}
If I keep the dispose call commented, and hit the close button, the window doesn't exit. Uncomment that and hit the close button, window closes.
I'd have to guess that something is wrong in your logic to set your "close" variable. Try double checking that.
This is the key, methinks: frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); Makes the difference in the test case I cooked up.
not sure where is your problem,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClosingFrame extends JFrame {
private JMenuBar MenuBar = new JMenuBar();
private JFrame frame = new JFrame();
private static final long serialVersionUID = 1L;
private JMenu File = new JMenu("File");
private JMenuItem Exit = new JMenuItem("Exit");
public ClosingFrame() {
File.add(Exit);
MenuBar.add(File);
Exit.addActionListener(new ExitListener());
WindowListener exitListener = new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION) {
System.exit(1);
}
}
};
frame.addWindowListener(exitListener);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setJMenuBar(MenuBar);
frame.setPreferredSize(new Dimension(400, 300));
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
private class ExitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION) {
System.exit(1);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ClosingFrame cf = new ClosingFrame();
}
});
}
}
For the handling of this thing do:
if the user selects yes then use setDefaultCloseOperation(DISPOSE_ON_CLOSE); within the curly braces of that if else
if a cancel is selected then use setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
Consider example:
int safe = JOptionPane.showConfirmDialog(null, "titleDetails!", "title!!", JOptionPane.YES_NO_CANCEL_OPTION);
if(safe == JOptionPane.YES_OPTION){
setDefaultCloseOperation(DISPOSE_ON_CLOSE);//yes
} else if (safe == JOptionPane.CANCEL_OPTION) {
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);//cancel
} else {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);//no
}
To solve the same problem I tried the very first answer of this article.
As separate application it works, but not in my case.
Maybe difference is in JFrame(in answer) and FrameView (my case).
public class MyApp extends SingleFrameApplication { // application class of my project
...
protected static MyView mainForm; // main form of application
...
}
public class MyView extends FrameView {
...
//Adding this listener solves the problem.
MyApp.getInstance().addExitListener(new ExitListener() {
#Override
public boolean canExit(EventObject event) {
boolean res = false;
int reply = JOptionPane.showConfirmDialog(null,
"Are You sure?", "", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
res = true;
}
return res;
}
#Override
public void willExit(EventObject event) {
}
});
...
}
Not sure where your problem is, but this works for me!
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
int res=JOptionPane.showConfirmDialog(null,
"Do you want to exit.?");
if(res==JOptionPane.YES_OPTION){
Cal.this.dispose();
}
}
});
setDefaultCloseOperation() method helps in the problem .https://chortle.ccsu.edu/java5/Notes/chap56/ch56_9.html
view this link