Results 1 to 17 of 17
  1. #1
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Smile Call a method on dispose() or EXIT of a JFrame

    Hey.

    Basically what I want to do is call a method when clicking on the close button in the JFrame (the default one in the top corner).

    I don't know if it's possible to override the DISPOSE_ON_CLOSE - or if it's the easiest to do.

    Anyway, I'll give you a few stumps of code:

    MainFrame:
    Java Code:
    package gui;
    import ...
    
    public class MainFrame extends JFrame {
    
    	private JButton btnAdmConf;
    
    	private Controller controller;
    
    	public MainFrame() {
    		...
    		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		...
    
    		controller = new Controller();
    
    		...
    
    		refreshButtons();
    
    		this.setVisible(true);
    	}
    
    	public void refreshButtons() {
    		...
    	}
    
    	public JFrame getFrame() {
    		return this;
    	}
    
    	private class Controller implements ActionListener
    	{
    		public void actionPerformed(ActionEvent e){
    			if (e.getSource() == btnAdmConf) {
    				new ConferenceFrame(getFrame());
    			}
    		}
    	}
    }
    And...

    ConferenceFrame:
    Java Code:
    package gui;
    import ...
    
    public class ConferenceFrame extends JFrame{
    
    	private MainFrame fromFrame;
    	private Controller controller;
    
    
    	public ConferenceFrame(JFrame fromFrame)
    	{
    		...
    		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    		...
    		this.fromFrame = (MainFrame)fromFrame;
    		...
    		controller = new Controller();
    		...
    		this.setVisible(true);
    	}
    	
    	public MainFrame getFromFrame() {
    		return fromFrame;
    	}
    
    	public JFrame getFrame() {
    		return this;
    	}
    
    	private class Controller implements ActionListener
    	{
    		public void actionPerformed(ActionEvent e){
    			...
    		}
    	}
    
    }
    Sorry if I wrote any incorrect brackets - ignore it if you can.
    So, on my my ConferenceFrame, I want to call getFromFrame.refreshButtons() when I dispose the frame.

    Any suggestions?
    Last edited by Muskar; 11-20-2010 at 06:53 PM. Reason: edited Title due to additional question

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,534
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Muskar View Post
    So, on my my ConferenceFrame, I want to call getFromFrame.refreshButtons() when I dispose the frame.

    Any suggestions?
    Yup, override the dispose() method in your class (make it call the superclass dispose() method when it has done its job), i.e. in your class:

    Java Code:
    public void dispose() {
       // do your work here
       super.dispose();
    }
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Nice! It worked right away. Thanks a lot, Jos :)

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,244
    Rep Power
    19

    Default

    Yup, override the dispose() method in your class
    Sorry, Jos, but I consider this a wrong approach.

    I would go with a WindowListener#windowClosing.
    How to Write Window Listeners (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)

    db

  5. #5
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Darryl.Burke View Post
    Sorry, Jos, but I consider this a wrong approach.

    I would go with a WindowListener#windowClosing.
    How to Write Window Listeners (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)

    db
    As far as I understand - there's no actual difference.
    Except, logically, I would guess that adding another listener requires a tiny bit more memory than just overriding a method.

    Could you perhaps enlighten your reasons for your opinion?

  6. #6
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,534
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Darryl.Burke View Post
    Sorry, Jos, but I consider this a wrong approach. I would go with a WindowListener#windowClosing.
    Yep, that's the gentle way to do it; come to think of it: if one of those listeners later in the chain bails out (e.g. by throwing an Exception) the window won't be closed or disposed while our own listener assumed it would ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  7. #7
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    Yep, that's the gentle way to do it; come to think of it: if one of those listeners later in the chain bails out (e.g. by throwing an Exception) the window won't be closed or disposed while our own listener assumed it would ...

    kind regards,

    Jos
    So, basically, you're saying that a custom WindowListener, like the one Darryl suggested, would do the check just before calling the actual methods that closes the window - and therefore not checking whether it's actually closing or not?
    I'm just checking if I understood it right (so a simple 'Yes' wouldn't be inappropriate).

  8. #8
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,534
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Muskar View Post
    So, basically, you're saying that a custom WindowListener, like the one Darryl suggested, would do the check just before calling the actual methods that closes the window - and therefore not checking whether it's actually closing or not?
    I'm just checking if I understood it right (so a simple 'Yes' wouldn't be inappropriate).
    Yep, you understood right. One of those listeners (called later than yours) could bail out so the window won't be disposed.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,244
    Rep Power
    19

    Default

    One of those listeners (called later than yours) could bail out so the window won't be disposed.
    Not if the defaultCloseOperation is DISPOSE_ON_CLOSE (or even EXIT_ON_CLOSE). It's possible only if the window is set to DO_NOTHING_ON_CLOSE, and windowClosing(...) doesn't call dispose(). Any other listener in the chain cannot veto a dispose() invoked from windowClosing(...).

    a custom WindowListener, like the one Darryl suggested, would do the check just before calling the actual methods that closes the window
    If the window is set to DISPOSE_ON_CLOSE, there is no other 'actual method that closes the window' and if it's DO_NOTHING_ON_CLOSE you have to invoke dispose() or if more appropriate, setVisible(false) from windowClosing(...).

    db

  10. #10
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Darryl.Burke View Post
    If the window is set to DISPOSE_ON_CLOSE, there is no other 'actual method that closes the window' and if it's DO_NOTHING_ON_CLOSE you have to invoke dispose()
    I guess I'm sorry for my lack of knowledge of how exactly dispose() works.
    With "actual methods", I was basically thinking of the methods that the dispose() method calls, within the method itself - I'd guess something that cleans up the frame for components or whatever, you get the point.
    And that's why Jos' reply made sense to me.

    Anyway, are you saying that windowClosing() dictates above all else in some way?
    I'm sorry, I didn't quite get your clarification, if that was what it was.

    EDIT:
    I now have an additional question:
    How do I do the same thing - but before "exiting" instead?
    It seems that there's no method on the JFrame called .exit(), so I assume that I have to somehow reach the whatever-keeps-the-program-running or what?

    I already tried the following:
    Java Code:
    	public void dispose() {
    		System.out.println("I printed before closing!");
    		super.dispose();
    	}
    and it wasn't called when I clicked on close (the frame is set to EXIT_ON_CLOSE)
    Last edited by Muskar; 11-20-2010 at 06:47 PM. Reason: Another question

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,244
    Rep Power
    19

    Default

    Read the API for dispose() fo rbetter understanding.
    Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable.
    When your frame is set to EXIT_ON_CLOSE there isn't any point in releasing resources, as the JVM is about to exit anyways. So don't expect dispose() to be invoked. And as I've been saying, overriding dispose() is NOT the correct approach to this requirement.
    Java Code:
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    
    public class FrameClosingListenerDemo {
    
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
    
          @Override
          public void run() {
            new FrameClosingListenerDemo().makeUI();
          }
        });
      }
    
      public void makeUI() {
        JFrame frame = new JFrame();
        frame.addWindowListener(new WindowAdapter() {
    
          @Override
          public void windowClosing(WindowEvent e) {
            System.out.println("Frame is closing");
          }
        });
    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    }
    db

  12. #12
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Darryl.Burke View Post
    When your frame is set to EXIT_ON_CLOSE there isn't any point in releasing resources, as the JVM is about to exit anyways. So don't expect dispose() to be invoked.
    So if I want to save data to a file, before Exiting, or open a dialog whether you want changes saved or not, I have no other option than using a windowListener() on all JFrames set to EXIT_ON_CLOSE, I presume?

    Quote Originally Posted by Darryl.Burke View Post
    And as I've been saying, overriding dispose() is NOT the correct approach to this requirement.
    I get how to make a windowListener - it's not that - but I still cannot see what makes overriding dispose() so terrible.
    And with all due respect, you're only the 50% of the experts with that opinion, in this thread (and not to mention: I don't know random people's credibility of their respective opinion, unless they present proof).
    And unless that changes dramatically - or you (or someone else) convince(s) me otherwise - I'm going to stick with my first solution, since it seemed convincing.
    Last edited by Muskar; 11-20-2010 at 10:50 PM.

  13. #13
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,244
    Rep Power
    19

    Default

    I have no other option than using a windowListener() on all JFrames set to EXIT_ON_CLOSE
    I don't see why any correctly designed application should have multiple JFrames set to EXIT_ON_CLOSE. But. If what you're looking for is a way to execute certain code on exit of your application, no matter how that exit is triggered -- which is not what you've been asking all along -- the correct way to do that is with a shutdown hook. Read the API for java.lang.Runtime#addShutdownHook(Thread).

    I still cannot see what makes overriding dispose() so terrible.
    You've already discovered for yourself that dispose() isn't necessarily invoked when closing/hiding a window. But sure, wait for Jos to come back to this thread and comment on that. No probs.

    db

  14. #14
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,534
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Darryl.Burke View Post
    But sure, wait for Jos to come back to this thread and comment on that. No probs.
    No further comments your honour; my suggestion was just a quick hack that only works if the dispose() method is called. My only artificial argument was that if (and only if) another WindowListener in the chain would bail out in an ugly way (by throwing an Exception) no dispose() and no further WindowListener(s) would be called at all ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  15. #15
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Darryl.Burke View Post
    If what you're looking for is a way to execute certain code on exit of your application, no matter how that exit is triggered -- which is not what you've been asking all along -- the correct way to do that is with a shutdown hook. Read the API for java.lang.Runtime#addShutdownHook(Thread).
    It was merely a question out of curiosity (I have no intention on using several EXIT_ON_CLOSE JFrames) - and I must say, you provided exactly what I needed, thanks :)

    Quote Originally Posted by JosAH View Post
    My only artificial argument was that if (and only if) another WindowListener in the chain would bail out in an ugly way (by throwing an Exception) no dispose() and no further WindowListener(s) would be called at all ...
    And that would truly be exceptional, as far as I understand, so even though the difference is very small (and thanks to you both for providing both solutions), it seems like the optimal way to go.

  16. #16
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,534
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Muskar View Post
    And that would truly be exceptional, as far as I understand, so even though the difference is very small (and thanks to you both for providing both solutions), it seems like the optimal way to go.
    In general, when it comes to Swing, better listen to Darryl's advice (or Camick's advice, but I don't see him around anymore); I'm most certainly no Swing expert and for one reason or another I always lose track in it's documentation ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  17. #17
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    In general, when it comes to Swing, better listen to Darryl's advice (or Camick's advice, but I don't see him around anymore); I'm most certainly no Swing expert and for one reason or another I always lose track in it's documentation ;-)

    kind regards,

    Jos
    Alright - but if you don't mind, I'll stick to your solution as long as no weird problems are occurring when disposing a window - but I'll keep it noted that I could change it to Darryl's extraordinarily advised way, if they should occur some day.

Similar Threads

  1. call a JSP method
    By sauravsinha in forum JavaServer Pages (JSP) and JSTL
    Replies: 4
    Last Post: 09-26-2011, 04:19 PM
  2. dispose() method not working
    By R&R in forum New To Java
    Replies: 19
    Last Post: 11-15-2010, 01:46 AM
  3. Inner class method call
    By d915172 in forum New To Java
    Replies: 3
    Last Post: 11-11-2010, 09:40 PM
  4. how to call method?
    By leapinlizard in forum New To Java
    Replies: 9
    Last Post: 04-29-2009, 11:55 PM
  5. cannot call private method from static method
    By jon80 in forum New To Java
    Replies: 3
    Last Post: 05-07-2008, 08:37 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •