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

Similar Messages

  • 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

  • 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

  • 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>

  • JFrame will not close giving null pointer exception

    Hello ev1, Heres what I'm doing, I have a menu with JButtons that when pressed will take you to a game (this works fine). When your done with the game, you press a button that closes the JFrame(game) and starts the menu again (this gives the error null pointer exception). Heres a brief summary of the design:
    FullScreenSetup class
    has openWindow() that sets up a new full screen JFrame. (works)
    has closeWindow() that removes everything in the contentPane and sets
    visible(false).
    GameMenu class
    uses FullScreenSetup via FullScreenSetup window;
    uses window.openWindow() to set up the window.
    also sets up the buttons and handles them when pressed
    VideoPoker class (the game)
    uses FullScreenSetup via FullScreenSetup window;
    runs the game and has the button that should close the window and go
    back to the menu.
    heres how i thought it should work, in the actionPerformed method I have
    window.closeWindow(); <- this gives me the error
    new GameMenu(); <- this is my ultimate goal (hopefully brings me
    back to the menu screen to choose another game)
    I hope what I have written is enough for someone to help me because I know what it is like to read through hundreds of lines of code to help someone. Thx.

    What I cannot understand is that when going from the menu to the game I use window.closeWindow(); so that I can clear the menu and paste the game on the screen this works fine. so why does it not work a second time?

  • 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

  • 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.

  • Invocation API: JFrame opens and closes immediatly when invoced.

    Hello,
    I'm sitting with an existing software, to which I would like to create a Java GUI to present calculation results in a nice way (simple editing, saving in different formats, etc.). The core is Fortran 77 and 90.
    Right now I'm trying to figure out how JNI works, and I have been able to make some C code show a Jframe. However, the JFrame disappears immediately if I don't make the runningThread.sleep() for some time, and I can't seem to find any GUI sample code. If I run it in NetBeans it stays open until I click the X.
    In the end I would like the GUI to be started from Fortran 90 when a user gives the plot command in the application console.
    In addition to the above problem, I would like a push in the right direction. What should I think about with this approach? Any common traps?
    This is how the test looks:
    Java code generated by NetBeans, where I just want to display a JFrame.
    public class JFrame extends javax.swing.JFrame {
        public JFrame() {
            initComponents();
        @SuppressWarnings("unchecked")
        private void initComponents() {
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            setTitle("JFrameInvoced");
            setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            pack();
        @SuppressWarnings("static-access")
        public static void main(String args[]) throws InterruptedException {
            JFrame frameTest = new JFrame();
            frameTest.setVisible(true);
            Thread runningNow = Thread.currentThread();
            runningNow.sleep(1000);
    }C code from internet.
    #include <stdio.h>
    #include <jni.h>
    JNIEnv* create_vm() {
         JavaVM* jvm;
         JNIEnv* env;
         JavaVMInitArgs args;
         JavaVMOption options[1];
         int ret;
         /* There is a new JNI_VERSION_1_4, but it doesn't add anything for the purposes of our example. */
         args.version = JNI_VERSION_1_4;
         args.nOptions = 1;
         options[0].optionString = "-Djava.class.path=D:\\Source\\Invocation_test";
         args.options = options;
         args.ignoreUnrecognized = JNI_FALSE;
         ret = JNI_CreateJavaVM(&jvm, (void **)&env, &args);
         return env;
    void invoke_class(JNIEnv* env) {
         jclass helloWorldClass;
         jmethodID mainMethod;
         jobjectArray applicationArgs;
         jstring applicationArg0;
         //helloWorldClass = (*env)->FindClass(env, "InvocationHelloWorld");
         helloWorldClass = (*env)->FindClass(env, "JFrame");
         mainMethod = (*env)->GetStaticMethodID(env, helloWorldClass, "main", "([Ljava/lang/String;)V");
         applicationArgs = (*env)->NewObjectArray(env, 1, (*env)->FindClass(env, "java/lang/String"), NULL);
         applicationArg0 = (*env)->NewStringUTF(env, "From-C-program");
         (*env)->SetObjectArrayElement(env, applicationArgs, 0, applicationArg0);
         (*env)->CallStaticVoidMethod(env, helloWorldClass, mainMethod, applicationArgs);
    int main(int argc, char **argv) {
         JNIEnv* env = create_vm();
         invoke_class( env );
    }

    sammen wrote:
    Can multithreading be a possible solution to this?Multithreading is certainly involved when you create a GUI using SWING, as SWING automatically creates a thread where all drawing and event handling is performed. Calculations and other longer tasks are performed outside that thread. This is done to avoid blocking the GUI during calculations.
    But first focus on the interface between the C program, where the calculations are performed, and the Java program, where the GUI should be located. Possible questions you should ask yourself are:
    - What data must be sent from the C part to the GUI?
    - What actions do I want to trigger from the C part, e.g. "create a plot"?
    - What actions do I want to trigger from the GUI to the C part, e.g. "redo calculations"?
    Then you could design the interface between those two. The multithreading performed by SWING has to be considered especially for the third question, as event handlers like "actionPerformed" are called from the SWING thread and should return quickly, just triggering the action, but not performing it. But those things are better discussed in the SWING forum.
    Martin

  • Closing a sub jframe closes my application

    Hi,
    A beginner question. I have multiple jframe forms in my application. From my main windows i call sub jframes. The problem is that when the user closes a sub jframe my application terminates. How can overcome this problem.
    Thanks in advace.

    Don't set the default close operation to "exit on close."

  • 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).

Maybe you are looking for

  • IPhoto and photo stream albums

    Please help me. I am trying to move pictures from my photo stream album into an existing event.

  • How to update XML source in ALDSP 3.0?

    1. ALDSP 2.5 provides a updateovrride class at server side for programmer to write custom update logic for Non-XA data source. how does ALDSP 3.0 do update with XML data source??? 2. I wrote a simple trigger service for ALDSP 2.5. It processes the da

  • GetImage() in JApplet

    Hi folks! Can anybody help me here - I'm trying to use the getImage() method of JApplet to load images into my Applet (the images required are dependent on info received from a JDBC / Network connection so I want to be selective about the images I lo

  • How do I 'close application elementsautoanalyser when installing PE 11?

    When I try to install Adobe Application Manager I get the message 'Please close the following applications to continue. ElementsAutoAnalyzer.exe' How do I do this, I can't find this file on my PC?

  • Griffin iMic and Edirol PCR-A30 conflict

    Garageband band gives me the following error and I must then force quit: Garageband detected a possible conflict between one or more third party midi or audio drivers Be sure to install the latest for all audio or midi equipment connected to your com