JFrame Closing problem in windowClosing event!

Hi,
I have a small question and need your help to solve this. I have a JFrame and I have overriden it's windowClosing method. Now Inside this method I pop a message and asks user if they really want to quit. If YES is clicked the Application exits and on any other click I just keep the JFrame showing. But whenever the user clicks NO or click the CLOSE BUTTON the Application doesn't exits but the JFrame hides and have no way to show it again. Here is code snippet:...
frame.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
int confirm = 0;
confirm = JOptionPane.showOptionDialog(null,"Close","Close",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null, null, null);
if(confirm == 0) //yes
System.out.println("**** CLOSING THE JFRAME");
System.exit(0);
else
//Here I still the JFrame is hidding itself as I want to stay it
//visible.
System.out.println(" DO NOT CLOSE THE JFRAME");
return;                              
How can I get arround this problem. I just want to exit the Application if the YES BUTTON is clicked else I want to keep the Application running and showing.
Thanks for any help

Use the windowClosing() method instead. When using it, if you don't call window.setVisible( false ), it won't get closed.myFrame.addWindowListener( new WindowAdapter() {
    public void windowClosing( WindowEvent we ) {
        int result = JOptionPane.showConfirmDialog( myFrame,
            "Are you sure you want to close the window?", "Close", JOptionPane.YES_NO_OPTION );
        if( result == JOptionPane.YES_OPTION ) {
            myFrame.setVisible( false );
});

Similar Messages

  • Stopping WindowClosing Event

    HI, I have a question about stopping WindowClosing Event from continuing to WindowClosed Event.
    I have a JFrame implementing WindowListener - and I'd like to stop frame from closing by intercepting WindowClosing Event (so it never reaches WindowClosed Event).
    Is there anyone who know how to do it?
    Thank you in advance.

    Once you set the default close operation as follows:
    setDefaultCloseOperation( DO_NOTHING_ON_CLOSE );
    You must explicitly close the window yourself. Something like:
    addWindowListener( new WindowAdapter()
         public void windowClosing(WindowEvent e)
              String message = "Do you want to close the window?";
              int result = JOptionPane.showConfirmDialog(parent, message, "Close Window", JOptionPane.YES_NO_OPTION);
              if (result == JOptionPane.YES_OPTION)
                   window.dispose();
    });

  • Calling a JDialog in the windowClosing Event of a JFrame

    hi
    As we had seen in many applications when u try to close the application a Dialog box will appear and it will ask whether we have to save it.I want to implement the same thing in my windowClosing Event of the Frame.I tried doing this by calling the Dialog i have created by using the show method in the window closing event of the Frame,but what happens is when i close the frame the Dialog box flickers and disappears.What should i do to avoid this flickering and Disppearing of the Dialog box.I want the Dialog box to stay on the screen.What should i do? any ideas?
    thanks

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class WindowClosingTest extends JFrame {
         public WindowClosingTest() {
              try {
                   setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                   JButton button = new JButton("Close");
                   button.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent ae) { performClose(); }
                   addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent we) { performClose(); }
                   getContentPane().add(button);
                   pack();
                   setLocationRelativeTo(null);
                   setVisible(true);
              } catch (Exception e) { e.printStackTrace(); }
         private void performClose() {
              int n = JOptionPane.showConfirmDialog(null, "Close?", "Confirm", JOptionPane.YES_NO_OPTION);
              if (n != 1) { System.exit(0); }
         public static void main(String[] args) { new WindowClosingTest(); }
    }

  • Problems with close event scripts and closing Photoshop

    Hi!
    We are having problems with close event scripts ("Cls ") when closing/quitting Photoshop.
    The close event scripts are working without problem when closing an image. But when quitting Photoshop without having closed all images we are observing the following behaviour:
    with CS2 the close event scripts are not triggered at all
    with CS4  the close event scripts are triggered and executed correctly. But after that the Photshop process freezes. No visible GUI, you have to kill the process with the task manager.
    I can reproduce this behaviour even with a small script consisting of a single alert('hello') and even an empty script. Is this an known bug or am I doing something wrong?
    Thanks for your help!
      Eric

    Check your energy saver settings under system preferences. That is where you set sleep setting.

  • JDialog dispose() not firing windowClosing()/windowClosed() event

    I have a small dialog that has 'OK' and 'CANCEL' buttons. When the user clicks on the 'X' in the top right hand corner to close the window, the windowClosing() event is fired on all listeners. However, calling dipose() when i click on the 'OK' or 'Cancel' buttons does not fire the event. I am sure this should work without a problem but i just cannot see what is going wrong.
    Andrew

    I'd have to test this, but there's some sort of logic to think that calling hide or dispose would not generate events. What would be the point? You know it's going to be closed, so you should tell anyone who needs to know. You can get the list of listeners and fire your own event if you wanted.
    Window.dispose() does fire a window closed event, though.
    If you want to simulate closing... This is from code I had written... some of it you can replace as appropriate (isJFrame(), etc).
          * Closes the window based on the window's default close operation. 
          * The reason for this method is, instead of just making the window
          * invisible or disposing it, to rely on either the default close
          * operation (for JFrames or JDialogs) or rely on the window's other
          * listeners to do whatever the application should do on the "window
          * closing" event. 
         private void doClose() {
              int closeOp = getDefaultCloseOperation();
              // send the window listeners a "window closing" event... 
              WindowEvent we = new WindowEvent(getWindow(), WindowEvent.WINDOW_CLOSING, null, 0, 0);
              WindowListener[] wl = getWindow().getWindowListeners();
              for(int i = 0; i < wl.length; i++) {
                   // this handler doesn't need to know...
                   if(wl[i] == this) {
                        continue;
                   wl.windowClosing(we);
              // if still visible, make it not (maybe)...
              if(getWindow().isVisible()) {
                   switch(closeOp) {
                        case WindowConstants.HIDE_ON_CLOSE:
                             getWindow().setVisible(false);
                             break;
                        case JFrame.EXIT_ON_CLOSE:
                        case WindowConstants.DISPOSE_ON_CLOSE:
                             getWindow().setVisible(false);
                             getWindow().dispose();
                             break;
                        case WindowConstants.DO_NOTHING_ON_CLOSE:
                        default:
         * Gets the default close operation of the frame or dialog.
         * @return the default close operation
         public int getDefaultCloseOperation() {
              if(isJFrame()) {
                   return ((JFrame)getWindow()).getDefaultCloseOperation();
              if(isJDialog()) {
                   return ((JDialog)getWindow()).getDefaultCloseOperation();
              // "do nothing" is, for all intents and purposes, the way AWT
              // Frame and Dialog work.
              return WindowConstants.DO_NOTHING_ON_CLOSE;

  • Problem with WindowClosing() method

    Hello everyone,
    I have some problem with WindowClosing() method, in which I gave options
    to quit or not. Quit is working fine but in case of Cancel, its not returning to
    the frame. Can anyone help me ....Here is my code
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class TestFrame extends JPanel
         public static void main(String[] args)
              JFrame frame = new JFrame("Frame3");
              WindowListener l = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        int button = JOptionPane.showConfirmDialog(null,"OK to Quit","",JOptionPane.YES_NO_OPTION, -1);
                        if(button == 0)     {
                             System.exit(0);
                                   else
                                              return;
              frame.addWindowListener(l);
              frame.setSize(1200,950);     
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    }

    Maybe try
    int button = JOptionPane.showConfirmDialog(yourframe,"OK to
    Quit","",JOptionPane.YES_NO_OPTION, -1);

  • Help !! needed with windowClosing() event

    Hi there I have a problem were I would like to shut down my application when it is iconified,
    THE SHORT STORY
    I would like my application to be deiconified when I close it by right click in its icon and select the close option.
    BACKGROUND
    the current situation is when it is iconified I can right click and then I get the menu where I can choose to restore or close, when I click close, a windowclosing event is fired but nothing happens the application is not shut shown, when I then right click again and restore the app I notice that my own built in logout menu is up so it seems to be recieving the event all I want is the appp to be deiconified when I clik close.
    As I am a distributed programmer this gui stuff is rocket science i would appreciate any help

    Something like the following, though I am not sure too.
         win.addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                   // Invoked when a window is in the process of being closed. The close operation can be overridden at this point.
                   Window win = e.getWindow();
                   boolean iconified = win.getState() == ICONIFIED;
                   if (iconified) {
                        e.consume();
                        win.setState(NORMAL);
                   } else {
                        super.windowClosing(e);

  • Help needed with JFrame closing

    Hi friends,
    I am new to java and java swings. I have made a JFrame in class "Mainclass" and i have written a method "declareActionEvents(frame)" which performs the action for JFrame closing.
    I have a method called " onExit()" in another class "secondaryclass".
    My question is when i click the x(Close button) of the JFrame(which is in Mainclass) then the "onExit()" method in "secondaryClass" should get called.
    sorry for the simple question as i am new to java and swings i am asking this. I am sending the code of both classes below.
    Thankyou
    import javax.swing.*;
    import java.awt.*;
    import java.io.File;
    public class MainClass {
        private static final int HEIGHT = 600;
        private static final int WIDTH = 1024;
         * Everything starts here.
        private void createAndShowGUI() throws Exception {
            //Create and set up the window.
            JFrame frame = new JFrame("Sample");
            declareActionEvents(frame);
            frame.setSize(new Dimension(WIDTH, HEIGHT));
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            frame.setLocation(screenSize.width / 2 - (WIDTH / 2),
            screenSize.height / 2 - (HEIGHT / 2));
            //Display the window.
            frame.setVisible(true);
        private void declareActionEvents(JFrame frame) {
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Instead of default close i want to save details(where save option is in another class) before closing this frame
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            } catch (Exception e) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        new MainClass().createAndShowGUI();
                    } catch (Exception e) {
                        e.printStackTrace();
    import javax.swing.*;
    import java.awt.*;
    import java.io.File;
    public class secondaryclass {
        private JFrame frame;
        public secondaryclass(JFrame frame) throws Exception {
            this.frame = frame;
        public void onExit() {
            if (JOptionPane.showConfirmDialog(frame, resourceBundle.getString("save.details.before.exit")) == JOptionPane.YES_OPTION)
                // ( a save detail method)
                saveDetail.onClickSaveData();
                System.exit(0);
    }

    Add a Window Listener and use the WindowClosing method to do whatever work needs done.
              this.addWindowListener(new java.awt.event.WindowAdapter() {  
                   public void windowClosing(java.awt.event.WindowEvent e) {   
                        exitApplication();
              });

  • How to trap WindowClose event?

    I would like to trap the WindowClose event such that when my closing condition is not satisfied, the window would not close.
    Right now everytime i click the X button at the upper right of the window, the window closes automatically. I would like to know how to trap that event so I can control the closing of the window.
    tnx!

    For that you have to implement java.awt.event.WindowListener and override the windowClosing or windowClosed method according to your requirement. Put your code inside that method. But before doing that you have to set the default close operation.
    setDefaultCloseOperation(0);
    Hope this would work.
    Anirban

  • I have no problems copying iMovie Events from one Mac to another, however, how can I copy iMovie Projects from one Mac to another?

    I have no problems copying iMovie Events from one Mac to another, however, how can I copy iMovie Projects from one Mac to another?  Any help will be appreciated.  Thank you.

    This should give you some good insight, I'd probably store them on an External HD on the old machine and then just drag and drop to the new machine.
    https://discussions.apple.com/docs/DOC-4141

  • ICal error "There was a problem receiving this event invitation"

    Whenever I try accepting an event invitation I get a dialog prompt that says
    *There was a problem receiving this event invitation*
    Someone invited you to an event using an email address that isnt on your "me" card in Address Book. Find your email address in the following list and add it to your card in Address Book
    Problem is I've done that, my vCard is up to date. It was working fine, I cant recieve any invites anymore, wether they come from OSX or Windows. Can anyone help?

    I ran into this same issue. To resolve this, go into the Address Book application. Select the vCard that is "your" card. Now in the menu bar, go to "Card". On the drop down menu, select "Make this my card". You should now be able to accept iCal invitations without any issues. When I upgraded to 10.5.1 the issue came back and this method seemed to resolve it.

  • How do I identify a problem in an event?

    Friends,
    I've updated to FCP X 10.1.  An event that I created after updating and for which I created a project suddenly displayed a yellow hazard symbol next to the name of the event.  This suggests that there is some sort of problem with the event or project.  How can I identify more specifically what the problem is?  Everything looks good when I look at the event and enclosed project.
    Thanks!
    Steve

    It means at least one peice of media is offline, and needs to be relinked.
    Select the Event, go to File > Relink Files, then swith from All to Missing Files.  You can then relink anything that is offline.

  • At event calendering site, getting message "There was a problem with your event submission. If you have disabled JavaScript please enable it and try your submission again." Javascript is ENABLED on my computer.

    I'm trying to submit an event to the events calendar at http://calendar.jtnews.net/events/index.php?com=submit. After I enter the Authentication words and press Enter, I get the message, "There was a problem with your event submission. If you have disabled JavaScript please enable it and try your submission again." According to my Firefox/Tools, etc., button, Javascript is enabled. I

    Hello mjswooosh,
    I'm very disheartened to hear that you've had ongoing problems when attempting to order from BestBuy.com. Our goal is ever to provide a fun and efficient shopping environment! Certainly creating aggravation serves neither you nor us and I apologize sincerely for this having been your experience.
    We recommend the troubleshooting steps you mentioned (i.e., clearing the browser cache, deleting temporary internet files and cookies) because this is the most common cause of this type of problem. I too have encountered this issue from time to time and these steps have almost always resolved the problem. I say almost always because there's one further step you can try: ensure that you have signed out of BestBuy.com, then perform the browser maintenance steps we've recommended. Afterward, before signing in to BestBuy.com, add your desired items to your cart and sign in as part of the checkout process. When the standard steps have not netted a resolution for me, this has solved the problem each time.
    I hope this helps. I'm very grateful that you took the time to write to us with your concerns and for sharing your very valuable feedback about your online experience.
    Sincerely,
    John|Social Media Specialist | Best Buy® Corporate
     Private Message

  • SCOM-Difference between Problem Count and Event Count in Application Failure Analysis Report

    Dear All, 
    Could someone explain me clearly , the difference between  Problem Count and
    Event Count in Application Failure Analysis  Report. Please help me in understanding What is meant be problem and event in the report .
    Thanks in Advance.
    Regards,
    Rajesh Kumar C

    Hello Rajesh,
    The "problem" is the logically grouped set of the exception events which have the identical hash calculated over several fields as "Stack", "Source", "Failed Function" and so on... So, even if exceptions are different
    in the other properties but hash matches over the considered properties - then all those exceptions go into the same "problem group".
    So, event is an instance of the problem. One event contributes to one problem but one problem might have a huge event count if you have a repeating issue.
    The logic is similar for the performance analysis report, only fields that go into the "problem" hash are different. e.g. "Stack" is not used in hash for perf events...
    Dmitry Matveev

  • Problem Posting an Event to the EventQueue

    Hi all,
    while i develop a java application i get problem posting ana event to the EventQueue using postEvent method.Here is the problem.i have a menu which have 3 menu items (Load, store, hide).i want when the user click "hide" the code in "store" option excuted plus extra code in option "hide".i tried to implement this using the postEvent of EventQueue. i simlate this by tring to post ActionEvent to simulate user cliks option "store" but this didn't work. can anyone tell me what's the problem.thanks

    try JMenuItem's doClick(). that simulates the user clicking on your menu item.
    thomas

Maybe you are looking for

  • Can i move my itunes library to another account on the same computer

    can i move my itunes library to another account on the same computer

  • Ok Guys Pleease Help With This H/d And Udma

    HI ALL for some reason my mobo or win xp decided to make my cd drives and h/d into pio mode instead of ultra dma after finding a fix for this which involves removing a couple of registry entries ,they both went to normal or so i thought. until i was

  • Yosemite download does not start

    I recently upgraded to Yosemite and want to reinstall it from scratch. So, I logged on App Store click on the "download" button, which is active and select the "continue" button for a full download, but then other than a cogwheel indicating some sort

  • Problem with TIMESTAMPDIFF

    I have this issue. I write this formula for a REPORT in a column and there aren't problems. CASE WHEN YEAR( "- Service Request Custom Attributes".DATE_6) =YEAR( "- Service Request Custom Attributes".DATE_7) AND WEEK_OF_YEAR( "- Service Request Custom

  • Labels in Detailed Navigation

    I'd like a detailed navigation with labels. I need something like sdn with some sections (Developer Areas, Formus, by example) which are opened. Can I do that with detailed navigation iview? How can I configure it? Thanks, Damian