The classes that represent events are at the core of Javas event handling mechanism. Java defines several types of events and arguably, the most widely used events are those defined by the AWT and those defined by Swing. The focus on this article are AWT events (most of these also apply to Swing).

At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all events. Its one constructor is shown here:

EventObject(Object src)

Here src is the object that generates this event.

EventObject defines two methods: getSource() and toString(). The getSource() method returns the source of the event. Its general form is shown here:

Object getSource()

As expected, toString() returns the string equivalent of the event.

The class AWTEvent, defined within the java.awt package, is a subclass if EventObject. It is the superclass (either directly or indirectly) of all AWT-based events used by the delegation event model. Its getID() method can be used to determine the type of event. The signature of this method looks like this:

int getID()

All of the other classes discussed in this article are subclasses of AWTEvent.

The package java.awt.event defines many types of events that are generated by various user interface elements. The table below shows several commonly used event classes and provides a brief description of when they are generated:

Event Class

Description

ActionEvent

Generated when a button is pressed, a list item is double-clicked, or a menu item is selected.

AdjustmentEvent

Generated when a scroll bar is manipulated.

ComponentEvent

Generated when a component is hiden, moved, resized or becomes visible.

ContainerEvent

Generated when a component is added to or removed from a container.

FocusEvent

Generated when a component gains or loses keyboard focus.

InputEvent

Abstract superclass for all component input event classes.

ItemEvent

Generated when a check box or list item is clicked; also occurs when a choice selection is made or a checkable menu item is selected or deselected.

KeyEvent

Generated when input is received from the keyboard.

MouseEvent

Generated when the mouse is dragged, moved, clicked, pressed or released; also generated when the mouse enters or exits a component.

MouseWheelEvent

Generated when the mouse wheel is moved.

TextEvent

Generated when the value of a text area or text field is changed.

WindowEvent

Generated when a window is activated, closed, deactivated, deiconified, iconified, opened or quit.

The ActionEvent Class:

An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is selected. The ActionEvent class defines four integer constants that can be used to identify any modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK and SHIFT_MASK. In addition, there is an integer constant, ACTION_PERFORMED, which can be used to identify action events.

ActionEvent has these three constructors:

        1. ActionEvent(Object src, int type, String cmd)

        2. ActionEvent(Object src, int type, String cmd, int modifiers)

        3. ActionEvent(Object src, int type, String cmd, long when, int modifiers)

Here src is a reference to the object that generated this event. The type of event is specified by type, and its command string is cmd. The argument modifiers indicates which modifier keys (alt, ctrl, meta and/or shift) were pressed when the event was generated. The when parameter specifies when the event occurred.

You can obtain the command name for the invoking ActionEvent object by using the getActionCommand() method, shown here:

String getActionCommand()

For example when a button is pressed, an action event is generated that has a command name equal to the label of that button.

The getModifiers() method returns a value that indicates which modifier keys (ALT< CTRL< META and/or SHIFT) were pressed when the event was generated. Its form is shown here:

int getModifiers()

The method getWhen() returns the time at which the event took place. This is called the events timestamp. The getMethod() is shown here:

long getWhen()

The AdjustmentEvent Class:

An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events. The AdjustmentEvent class defines integer constants that can be used to identify them. In the following table you can see the constants and their meanings:

BLOCK_DECREMENT

The user clicked inside the scroll bar to decrease its value.

BLOCK_INCREMENT

The user clicked inside the scroll bar to increase its value.

TRACK

The slider was dragged.

UNIT_DECREMENT

The button at the end of the scroll bar was clicked to decrease its value.

UNIT_INCREMENT

The button at the end of the scroll bar was clicked to increase its value.

In addition, there is an integer constant, ADJUSTMENT_VALUE_CHANGED, that indicates that a change has occurred.

Here is one AdjustmentEvent constructor:

AdjustmentEvent(Adjustable src, int id, int type, int val)

Here src is a reference to the object that generated this event. The id specifies the event. The type of the adjustment is specified by type, and its associated value is val.

The getAdjustable() method returns the object that generated the event. This is how its form looks like:

Adjustable getAdjustable()

The type of adjustment can be obtained from the getValue() method, shown here:

int getValue()

For example, when a scroll bar is manipulated, this method returns the value represented by that change.

The ComponentEvent Class:

An ComponentEvent is generated when the size, position, or visibility of a component is changed. There are four types of component events. The ComponentEvent class defines integer constants that can be used to identify them. The following table shows the constants and their meanings:

COMPONENT_HIDDEN

The component was hidden.

COMPONENT_MOVED

The component was moved.

COMPONENT_RESIZED

The component was resized.

COMPONENT_SHOWN

The component became visible.

ComponentEvent has this constructor:

ComponentEvent(Component src, int type)

Here src is a reference to the object that generated this event. The type of the event is specified by type.

ComponentEvent is the superclass either directly or indirectly of ContainerEvent, FocusEvent, KeyEvent, MouseEvent and WindowEvent, among others.

The getComponent() method returns the component that generated the event:

Component getComponent()

The ContainerEvent Class:

An ContainerEvent is generated when a component is added or removed from a container. There are two types of container events. The ContainerEvent class defines int constants that can be used to identify them:

COMPONENT_ADDED

It indicates when a component is added to a container.

COMPONENT_REMOVED

It indicates when a component is removed from a container.

ContainerEvent is a subclass of ComponentEvent and it has this constructor:

ContainerEvent (Component src, int type, Component comp)

Here, src is a reference to the container that generated this event. The type of the event is specified by type, and the component that has been added or removed from the container is comp.

You can obtain a reference to the container that generated this event by using the getContainer() method:

Container getContainer()

The getChild() method returns a reference to the component that was added to or removed from the container. Its general form is:

Component getChild()

The FocusEvent Class:

A FocusEvent is generated when a component gains or loses input focus. These events are identified by the integer constants FOCUS_GAINED and FOCUS_LOST.

FocusEvent is a subclass of ComponentEvent and has these constructors:

  1. FocusEvent(Component src, int type)

  2. FocusEvent(Component src, int type, boolean temporaryFlag)

  3. FocusEvent(Component src, int type, boolean temporaryFlag, Component other)

  4. FocusEvent(Component src, int type, boolean temporaryFlag, Component other, FocusEvent.Cause what)

Here, src is a reference to the component that generated this event. The type of the event is specified by type. The argument temporaryFlag is set to true if the focus event is temporary. Otherwise, it is set to false. (A temporary focus event occurs as a result of another user interface operation. For example, assume that the focus is in a text field. If the user moves the mouse to adjust a scroll bar, the focus is temporarily lost.)

The other component involved in the focus change, called the opposite component, is passed in other. Therefore, if a FOCUS_GAINED event occurred, other will refer to the component that lost focus. Conversely, if a FOCUS_LOST event occurred, other will refer to the component that gains focus. The fourth constructor was added by JDK 9. Its what parameter specifies why the event was generated. It is specified as a FocusEvent.Cause enumeration value that identifies the cause of the focus event. The FocusEvent.Cause enumeration was also

added by JDK 9.

You can determine the other component by calling getOppositeComponent(), shown here:

Component getOppositeComponent( )

The opposite component is returned.

The isTemporary() method indicates if this focus change is temporary. Its form is shown here:

boolean isTemporary()

The method returns true if the change is temporary. Otherwise, it returns false. Beginning with JDK 9, you can obtain the cause of the event by calling getCause(), shown here:

final FocusEvent.Cause getCause()

The cause is returned in the form of a FocusEvent.Cause enumeration value.

The InputEvent Class:

The abstract class InputEvent is a subclass of ComponentEvent and is the superclass for component input events. Its subclasses are KeyEvent and MouseEvent.

InputEvent defines several integer constants that represent any modifiers, such as the control key being pressed, that might be associated with the event. Originally, the InputEvent class defined the following eight values to represent the modifiers, and these modifiers may still be found in older legacy code:

ALT_MASK

BUTTON2_MASK

META_MASK

ALT_GRAPH_MASK

BUTTON3_MASK

SHIFT_MASK

BUTTON1_MASK

CTRL_MASK

However, because of possible conflicts between the modifiers used by keyboard events and mouse events, and other issues, the following extended modifier values were added:

ALT_DOWN_MASK

BUTTON2_DOWN_MASK

META_DOWN_MASK

ALT_GRAPH_DOWN_MASK

BUTTON3_DOWN_MASK

SHIFT_DOWN_MASK

BUTTON1_DOWN_MASK

CTRL_DOWN_MASK

The original modifiers have have been deprecated by JDK 9.

To test if a modifier was pressed at the time an event is generated, use the isAltDown(), isAltGraphDown(), isControlDown(), isMetaDown(), and isShiftDown() methods. The forms of these methods are shown here:

boolean isAltDown( )

boolean isAltGraphDown( )

boolean isControlDown( )

boolean isMetaDown( )

boolean isShiftDown( )

It is possible to obtain a value that contains all of the original modifier flags by calling the getModifiers() method. It is shown here:

int getModifiers()

Although you may still encounter getModifiers() in legacy code, it is important to point out that because the original modifier flags have been deprecated by JDK 9, this method has also been deprecated by JDK 9. Instead, you should obtain the extended modifiers by calling getModifiersEx(), which is shown here:

int getModifiersEx()

The ItemEvent Class:

An ItemEvent is generated when a check box or a list item is clicked or when a checkable menu item is selected or deselected. There are two types of item events, which are identified by these two integer constants:

DESELECTED

The user deselected an item.

SELECTED

The user selected an item.

In addition, ItemEvent defines the integer constant ITEM_STATE_CHANGED, that signifies a change of state.

ItemEvent has this constructor:

ItemEvent (ItemSelectable src, int type, Object entry, int state)

Here, src is a reference to the component that generated this event. For example, this might be a list or choice element. The type of the event is specified by type. The specific item that generated the item event is passed in entry. The current state of that item is in state.

The getItem() method can be used to obtain a reference to the item that changed.

Its signature is shown here:

Object getItem()

The getItemSelectable() method can be used to obtain a reference to the ItemSelectable object that generated an event. Its general form is shown here:

ItemSelectable getItemSelectable()

Lists and choices are examples of user interface elements that implement the ItemSelectable interface.

The getStateChange() method returns the state change (that is, SELECTED or DESELECTED) for the event. It is shown here:

int getStateChange()

The KeyEvent Class:

A KeyEvent is generated when keyboard input occurs. There are three types of key events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two events are generated when any key is pressed or released. The last event occurs only when a character is generated. Remember, not all key presses result in characters. For example, pressing shift does not generate a character.

There are many other integer constants that are defined by KeyEvent. For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and letters. Here are some others:

VK_ALT

VK_DOWN

VK_LEFT

VK_RIGHT

VK_CANCEL

VK_ENTER

VK_PAGE_DOWN

VK_SHIFT

VK_CONTROL

VK_ESCAPE

VK_PAGE_UP

VK_UP

The VK constants specify virtual key codes and are independent of any modifiers, such as control, shift or alt.

KeyEvent is a subclass of InputEvent. Here is one of its constructors:

KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)

Here, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the key was pressed is passed in when. The modifiers argument indicates which modifiers were pressed when this key event occurred. The virtual key code, such as VK_UP, VK_A, and so forth, is passed in code. The character equivalent (if one exists) is passed in ch. If no valid character exists, then ch contains CHAR_UNDEFINED. For KEY_TYPED events, code will contain VK_UNDEFINED.

The KeyEvent class defines several methods, but probably the most commonly used ones are getKeyChar(), which returns the character that was entered, and getKeyCode(), which returns the key code. Their general forms are shown here:

char getKeyChar()

int getKeyCode()

If no valid character is available, then getKeyChar() returns CHAR_UNDEFINED. When a KEY_TYPED event occurs, getKeyCode() returns VK_UNDEFINED.

The MouseEvent Class:

There are eight types of mouse events. The MouseEvent class defines the following integer constants that can be used to identify them:

MOUSE_CLICKED

The user clicked the mouse.

MOUSE_DRAGGED

The user dragged the mouse.

MOUSE_ENTERED

The mouse entered a component.

MOUSE_EXITED

The mouse exited from a component.

MOUSE_MOVED

The mouse moved.

MOUSE_PRESSED

The mouse was pressed.

MOUSE_RELEASED

The mouse was released.

MOUSE_WHEEL

The mouse wheel was moved.

MouseEvent is a subclass of InputEvent. Here is one of its constructors:

MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup)

Here, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which modifiers were pressed when a mouse event occurred. The coordinates of the mouse are passed in x and y. The click count is passed in clicks. The triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.

Two commonly used methods in this class are getX() and getY(). These return the X and Y coordinates of the mouse within the component when the event occurred. Their forms are shown here:

int getX()

int getY()

Alternatively, you can use the getPoint() method to obtain the coordinates of the mouse. It is shown here:

Point getPoint( )

It returns a Point object that contains the X,Y coordinates in its integer members: x and y. The translatePoint() method changes the location of the event. Its form is shown here:

void translatePoint(int x, int y)

Here, the arguments x and y are added to the coordinates of the event.

The getClickCount() method obtains the number of mouse clicks for this event. Its signature is shown here:

int getClickCount()

The isPopupTrigger() method tests if this event causes a pop-up menu to appear on this platform. Its form is shown here:

boolean isPopupTrigger()

Also available is the getButton() method, shown here:

int getButton()

