Maxpm
Maxpm

Reputation: 25551

Why won't this listener detect window close events?

I'm trying to listen for events on a single Frame via WindowStateListener.

import java.awt.Frame;
import java.awt.Label;

import java.awt.event.WindowStateListener;
import java.awt.event.WindowEvent;

public class UserInterface implements WindowStateListener
{
    public static void main(final String[] arguments)
    {
        UserInterface userInterface = new UserInterface();
    }

    public UserInterface()
    {
        Frame frame = new Frame("Graphics Example");
        frame.addWindowStateListener(this);
        frame.add(new Label("Hello, world!");
        frame.pack();
        frame.setVisible(true);
    }

    public void windowStateChanged(WindowEvent event)
    {
        System.out.println(event.paramString();
    }
}

It's working fine for minimization events, but not close events. WINDOW_CLOSING is definitely a valid WindowEvent value, and it's definitely something that Frame can throw. So why isn't it being passed to windowStateChanged()?

Upvotes: 5

Views: 4546

Answers (2)

SilentBomb
SilentBomb

Reputation: 168

You can use this.

frame.addWindowListener(new java.awt.event.WindowAdapter()
{
public void windowClosing(WindowEvent winEv)

}}

this would definitely compiled.

class TestSnippet {
    public static void main(Sring[] args) {

        // START: copy/pasted snippet
        frame.addWindowListener(new java.awt.event.WindowAdapter()
        {
        public void windowClosing(WindowEvent winEv)

        }}
        // END: copy/pasted snippet
    }
}

(A passerby notes) Well, except for..

I:\proj\TestSnippet.java:7: ';' expected
        public void windowClosing(WindowEvent winEv)
                                                    ^
I:\proj\TestSnippet.java:9: ')' expected
        }}
         ^
2 errors

Tool completed with exit code 1

Upvotes: 5

Jeff Storey
Jeff Storey

Reputation: 57192

WindowStateListeners are not notified of the window closing events. They are only notified of changes to the window's state, such as iconified or de-iconified. If you want close events, implement WindowListener (or extend WindowAdapter). This tutorial explains it http://download.oracle.com/javase/tutorial/uiswing/events/windowlistener.html.

Upvotes: 6

Related Questions