Java event handling
Event handling in Java refers to executing some code when specific things occur such as a window being minimized or a button being clicked.
To demonstrate event handling in action in this tutorial we will be using frames. A frame in Java is a standard graphical window. We will be catching window events like minimize and maximize and performing some action accordingly.
This tutorial focuses on:
- Handling events
- Setting up the event functionality
- Making objects listen for events
- An entire frame with events
There are several types of events that can happen in a Java program:
- Window events - Occur when something happens with the program window such as maximizing the window, minimizing the window, or closing the window.
- Action events - Occur when something happens with a component such as the clicking of a button
- Focus events - Occur when a component gains or loses focus
- Mouse events - Occur when something happens with the mouse such as moving the mouse or clicking the mouse
- Key events - Occur when something happens with the keyboard such as a key is pressed or a key is released.
Each event type has it's own interface that you need to implement in a program to handle those events. These interfaces are located in the java.awt.event package.
- Window events - WindowListener interface
- Action events - ActionListener interface
- Focus events - FocusListener interface
- Mouse events - MouseListener, MouseMotionListener interfaces
- Key events - KeyListener interface
Each interface has it's own methods to use to execute some code when certain events occur. For example, the KeyListener interface has a keyPressed method that can be used to execute some code when a key is pressed.
Setting up the event functionality
Let's start with a simple frame that will have window events. and then we will add event functionality to it.
Now we need to use the methods of the WindowListener interface to specify what happens during window events.
NOTE: When you implement an interface, you have to define all of it's methods in your program.
Making objects listen for events
Now that we implemented the interface and set up the methods we need to specify which component will listen for these events and trigger the functionality accordingly. To do this, we will need to use an event listener. To use an event listener the addWindowListener() method will be used on the component that will listen for these events - the frame.
An entire frame with events
Here is the code for the entire frame. This frame utilizes all the window event methods. Try it and see how your command prompt will display different messages as you perform actions such as minimize and maximize on the frame.