Overriding exit on close?

how can i overwrite the default exit on close operation of a JFrame to run a method of my choice?
what i am actually trying to do is, create a booking program, only i want it to load itself from file,
check the users username & password, then initalise the gui, up to this point i have it working.
but i cant work out how to have the system save itself whenever a user clicks on a close button.
i found this but i dont know if its any help as its a bit confusing to me
http://www.javaalmanac.com/egs/java.lang/ExitHook.html
the problem i was having when trying to do it like that example is that from inside run(),
i couldnt access any of my objects(out of scope) to write them,
and at any rate, i didnt even manage to get the run() method to execute when the exit button was clicked.
my write method works and requires the following arguments
public static boolean write(Rooms rooms,Facilitys facilitys,Facilitys discounts,String username,String password) {
     //do things
}if i add my write method to the main method, it will run and write the relevant objects to file,
but how do i get this to only do it when the close button is clicked?
here is my main method at the moment
     public static void main (String [] args) {
          //initialise all components
          System.out.println("reading from file" + filename);
          Vector fromFile = read();
          if (fromFile==null) {
               System.exit(1);
          try {
               Rooms rooms = (Rooms)fromFile.get(0);
               Facilitys facilitys = (Facilitys)fromFile.get(1);
               Facilitys discounts = (Facilitys)fromFile.get(2);
               username = (String)fromFile.get(3);
               password = (String)fromFile.get(4);
               System.out.println("username "+username);
               System.out.println("password "+password);
          catch (IndexOutOfBoundsException e) {
               System.out.println("there are not that many elements in the vector"+"\n"+"\n"+e);
               System.exit(1);
          //components initialised
          //log in
          System.out.println("Validating user");
          String inUser = JOptionPane.showInputDialog( null, "Enter the username" );
          String inPass = JOptionPane.showInputDialog( null, "Enter the password" );
          if (isRightUser(inPass,inUser ) ==false) {
          JOptionPane.showMessageDialog(null,"Sorry that username & password combination was not correct",
                    "System closing",JOptionPane.ERROR_MESSAGE);
               System.exit(1);
          //logged on
          //schedule a job for the event dispatching thread
          //creating and showing the GUI
          javax.swing.SwingUtilities.invokeLater (new Runnable() {
               public void run() {
                    createAndShowGUI();
     }

Thankyou 74philip, your suggestion was spot on. however when i had written the main part of the GUI it was several months ago as one of the first GUI's i ever did and frankly, it was messy copy+paste work. and still, there are gaps in my knowledge which without the keen eye of Torgil, i dont think i would have worked out that indeed i had to have a Jframe in there somewhere. i found the frame, added the listener, it all works great now thank you both for your help :D

Similar Messages

  • Can I make the quiz "EXIT" or close after posting results?

    I have been able to make the QUIZ post to my internal server, but after the "Name / Email" dialog box appears and posting is "successfully" done, the results screen remains visible (possibly allowing a second posting).
    Is there any way to make the QUIZ close once the posting has occured?
    Also, I noticed that if I choose not to display the score, the post results button does not appear. In order to hide the score, I change the fonts to match the background color. Perhaps there is a way around this too, as I am new to Captivate and don't know all the little tricks yet.

    Thanks for your suggestions. Since I am considering having students take the exam I will be working with the school to see how to integrate with the LMS server. I suspect the variables will be passed directly and all will work out well.
    When you said “the answers are sent at the point you submit each answer” I assume this is not the case with an internal server, which is why the results have to be posted by the user.
    To that end, I am testing the exam with my internal server, which does capture the test results properly. But, this requires the appearance of the results slide, which opens a small dialog requesting name and email (although the email can be anything). Once the results are “posted successfully” the original results slide returns. I cannot even add a button, nor edit the action of existing buttons to continue to another slide --- it’s as if the program is hard-wired to only behave with the default buttons on the results slide.
    I just wish there were a clean way of exiting the exam. The results slide only has an ENTER action, but no exit action choice in the properties. I am just unable to move to another slide beyond the results slide and I suspect that I am doing something wrong.
    I appreciate your advice, so thank you for taking the time to discuss this with me.

  • Exiting PP closes but, program still running, danger Will Robinson

    This was an issue on the demo version of Production Pro which expired and since then I've loaded Master Suite demo to continue until my hard copy of Production Pro arrives.
    The issue is that initially, I was unaware of the program not closing down in backgorund and after a few in and out episodes would get a hard boot safety shut down because resources were maxed and the CPU was getting to critical mass heat, shutting off abrubtly.
    I reported it to Adobe in the sky and just wondered of anyone else has had this happen? Or could point to what is causing the ghosting allocation to stay active?
    It went on for a couple of weeks and was not the best Mojo for the two SATA drives but we eventually isolated why the laptop was overheating.
    The new demo is doing the same thing so I hit control alt delete to close the background manually after exiting the program normally.
    The machine:W7P,  i7, 500 GB 5400 SATA, 2TB eSATA 7200, below the Mercury minimum 749 with an 500mbs GeForce, 380M.
    I hope the hard copy will overcome this but forwarned is forebearance.
    Some ultra bug no doubt that will be sorted out down the line.
    Thanks in advance for any noodeling,
    Rob

    When you're running the demo, you're running version 5.0.0--the initial release. There have been three feature-and-bug-fix releases since then. You'll be able to update to the last released version once you've registered the software. Though I can't say for certain, I suspect this issue would go away once you're running 5.0.3 (current version).
    Post back after you've installed that, if it doesn't correct the problem.

  • System.exit(0) closes wrong window

    I use a web browser to display an applet.
    In the applet I have the possibility to start a new webbrowser window with myapplet.getAppletContext().showDocument(url, "_blank");In the new webpage I also start a new applet.
    To close this new web page I call System.exit(0); from the applet in the new page.
    The strang thing that happens than is that the parent window is closed and the newly opened web page is still active.
    If I open these windows myself in the browser, I can close them from the applet.
    Can anybody help.

    System.exit is not permitted by an applet for the above mentioned reason.
    Multiple browser windows with applets share the same jvm so exiting the
    jvm makes the other applets crash.
    When you give the applet permission (sign or policy) system.exit will crash
    the browser.
    It is possible to close a popup window, since I don't beleve in the JSObject
    anymore (crashed too many times with too many bugs in mozilla).
    You can use another way, here it is.
    in your applet// to open the window
    this.getAppletContext().showDocument(
         new URL("javascript: myPopupWindow = window.open('yourPage.htm');myPopupWindow.focus()"));
    // to close the window
    this.getAppletContext().showDocument(
         new URL("javascript: myPopupWindow.close()"));in your html page:<script>
    var myPopupWindow = null;
    </script>

  • Exit on close - Overwriting the X

    Hello people,
    I've just started to incorporate Properties files into my program to save settings / profiles .. etc.. However, when a user clicks the X in the top corner, my program obviously exits.
    I would like to overwrite this action in order to save the settings, or bring up a warning to save .. or take some other actions. Thus my question is, where and what are the functions that I must write / overwrite to achieve this?
    I have a JPanel nested in a JFrame ... (love swing) would it be on one of those?

    Heres somthing interesting with DO_NOTHING_ON_CLOSE
    I've chosen an implementation similar to that of what Mattsabigman posted, and in actuality its working fine... (side note: I am using netBeans 4.1 IDE)
    However, I've noticed that ever since changing my default close operation, my mouse wont change its appearence in netBeans. In other words, before when I was using EXIT_ON_CLOSE. I would X out my program, mouse over my code in the IDE and the mouse cursor would change into a thin "T" like cursor...
    however now that I am using DO_NOTHING_ON_CLOSE (which eventually calls System.exit(0)) , my cursor will remain showing the arrow icon at all times when in the IDE .... regardless of what I mouse over...
    Is this suggestive of somthing not being handled correctly or the Virtual Machine not being totally shutdown .... or whatever... ?
    Like I've said before .. its not actually a problem but if anyone has any ideas about whats goin on ... i'd love to hear them.
    thanks
    ps. I do have a custom mouse listener and "right-click" popup windows for some swing elements in my GUI

  • Why wont the button on my trak pall set to close/exit programs close/exit Firefox 7.0.1?

    I have a Microsoft track ball the 5 customizable buttons.
    The the regular right and left buttons are the default right and left click.
    The outer left button is programed to do the "Enter" function.
    The wheel button is programmed to do the "Back" action.
    The outer right button is programed to "Close/Exit" programs. I have this one set up this was because I do not like tabbed browsing and it makes it easy to close multiple browser windows.
    I just installed 7.0.1, and now the ONLY program that will not close on my system when I press the outer right button is Firefox.
    Can you explain why this is happening?

    Firefox 8 will be released in a few days, that I believe includes fixes for the connections number on Windows, and a problem related to the bookmarks database.
    * meanwhile it may be worth trying the fix from this blog: http://blog.bonardo.net/2011/09/30/is-your-firefor-freezing-at-regular-intervals
    * a more speculative and unofficial suggestion is to adjust the preference ''browser.sessionstore.interval'' as suggested by ''[/questions/767246?page=2#answer-270794 frankal]'' based on http://www.techmynd.com/firefox-freezes-for-a-moment-after-every-10-sec-fix/ <br/>(In my opinion unlikely to do any harm, and easily reversible so worth a try)
    Another suggestion, not as a workaround, but as a means of demonstrating part of the cause is to use the error console to log CC & GC collections. The procedure for changing the preference is as above.
    [http://blog.mozilla.com/nnethercote/2011/10/26/memshrink-progress-week-19/ If you turn on javascript.options.mem.log in about:config you can see when GCs and CCs occur and how long they take, which is helpful for diagnosis.]
    No need to leave that on for long, just look for collections exceeding a second i.e. >1000ms if you see that you have a problem.

  • Badi or User Exit to close PR in ME59n

    Dear All,
    I have implemented a enhancement for ME59n(EXIT_SAPLME59_001). Here we club the PR which has same material, vendor, date..... And add the quantity to first PR quantity and create a single PO against all the PR.
    PR No              Material                vendor                     date                Quantity
    1                      ABC                   XYZ                     26.05.2011           100
    2                     ABC                    XYZ                     26.05.2011           200
    3                    ABC                     XYZ                     26.05.2011           300
    Assume the above example and here it will sum up the quantity i.e. 600 total and put against PR 1 and will remove the PR 2 and 3 from the internal table. Now PO will create for PR 1 with 600 as quantity and standard SAP will mark the PR 1 as closed.
    Now we have removed PR 2 and 3 from the internal table during run time after adding the Quantity. But I need to mark PR 2 and 3 as closed.
    Please let me know if there is any right Exit or Badi to achieve it or other way.
    Thanks in advance.
    Arun Kumaram.

    Here are the user exits you can look to http://www.sap-img.com/ab038.htm to and
    AMPL0001            Subscreen usu.p.dat.adicionales p.lista piezas fabr.autoriz.            
    LMEDR001            Ampliaciones programa de impresión                                      
    LMEKO001            Ampliar estructura comunicación KOMK para determinar precios            
    LMEKO002            Ampliar estructura comunicación KOMP para determinar precios            
    LMELA002            Transfer.núm.lote de aviso entrega al contabilizar una EM               
    LMELA010            Entrada aviso de entrega: toma de datos posición de IDOC                
    LMEQR001            Exit de usuario p.determinación fuente aprovision.                      
    LMEXF001            Condiciones en documentos de compra sin recepción d.factura             
    LWSUS001            Determinación fuente aprov.específica cliente en el comercio            
    M06B0001            Determinación de funciones p.liberación solicitud de pedido             
    M06B0002            Modific.estructura de comunicación p.liberación solic.pedido            
    M06B0003            rango de números y número de documento                                  
    M06B0004            rango de números y número de documento                                  
    M06B0005            Modif.estruct.comunicación p.liberación general solic.pedido            
    M06E0004            Modif.estructura comunicación p.liberación docs.compras                 
    M06E0005            Determinación funciones p.liberación doc.compras                        
    ME590001            Agrupación solicitudes de ped.p.partición de pedidos en ME59            
    MEETA001            Determinar clase de reparto (atrasos, nec.inmed., previsión)            
    MEFLD004            Determ.fe.entrega más temprana p.verif.seg.EM (sólo pedido)             
    MELAB001            Crear orden entrega p.suministro: Realiz.plan de transmisión            
    MEQUERY1            Ampliación para resumen de documentos ME21N/ME51N                       
    MEVME001            Cálculo ctd.prop.entr.mercanc.y tolerancia exc./faltas sum.             
    MM06E001            Exit de usuario para EDI: entrada/salida documentos ventas              
    MM06E003            rango de números y número de documento                                  
    MM06E004            Control pantallas datos import. en el pedido                            
    MM06E005            Campos cliente en documento compras                                     
    MM06E007            Doc.modif.p.solicitudes pedido durante conversión a pedido              
    MM06E008            Control del valor previsto p.pedidos p.orden de entrega                 
    MM06E009            Textos relevantes p.indicador "Existen textos"                          
    MM06E010            Selección de campos para la dirección del proveedor                     
    MM06E011            Activación bloqueo de solicitud pedido                                  
    MMAL0001            ALE distribución libro de pedidos: tratamiento salidas                  
    MMAL0002            ALE distribución libro de pedidos: tratamiento entradas                 
    MMAL0003            ALE distribución registro info compras: tratamiento salidas             
    MMAL0004            ALE distribución registro info compras: tratamiento entradas            
    MMDA0001            Propuesta de direcciones suministro                                     
    MMFAB001            Exit usuario para creación orden entrega                                
    MRFLB001            Controlar posiciones p.creación orden entrega

  • JFrame exit on close

    a) setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    b) addWindowListener(new WindowAdapter(){
         public void windowClosing(WindowEvent e)
    {System.exit(0);}
    which one is better ? or are they both exactly the same ?

    i prefere the WindowListener, because I can write my own code, when closing. Like: Bye-Messages, memory clean up, connection closing, ...
    woodi

  • Cp8 pc, action 'exit' (for close app), not work for iphone app

    i found bug,
    when you use the action 'exit' on pc( it work well).
    but on iphone, it not work

    action "cpCmdExit" , it not work for iphone.

  • IPhone 4: When playing a podcast and I exit it closes ipod.

    Question: When I'm listening to my iPod podcast and I go to my mail (for example) it closes or pauses my iPod podcast. Is it suppose to do that? I thought it was suppose to run just like Pandora in the background?!

    Do you play 'Video' podcast?
    If you are playing a video, it suspends as you close the ipod app.
    This happens even in music with video such as video clip.

  • I am unable to find "menu button New Fx Menu" when trying to (Click the menu button New Fx Menu and then click Exit Close 29)

    I have had sound problems when viewing facebook and youtube and thought it may be a plugin problem. I don't know much about computers and stumble my way through like now so simple instruction are required please.

    Hello,
    On the right side of your browser, below the window close button [X], should be three horizontal lines.
    * Menu [[Image: New Fx Menu]]
    * Exit [[Image: Close 29]] is on the bottom right corner of the menu that opens
    If you still cannot see it, '''try Firefox Safe Mode''' to see if the problem goes away. [[Troubleshoot Firefox issues using Safe Mode|Firefox Safe Mode]] is a troubleshooting mode that temporarily turns off hardware acceleration, resets some settings, and disables add-ons (extensions and themes).
    If Firefox is open, you can restart in Firefox Safe Mode from the Help menu:
    *Assuming you have your menu bar visible, go to "Help" > "Restart with Add-ons Disabled"
    If Firefox is not running, you can start Firefox in Safe Mode as follows:
    * On Windows: Hold the '''Shift''' key when you open the Firefox desktop or Start menu shortcut.
    When the Firefox Safe Mode window appears, select "Start in Safe Mode".<br>
    [[Image:Safe Mode Fx 15 - Win]]
    '''''If the issue is not present in Firefox Safe Mode''''', your problem is probably caused by an extension, theme, or hardware acceleration. Please follow the steps in the [[Troubleshoot extensions, themes and hardware acceleration issues to solve common Firefox problems]] article to find the cause.
    ''To exit Firefox Safe Mode, just close Firefox and wait a few seconds before opening Firefox for normal use again.''
    When you figure out what's causing your issues, please let us know. It might help others with the same problem.
    If that menu is still not visible, please provide us with a screenshot. If you need help to create a screenshot, please see [[How do I create a screenshot of my problem?]]
    Once you've done this, attach the saved screenshot file to your forum post by clicking the '''Browse...''' button below the ''Post your reply'' box. This will help us to visualize the problem.
    Thank you!

  • When trying to close an open page Ihave no "x"to close it and can't reverse back to a previous page either,I have to exit Firefox

    Pages won't close without exiting Firefox.

    close that exe using your task manager (win) or activity monitor (mac).

  • Itunes won't close or exit after prolong use.

    After leaving itunes open for a prolong period of time (a whole day or longer) I am unable to exit or close the program.
    The only way is to force exit in task manager. Any way to fix this?
    I've seen past post suggesting Nod32 or Eset software conflicts with itunes. I have tried  excluding the itunes folder and have the latest updated version from eset but problem still remains.
    side note: I also notice my podcast smart playlist stops live updating when I am unable to properly exit itunes. Not sure if this is a related issue or separate problem.
    Winxp sp3
    Itunes 10.4.1.10
    Eset Smart Security 5

    I found a temp work around to my problem.
    Whenever I had iTunes auto update my podcasts it evenetually choke up and not allow me to exit.
    I just have to manually click update podcasts once a day and exit/close before updating. Rather annoying.

  • How do I make an exit button to close my project on a CD?

    I am currently using Captivate 5 and have published my project to a CD to pass around my workplace, however the JavaScript attached to my EXIT button only works when I host my project on my Intranet.  Is there anyway that I can use code to make the exit button close my project regardless where it published?

    Question/Score slides are bit special. Maybe have a look at this blog post: Buttons on Question/Score Slides in Captivate 6? - Captivate blog

  • How do you override the WINDOWS key?

    I'm writing or rather rewriting a game. I would like to override the windows key to do some function in the game without invoking the windows menu. Is this possible, and if so how?
    Below is a sample bit of code I used to see what key codes, locations, and events were fired while pressing various keys. I made the key pressed/typed/released methods consume the events in an attempt to block the windows menu from coming up. I tried using a KeyEventDispatcher to catch all key events and consume them there, but it still displays the windows menu (on Windows 2000 at least).
    I have searched the forums and the all mighty Google to no avail. Please help me if you can. Thank you.
    import java.awt.Dimension;
    import java.awt.KeyEventDispatcher;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.FocusManager;
    import javax.swing.JFrame;
    public class Test extends JFrame implements KeyListener, KeyEventDispatcher
      public Test()
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addWindowListener(new WindowAdapter()
          @Override
          public void windowClosing(WindowEvent windowEvent)
            System.exit(0); //close all windows and exit
        FocusManager.getCurrentManager().addKeyEventDispatcher(this);
        this.addKeyListener(this);
        this.pack();
      public static void main(String[] arguments)
        Test frame;
        frame = new Test();
        frame.setTitle("Test Frame");
        frame.setPreferredSize(new Dimension(200,200));
        frame.invalidate();
        frame.pack();
        frame.setVisible(true);
      // this doesn't stop windows key from being processed whether true or false
      // if it is true the keyPressed, keyTyped, and keyReleased don't get called
      public boolean dispatchKeyEvent(KeyEvent keyEvent)
        System.out.println("dispatchKeyEvent " + keyEvent);
        return true;
      public void keyPressed(KeyEvent keyEvent)
        System.out.println("keyPressed " + keyEvent);
        keyEvent.consume();
      public void keyReleased(KeyEvent keyEvent)
        System.out.println("keyReleased " + keyEvent);
        keyEvent.consume();
      public void keyTyped(KeyEvent keyEvent)
        System.out.println("keyTyped " + keyEvent);
        keyEvent.consume();
    }

    Thanks for the reply. That is basically all I wanted to confirm. I wanted to allow the player to redefine the windows key to some game specific command. I can do this for all of the other keys I was able to test except for that one.
    If someone uses it on something other than windows they can redefine any key that maps to one of theirs. Since I don't have any alternate systems or keyboards to test on I won't bother making other keyboard configurations for the time being, if ever.

Maybe you are looking for