It returns a value that represents the button that caused the event. For most cases, the return value will be one of these constants defined by MouseEvent:

NOBUTTON

BUTTON1

BUTTON2

BUTTON3

The NOBUTTON value indicates that no button was pressed or released.

Also available are three methods that obtain the coordinates of the mouse relative to the screen rather than the component. They are shown here:

Point getLocationOnScreen()

int getXOnScreen()

int getYOnScreen()

The getLocationOnScreen() method returns a Point object that contains both the X and Y coordinate. The other two methods return the indicated coordinate.

The MouseWheelEvent Class:

The MouseWheelEvent class encapsulates a mouse wheel event. It is a subclass of MouseEvent. Not all mice have wheels. If a mouse has a wheel, it is typically left and right buttons and it’s used for scrolling.

MouseWheelEvent defines these two integer constants:

WHEEL_BLOCK_SCROLL

A page up or page-down scroll event occurred.

WHEEL_UNIT_SCROLL

A line-up or line-down scroll event occurred.

Here is one of the constructors defined by MouseWheelEvent:

MouseWheelEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup, int scrollHow, int amount, int count)

Here, src is a reference to the object that generated the event. The type of the event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which modifiers were pressed when the event occurred. The coordinates of the mouse are passed in x and y. The number of clicks is passed in clicks. The triggersPopup flag indicates if this event causes a popup menu to appear on this platform. The scrollHow value must be either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_ SCROLL. The number of units to scroll is passed in amount. The count parameter indicates the number of rotational units that the wheel moved.

MouseWheelEvent defines methods that give you access to the wheel event. To obtain the number of rotational units, call getWheelRotation(), shown here:

int getWheelRotation()

It returns the number of rotational units. If the value is positive, the wheel moved counterclockwise. If the value is negative, the wheel moved clockwise.

Also available is a method called getPreciseWheelRotation(), which supports highresolution wheels. It works like getWheelRotation(), but returns a double.

To obtain the type of scroll, call getScrollType(), shown next:

int getScrollType()

It returns either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL. If the scroll type is WHEEL_UNIT_SCROLL, you can obtain the number of units to scroll by calling getScrollAmount(). It is shown here:

int getScrollAmount()

The TextEvent Class:

Instances of this class describe text events. These are generated by text fields and text areas when characters are entered by a user or a program. TextEvent defines the integer constant TEXT_VALUE_CHANGED.

The one constructor for this class is shown here:

TextEvents(Object src, int type)

Here, src is a reference to the object that generated this event. The type of the event is specified by type.

The TextEvent object does not include the characters currently in the text component that generated the event. Instead, your program must use other methods associated with the text component to retrieve that information. This operation differs from other event objects discussed in this section. Think of a text event notification as a signal to a listener that it should retrieve information from a specific text component.

The WindowEvent Class:

There are ten types of window events. The WindowEvent class defines integer constants that can be used to identify them. You will see the constants and their meanings in the following table:

WINDOW_ACTIVATED

The window was activated.

WINDOW_CLOSED

The window has been closed.

WINDOW_CLOSING

The user requested that the windows be closed.

WINDOW_DEACTIVATED

The window was deactivated.

WINDOW_DEICONIFIED

The window was deiconified.

WINDOW_GAINED_FOCUS

The window gained input focus.

WINDOW_ICONIFIED

The window was iconified.

WINDOW_LOST_FOCUS

The window lost input focus.

WINDOW_OPENED

The window was opened.

WINDOW_STATE_CHANGED

The state of the window changed.

WindowEvent is a subclass of ComponentEvent. It defines several constructors. The first is:

WindowEvent(Window src, int type)

Here, src is a reference to the object that generated this event. The type of the event is type.

The next three constructors offer more detailed control:

WindowEvent(Window src, int type, Window other)

WindowEvent(Window src, int type, int fromState, int toState)

WindowEvent(Window src, int type, Window other, int fromState, int toState)

Here, other specifies the opposite window when a focus or activation event occurs. The fromState specifies the prior state of the window, and toState specifies the new state that the window will have when a window state change occurs.

A commonly used method in this class is getWindow(). It returns the Window object that generated the event. Its general form is shown here:

Window getWindow()

WindowEvent also defines methods that return the opposite window (when a focus or activation event has occurred), the previous window state, and the current window state. These methods are shown here:

Window getOppositeWindow()

int getOldState()

int getNewState()

That was all about the Event Classes. Hope you`ll find some valuable info. We are learning together. Happy coding!

Source: Herbert Schildt – Java. The Complete Reference. Tenth Edition – 2017

Spread the love

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *