Event Handling

Detecting an event and carrying out the required task is known as handling the event. Programs following this paradigm are known as event-driven programs.

A program handling button events is demonstrated with the help of the following applet:

Java Runtime Environment is required to properly see the Applet. Please check the following link

Listing 2.1.1 shows the source code for the above program.

In the above applet, the Button is the GUI component. Once the GUI components are created, they need to respond to user actions. This is accomplished by adding various types of listeners to the GUI components. One (or more) listener objects added to the GUI components handle the events generated by the GUI component. The listener object can be the applet itself or any other object. For now, we will focus on the applet having the role of the listener and responding to the user actions. Depending on what type of component and the type of the listener, the corresponding methods written within the applet handle the user events. The table below shows some of the listeners for the corresponding GUI components.

GUI Component Listener Event Handling Method(s)
JButton ActionListener actionPerformed
JSlider ChangeListener stateChanged
JTextField ActionListener actionPerformed
JCheckBox ItemListener itemStateChanged
JRadioButton ActionListener actionPerformed
JMenuItem ActionListener actionPerformed
JComboBox ActionListener actionPerformed
ItemListener itemStateChanged
JApplet MouseListener mousePressed, mouseReleased, mouseClicked, etc.
MouseMotionListener mouseMoved, mouseDragged