Concepts / Handling Mouse Events in GUI Programming

Handling Mouse Events in GUI Programming

A GUI program has no main() routine that runs step by step from beginning to end. It must respond to events that happen at unpredictable times and in an order the program does not control.

  • Programming

A Program That Waits for the User

Most programs you have written so far run from top to bottom. The program starts at the first instruction, carries out each step in order, and stops after the last one. A GUI program, with its windows, buttons, and pointer, does not work this way. Its behavior depends on what the user does with the mouse and keyboard, and those actions happen at unpredictable times. This article explains how a GUI program is organized around events, what an event object contains, and how the event loop passes each event to the part of the program that handles it.

What do you think happens?

A short program receives three events in this order: a mouse click, a key press of the letter a, and a mouse move. It then prints a final line saying Program finished. Which line do you expect to appear last in the output, and why?

Reveal answer
Answer:

The last line is Program finished. It is the only line not tied to an event, and it appears after the last event has been handled.

Each of the first three output lines is printed by a handler that the loop called for one event. The final line is printed only after the program has finished handling the events, so it comes after the three event lines.

Why There Is No Fixed Main Routine

A GUI program does not have a main() routine that outlines what will happen when the program is run, step by step from beginning to end. Instead, the program must be prepared to respond to various kinds of events. These events can happen at unpredictable times, and they can happen in an order that the program does not control. The user can press any key, move the mouse, or press a button on the mouse, and the user can do any of these things at any time. The computer has to respond appropriately each time. This is why the program is written as a set of responses to events rather than as one fixed sequence of instructions.

FeatureStep-by-step program with main()GUI program
Order of actionsFixed by the programmer, from first line to lastDecided by the user, at unpredictable times
Where control startsAt the beginning of main()Waiting for an event to occur
What drives the programThe sequence of instructionsThe events that the user generates
How the program ends a stepReaches the next instructionFinishes handling one event and returns to waiting

Contrasting a fixed top-to-bottom program with an event-driven GUI program

Events as Objects Carrying Information

Definition

In Java, an event is represented as an object. When an event occurs, the system collects all the information relevant to that event and constructs an object to contain it. The object describes what the user did. Once the event object has been constructed, it can be passed as a parameter to a designated method. By writing that method, the programmer says what should happen when the event occurs.

MouseEventbuilt when the button ispressedsourcethe component clicked on(x, y) coordinatesthe point in the componentwhere the click occurredtimethe exact time of the clickmouse buttonwhich button was pressedcontainscontainscontainscontains
What pieces of information does a mouse event object contain, and how does the handler read them from it?

Mouse and Key Event Objects

The most basic kinds of events are generated by the mouse and keyboard. When the user presses one of the buttons on a mouse, an object belonging to a class called MouseEvent is constructed. When the user presses a key on the keyboard, a KeyEvent is created instead. MouseEvent and KeyEvent are both event classes in Java. The kind of event tells the program what type of user action it is dealing with, and the object that was built holds the details of that particular action.

Key point

A MouseEvent records four things: the source component, the (x, y) coordinates of the click, the exact time, and which mouse button was pressed. A KeyEvent is created for key presses. Both are objects that describe one user action.

The Event Loop Cycle

There is a lot of processing between the moment a user presses a key or moves the mouse and the moment a subroutine in your program is called to respond. As a Java programmer you do not need to know much about that processing, but you should understand the core pattern. Even though you did not write it, a routine is running somewhere that executes a loop of this form: while the program is still running, wait for the next event to occur, then call a subroutine to handle the event. This loop is called an event loop. Every GUI program has an event loop. In Java you do not have to write the loop, because it is part of the system. If you write a GUI program in some other language, you might have to provide a main routine that runs the event loop yourself.

Still running?the loop checks firstProgram endsthe cycle stopsWait for next eventthe program is idle until auser actionCall handlersubroutinepasses the event objectHandler finishescontrol returns to thecheckyesevent occursruns handlerrepeatno
After one event is handled, where does control go, and how does the program return to waiting for the next event?

Follow the cycle in the order shown. The program checks whether it is still running, waits for the next event, and calls a subroutine to handle that event. After the handler finishes, control returns to the check, so the cycle repeats until the program stops. Notice that the loop does not decide what the event means. The loop only waits and passes the event along. The meaning comes from the handler that the programmer wrote.

From Click to Handler Call

