Summary of Massaging, Event and Listener in Java GUI


I wrote the explanation of messaging, event and listener and put the example code at the bottom of the post. In each explanation, I also wrote an explanation for the example program.

Messaging

Messaging is that one GUI component communicates other GUI components. In addition, the mechanism of communication is said as messages.

Communicating is often expressed by the words, “send message”, and the word “message” is used to represent the data to be sent.

In Swing and AWT application

Events and listener compose messaging mechanism. They make the programming easier. We only have to consider the events and the listener. An event corresponds to a message, and a listener catches the event occurrence and performs as defined.

In the example

MouseEvent and MouseMotionListener collaborate and handle messaging.

Events

Events mean messages, data to be sent, in GUI programming. A message, the data to be sent, is referred to as an event in GUI programming.

In Swing and AWT application

Predefined events implement the interface, AWTEvent.

In the example

I used MouseEvent, which is an event class customized for an event by mouse.

Class hierarchy

Listeners

Listeners are receivers of events. They are also called an event handler, which handles the events. The role of the event handler is to define how to perform when the event happens and to connect components on GUI application and sometimes user inputs are triggers for the events.

Sometimes the word, “event handler”, indicates the method in the listener object, which performs when the event gets raised.

In Swing and AWT application

Predefined event listeners implement the interface, java.util.EventListener.

In the example

I used MouseMotionAdapter which implements MouseMotionListener. MouseMotionListener interface is a listener customized to listen to the mouse motion. MouseMotionListener extends EventListener. The program creates an object which extends MouseMotionAdapter. The function mouseMoved in the event listener object works when the mouse pointer moved on the JFrame window.

Class hierarchy

Example program

This program has only one listener, MouseMotionListener, which captures a MouseEvent.

Output

When I start the program and move the mouse cursor on the window, the program outputs the position of the mouse cursor. Here is a part of the output.