Alex
Alex

Reputation: 44295

How to fire an event?

I have the following java code snippet:

public static void main(String[] args) {

    String filename = args[0];

    JFrame f = new JFrame("Load Image Sample");

    f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    f.add(new LoadImageApp(filename));
    f.pack();
    f.setVisible(true);
}

in which a WindowClosing event is defined. How can I fire/execute/initiate this event from within my code, leading to the exit of the code?

Additional question: What is this construction I see in the code:

new WindowAdapter(){...}

i.e. normal brackets followed by curly ones?

Upvotes: 0

Views: 647

Answers (3)

Mercurial
Mercurial

Reputation: 2165

Well, there is really no point in simulating the event. Why? Because when the event is fired, it means that something happened in your application, and that is the 'Java' way of telling you: "Hey something happened! Here's the event so you can handle it appropriately.". In your case, it could be the user pressing the X button, or the OS shutting down. What you really want to do here, is to shut down the application, not trigger the event. Consider this:

f.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e) {
            ThisClassName.this.shutDown();
        }
    });
//...
}

private void shutDown(){
    System.exit(0);
}

This way, you can call shutDown() from wherever you want.

About the parentheses, it's called the Anonymous class. It's a class like any other, it just doesn't have a name. Since JFrame requires a WindowListener as a parameter in it's addWindowListener function, you need to pass it. The thing is, you don't need the WindowAdapter anywhere else in your code, so there is no need to keep a named reference to it.

Upvotes: 0

camickr
camickr

Reputation: 324098

See Closing an Application for some general ideas on this topic.

The ExitAction shows one way to dispatch the event to the frame. The Action was meant to be used with a JMenuItem or JButton to enable the user to close the frame by other means than clicking on the "X".

Upvotes: 2

Vaibs_Cool
Vaibs_Cool

Reputation: 6156

Take a look at this links . Hope it helps

http://docs.oracle.com/javase/tutorial/uiswing/events/propertychangelistener.html

http://weblogs.java.net/blog/joshy/archive/2006/02/all_hail_the_pr.html

Also, in this specific case, you don't really need to trigger the event since all it does is call System.exit(0). The only reason you would want to trigger the event within the code by hand is to emulate someone clicking the "X" button to close the window (as opposed to closing the program through other means).

Upvotes: 2

Related Questions