Burhan
Burhan

Reputation: 43

Adding a WindowListener to JFrame (Window Opened)

This is my view class. The main class actually launches the program. The below code was used in the view lass since it contains the GUI and event handlers (action listeners).

public class TheaterView extends JFrame implements WindowListener{
    public void windowOpened(WindowEvent e) {
            displayMessage("WindowListener method called: windowOpened.");
    }
}

This is what I'm doing but it gives the error message: TheaterView is not abstract and does not override abstract method windowDeactivated(WindowEvent) in WindowListener.

Anyway, I implement the methods and get this (I get others too, but this is the only one I need):

@Override
    public void windowOpened(WindowEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

However, it doesn't seem to work when I do anything like use the println command. I want it to do something once the program runs for the first time i.e. when the windows is opened.

I searched a lot but I couldn't figure it out yet. Any help would be appreciated :)

Code in main:

TheaterView theater = new TheaterView("Movie Theater");
theater.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theater.setLocation(200, 200);
theater.pack();
theater.setVisible(true);

Upvotes: 0

Views: 1918

Answers (2)

Florian Stendel
Florian Stendel

Reputation: 359

Write a class which extends WindowsAdapter and add it to your JFrame via addWindowsListener.

See https://docs.oracle.com/javase/7/docs/api/java/awt/event/WindowAdapter.html for more information.

When working with listeners in Swing/AWT it is allways worth try to search for an according adapter to the listener you want to use.

Upvotes: 0

kevin ternet
kevin ternet

Reputation: 4612

Did you overide all abstract methods from your listener ? something like that :

public void windowClosing(WindowEvent e) {
     aboutFrame.dispose();      
}

public void windowClosed(WindowEvent e) {
}

public void windowIconified(WindowEvent e) {
}

public void windowDeiconified(WindowEvent e) {
}

public void windowActivated(WindowEvent e) {
}

public void windowDeactivated(WindowEvent e) {
}

Upvotes: 2

Related Questions