Adapter classes – Java Basics #37

Not all action listeners are so easy to handle (according to last two posts). Clicking a button is easy to handle but you should check other things in your program. For instance, we should check if user closes a frame to prevent losing data. You can see this in action in almost all text editors. When user closes the window, JFrame object emits a special event, called WindowsEvent. Adapter classes will help us handle that.


In order to make this work we need to add object which implements WindowsListener interface to our frame:

That was easy.

listener object needs to implement WindowListener interface, which looks like that:

That means that we have to write at least seven methods in listener object’s class because WindowsListener is an interface. Obviously, we rarely will need all of them. For example, if we need to use windowsClosed and windowsIconified methods, then we probably would write down all seven methods, but only those two would do anything. Of course, it’s not very efficient way to create your applications. The code gets messy and ugly which is bad. Adapter classes may help us with it.

Adapter classes in use

Let’s build up a simple class that extends WindowsAdapter and write a windowsClosing method there:

Now you can add AdapterClass to the frame:

The windowClosing¬†method has been “obscured“. Now, you don’t have to write all seven methods. Although, keep in mind that if you misspend the method name, this whole thing won’t work. For example, if you write windowOppened instead of windowOpened¬†the method won’t work and, unfortunately, compiler won’t tell you that.


If you can create object and apply it to frame, then why not just create object in frame. Java’s OOP allows that:

As well as anonymous nested class: