Java Event Handling

The idea of event handling is most commonly seen when a user clicks on something in a graphical application or hits a key. Java Event handling is based around the concept of event Listeners. A listener is created and attached to a component. The two main methods of creating listeners are

  • interfaces
  • adapter classes

Using interfaces are sometimes known as "Programming by contract". When a class implements an interface it is contracting to implement the body in every method in the interface. So if you wanted to manage a window and used the WindowListener interface you would have to create a body for all 7 of the methods in that interface. If you were simply creating some test programs you might only want to actually process one of the events, that match the methods, and thus only need to create useful code for that methods. Despite only wanting to process one method, you would have to create an empty body for the other 6 methods. The adapter class helps get around this problem by supplying empty bodies for all the methods, and you then override the method that matches the action you want to process. If that explanation seems a little complicated, it is safe not to worry about it for the moment, and come back to it later.

Last modified: Sunday, 20 September 2015, 07:21 PM