Put the pieces together for a single mouse click. The user presses a mouse button. The system collects the source, the coordinates, the time, and the button, and constructs a MouseEvent object containing them. The event loop, which was waiting, receives that event and calls the subroutine written to handle it. The event object is passed to that subroutine as a parameter, so the handler can read the details it needs.

Userpresses a mouse buttonSystembuilds the event objectEvent loopwaiting for eventsHandler subroutinewritten by the programmer1. clicks the mouse2. MouseEvent object delivered3. calls handler with the event
What happens in order, and who passes what to whom, from the moment the user clicks the mouse until the handler method runs?

Tracing the Verified Output

The traced program receives three events in turn: a mouse click at (10, 20), a key press of the letter a, and a mouse move to (5, 5). The verified output of the traced program is exactly four lines, in this order: Handling: mouse click at (10, 20), then Handling: key press 'a', then Handling: mouse move to (5, 5), then Program finished. You can check this output line by line to see which event produced each result.

Worked example

Locating each output line

Given the three events and the four verified output lines, identify which event or part of the program produced each line.

  1. 1
    Line 1: Handling: mouse click at (10, 20)

    This line is printed by a handler the loop called for the mouse click event. The coordinates (10, 20) come from the event object's (x, y) information.

  2. 2
    Line 2: Handling: key press 'a'

    This line is printed by a handler the loop called for the key press event. The letter a is the information carried by that event.

  3. 3
    Line 3: Handling: mouse move to (5, 5)

    This line is printed by a handler the loop called for the mouse move event. The destination (5, 5) is the information this event reports.

  4. 4
    Line 4: Program finished

    This is the only line not tied to an event. It appears after the last event has been handled, so it is not produced by any single handler.

Result

Lines 1 to 3 each map to one event, in the order the events occurred. Line 4 is printed after the events are finished.

Mistakes Beginners Make with Event Order

  • Common mistake

    Expecting a GUI program to run its handlers in the order they appear in the source file

    What it looks like

    Assuming the mouse handler must run before the key handler just because it is written first

    Why it fails

    The order of events is decided by the user at unpredictable times, not by the order of methods in the code.

    Do this instead

    Think of each handler as a response that runs only when its event occurs.

  • Common mistake

    Thinking the programmer must write the event loop in Java

    What it looks like

    Trying to add a while loop that waits for clicks inside a Java GUI program

    Why it fails

    In Java the event loop is part of the system. The programmer writes the handling methods.

    Do this instead

    Write the handler methods that say what should happen for each event type.

  • Common mistake

    Treating a MouseEvent as only a click

    What it looks like

    Believing a MouseEvent exists only when a button is pressed

    Why it fails

    The traced program also produces a mouse move event, which is handled separately with its own destination coordinates.

    Do this instead

    Read the event object to find out what kind of user action it describes.

  • Common mistake

    Looking for the source of the Program finished line among the events

    What it looks like

    Assuming Program finished is printed by a handler for some event

    Why it fails

    The source states that this is the only line not tied to an event, printed after the last event is handled.

    Do this instead

    Locate it as the final step after the event cycle has finished.

Practice Tracing Event Output

EASY

Suppose a GUI program receives these events in order: a key press of the letter b, then a mouse click at (3, 7). Using the event loop cycle, describe what the loop does for each event, which kind of event object is involved for each, and what information each event object carries. Finally, state what line you would expect at the end of the output if the program then stops.

Hints
  • For each event, ask whether the system creates a MouseEvent or a KeyEvent.
  • A MouseEvent carries the source, the coordinates, the time, and the button. A KeyEvent represents a key press.
  • The final line that is not tied to any event appears after the last event has been handled.
MEDIUM

Reorder three events of your own choice, for example a mouse move, a key press, and a mouse click. Predict the output lines before you check them, and explain which event produced each line.

Hints
  • Write the events in the order they occur, then match one handler call to each event.
  • Remember that the final line is printed only after all events are handled.

Key Takeaways

  • A GUI program has no main() routine that runs step by step from beginning to end, because it must respond to events that happen at unpredictable times and in an order the program does not control.
  • In Java, each event is an object. A MouseEvent records the source component, the (x, y) coordinates, the time, and the mouse button, and a KeyEvent is created for key presses.
  • Every GUI program has an event loop that waits for the next event and calls a subroutine to handle it. In Java the system provides this loop, so the programmer writes the handling methods.
  • The verified output of the traced program has four lines: three are printed by handlers for the click, key press, and mouse move events, and the final Program finished line appears after the last event is handled.