Anonymous Inner class with Listeners Adapters

Anonymous Inner class with Listeners Adapters


Anonymous inner classes were introduced, at the first, to make event handling simpler and easier. With inner classes, forget the laborious days of implementing listeners and extending adapters classes. Now the code comes right at the place of linking the listener with the component in the constructor itself.

Two programs are given (using Anonymous Inner class with Listeners Adapters) one on window closing and one on button event handling using anonymous inner classes.

I. Anonymous inner class with Adapter

In the following program, frame is closed using anonymous inner class of WindowListener


Anonymous Inner class with Listeners Adapters
Output screen of Anonymous Inner class with Listeners Adapters

addWindowListener() is a method of class Window inherited by Frame. Here "new WindowAdapter()" is an anonymous class of WindowAdapter.

II. Anonymous inner class with Listener

In the following code, button event handling is done with anonymous inner class of ActionListener.


Anonymous Inner class with Listeners Adapters
Output screenshot on Anonymous Inner class with Listeners Adapters

addActionListener() is a method of class Button. Here "new ActionListener()" is an anonymous inner class of ActionListener. The event handling code comes in the constructor itself.

Leave a Reply

Your email address will not be published. Required fields are marked *