Why won't this listener detect window close events?
Asked Answered
D

2

5

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()?

Distinctly answered 1/11, 2011 at 5:15 Comment(0)
G
6

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.

Grandpa answered 1/11, 2011 at 5:36 Comment(0)
M
5

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
Migrate answered 1/11, 2011 at 5:53 Comment(3)
this would definitely compiled.In this listener we can perform the task which we have to do when we are closing the window.Migrate
Ok now i understand that what were you trying to say.Ya thats write.Migrate
Feel free to edit out my additions. But please correct the snippet (or make it even more general) at the same time. +1 for the pointer to WindowListener.Eweneck

© 2022 - 2024 — McMap. All rights reserved.