Skip to main content
Engineering LibreTexts

13.4: The Java Event Model

  • Page ID
    15143
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    As we saw in Chapter 4, whatever happens while the computer is running is classified as an event. Every keystroke and mouse click, every time a disk is inserted into a disk drive, an event is generated. The handling of events are an important element of GUI programming. Therefore, before we begin discussing how to design GUIs, it will be useful to review the main concepts of Java’s event model.

    When a Java program is running, events generated by the hardware are passed up through the operating system (and through the browser, for applets) to the program. Those events that belong to the program must be handled by the program (refer to Fig. 4.18 in Chapter 4). For example, if you click your browser’s menu bar, that event will be handled by the browser itself. If you click a button contained in the Java program, that event should be handled by the program.

    In Java, whenever something happens within a GUI component, an event object is generated and passed to the event listener that has been registered to handle that component’s events. You’ve seen numerous examples of this process in earlier chapters, but we’ve included a simple example to serve as a reminder.

    Suppose you create a JButton in a GUI as follows:

    private JButton clickme = new JButton("ClickMe");

    Whenever the user clicks the JButton, an ActionEvent is generated. In order to handle these events, the GUI must register the JButton with a listener object that listens for action events. This can be done in an applet’s init() method or in an application’s constructor method, as in this example:

    public MyGUI() {
      // Add clickme to the GUI and assign it a listener
      add(clickme);  
      clickme.addActionListener(this); 
    }

    In this case, we have designated the GUI itself (this) as an ActionListener for clickme (Fig. 13.5). A listener is any object that implements a listener interface, which is one of the interfaces derived from java.util.EventListener. An ActionListener is an object that listens for and receives ActionEvents.

    In order to complete the event-handling code, the GUI must implement the ActionListener interface. As Figure [fig-clickme] shows, implementing an interface is a matter of declaring the interface in the class heading and implementing the methods contained in the interface, in this case the actionPerformed() method.

    import javax.swing.*;
    import java.awt.event.*;
    
    public class MyGUI extends JFrame 
                                  implements ActionListener {
        private JButton clickme = new JButton("ClickMe");
    
        public MyGUI() {
         // Add clickme to the GUI and assign it a listener
            getContentPane().add(clickme);   
            clickme.addActionListener(this);
            setSize(200,200);
            setVisible(true);
        } // init()
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == clickme) {
            clickme.setText(clickme.getText()+"*");
            }
        } // actionPerformed()
        public static void main(String args[]) {
            MyGUI gui = new MyGUI();
        }
    } // MyGUI

    Now that we have implemented the code in Figure [fig-clickme], whenever the user clicks clickme, that action is encapsulated within an ActionEvent object and passed to the actionPerformed() method. This method contains Java code that will handle the user’s action in an appropriate way. For this example, it modifies the button’s label by appending an asterisk to it each time it is clicked. Figure [fig-p479f1] depicts the sequence of actions and events that occur when the the user clicks a button.

    The methods used to handle the ActionEvent are derived from the class, the root class for all events (Fig. 13.8). Our example (Fig. [fig-clickme]) uses the getSource() method to get a reference to the object that generated the event. To see what information is contained in an event object, we can use the toString() method to print a string representation of the event that was generated. Here’s what it displays:

    java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=ClickMe]
      on javax.swing.JButton[,58,5,83x27,
      layout=javax.swing.OverlayLayout]

    As you can see, the event generated was an ACTION_PERFORMED event, in response to the ClickMe command. The source of the event was the JButton.

    Event Classes

    Although the event model is the same for both AWT and Swing classes, the Swing package introduces many additional events. Table 13.1 lists the events that are generated by both AWT and Swing components. You already have worked with some of these. We have written GUIs that handled ActionEvents for JButtons and JTextFields in preceding chapters.

    lll
    Components&Events&Description

    Button, JButton & ActionEvent & User clicked button & ItemEvent & User toggled a checkbox & ItemEvent & User toggled a checkbox & ItemEvent & User selected a choice & ComponentEvent & Component was moved or resized & FocusEvent & Component acquired or lost focus & KeyEvent & User typed a key & MouseEvent & User manipulated the mouse & ContainerEvent & Component added/removed from container & ActionEvent & User double-clicked a list item & ItemEvent & User clicked a list item & ActionEvent & User selected menu item & AdjustmentEvent& User moved scrollbar & TextEvent & User edited text & ActionEvent & User typed Enter key & WindowEvent & User manipulated window

    In viewing Table 13.1, it’s important to remember that the classes listed there are arranged in a hierarchy. This will affect the events that a particular object can generate. For example, a JButton is a JComponent (Fig. [fig-swing2-guis]), so in addition to generating ActionEvents when the user clicks on it, it can also generate MouseEvents when the user moves the mouse over it. Similarly, because a JTextField is also a JComponent, it can generate KeyEvents as well as ActionEvents.

    Note that the more generic events, such as those that involve moving, focusing, or resizing a component, are associated with the more generic components. For example, the JComponent class contains methods that are used to manage ComponentEvents. Because they are subclasses of JComponent, JButtons and JTextFields can also use these methods. Defining the more generic methods in the JComponent superclass is another example of the effective use of inheritance.

    Table 13.2 lists events that are new with the Swing classes. Some of the events apply to new components. For example, JTable and JTree do not have AWT counterparts. Other events provide Swing components with capabilities that are not available in their AWT counterparts. For example, a CaretEvent allows the programmer to have control over mouse clicks that occur within a text component.

    lll
    Component&Events&Description

    JPopupMenu&PopupMenuEvent&User selected a choice&AncestorEvent&An event occurred in an ancestor&ListSelectionEvent&User double-clicked a list item &ListDataEvent&List’s contents were changed&MenuEvent&User selected menu item&CaretEvent&Mouse clicked in text &UndoableEditEvent&An undoable edit has occurred&TableModelEvent&Items added/removed from table &TableColumnModelEvent&A table column was moved&TreeModelEvent&Items added/removed from tree &TreeSelectionEvent&User selected a tree node &TreeExpansionEvent&User expanded or collapsed a tree node&WindowEvent&User manipulated window

    Tables 13.1 and 13.2 provide only a brief summary of these classes and Swing components. For further details you should consult the JDK online documentation at

    http://java.sun.com/j2se/1.5.0/docs/api/

    Is it possible to register a component with more than one listener?

    Is it possible for a component to have two different kinds of listeners?


    This page titled 13.4: The Java Event Model is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Ralph Morelli & Ralph Wade via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.