Blog about Programming Languages & Coding

Blog about Programming Languages & Coding
Contents for Computer Science, IT, B.Sc. CS & IT, M.Sc. CS & IT, MCA, BE CS & IT, ME CS & IT , Interview Questions, Books and Online Course Recommendations from Udemy, Coursera, etc

Event Handling in Swing

 

The Delegation Event Model

 

  1. The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events.
  2. Its concept is quite simple: a source generates an event and sends it to one or more listeners.
  3. In the scheme, the listener simply waits until it receives an event.  Once received, the listener processes event and then returns.  The advantage of this design is that the application logic that processes events is clearly separated from the user interface logic that generates those events.
  4. In the delegation event model, listeners must register with a source in order to receive an event notification.  This provides an important benefit: notifications are sent only to listeners that want to receive them.

Event:

  1. An event is an object that describes some change in source.  It can be generated when a person interacts with an element in a GUI.  For example pressing a button, clicking a mouse, double clicking on a list box entry or closing window.

 

  1. Events may also occur that are not directly caused by interactions with a user interface.  For example, an event may be generated when a time expires, counter exceeds a value, a software or hardware failure occurs.

Event Source:

          A source generates events.  It has three main responsibilities

1.    It must provide methods that allow listeners to register and unregister for notifications about a specific type of events.

2.    It must generate the event

3.    It must send the event to all registered listeners.  The event may be a unicast to a single listeners or multicast to several listeners.  It is possible for a source to generate several types of events.

4.    Each type of event has its own registration method. Here is the general form:

                                 public void addTypeListener(TypeListener el)

Event Listeners:

A listener receives event notifications.  It has three main responsibilities

1.    It must register to receive notifications account specific events.  It does so by calling the appropriate registration method of source.

2.    It must implement an interface to receive events of that type.

3.    It must unregister if it is no longer to proceed those notifications.  It does so by calling appropriate unregistration method of the source.

 

Event Classes

The classes that represent events are at the core of Java’s event handling mechanism.

 


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.

 

Method

Description

Object getSource( )

Returns the object that generated the event

String toString( )

Returns the string equivalent of the event

 

To summarize:

EventObject is a superclass of all events.

AWTEvent is a superclass of all AWT events that are handled by the delegation

event model.

The package java.awt.event defines several types of events that are generated by

various user interface elements

 

Main Event Classes in java.awt.event

 

Event Class

Generated When

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 hidden, 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

 

A mouse or key event occurs.

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.

 

 

Sources of Events

The table lists some of the user interface components that can generate the events

 

Event Source

Description

Button

Generates action events when the button is pressed.

Checkbox

Generates item events when the check box is selected or deselected.

Choice

Generates item events when the choice is changed.

List

Generates action events when an item is double-clicked; generates item events when an item is selected or deselected.

Menu Item

Generates action events when a menu item is selected; generates item events when a checkable menu item is selected or deselected.

Scrollbar

Generates adjustment events when the scroll bar is manipulated.

Text components

Generates text events when the user enters a character.

Window

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

 

Event Listener Interfaces

 

The delegation event model has two parts: sources and listeners. Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package. When an event occurs, the event source invokes the appropriate method defined by the listener and provides an event object as its argument. Table lists commonly used listener interfaces and provides a brief description of the methods that they define.

 

Interface

Description

Methods

ActionListener

Defines one method to receive action events.

void actionPerformed(ActionEvent ae)

 

AdjustmentListener

Defines one method to receive adjustment events.

void adjustmentValueChanged(AdjustmentEvent ae)

 

ComponentListener

Defines four methods to recognize when a component is hidden, moved, resized, or shown.

void componentResized(ComponentEvent ce)

void componentMoved(ComponentEvent ce)

void componentShown(ComponentEvent ce)

void componentHidden(ComponentEvent ce)

 

ContainerListener

Defines two methods to recognize when a component is added to or removed from a container.

void componentAdded(ContainerEvent ce)

void componentRemoved(ContainerEvent ce)

 

FocusListener

Defines two methods to recognize when a component gains or loses keyboard focus.

 

void focusGained(FocusEvent fe)

void focusLost(FocusEvent fe)

 

ItemListener

Defines one method to recognize when the state of an item changes.

void itemStateChanged(ItemEvent ie)

 

KeyListener

Defines three methods to recognize when a key is pressed, released, or typed.

void keyPressed(KeyEvent ke)

void keyReleased(KeyEvent ke)

void keyTyped(KeyEvent ke)

 

MouseListener

Defines five methods to recognize when the mouse is clicked, enters a component, exits a component, is pressed, or is released.

void mouseClicked(MouseEvent me)

void mouseEntered(MouseEvent me)

void mouseExited(MouseEvent me)

void mousePressed(MouseEvent me)

void mouseReleased(MouseEvent me)

 

MouseMotionListener

Defines two methods to recognize when the mouse is dragged or moved.

void mouseDragged(MouseEvent me)

void mouseMoved(MouseEvent me)

 

TextListener

Defines one method to recognize when a text value changes.

void textChanged(TextEvent te)

 

WindowFocusListener

Defines two methods to recognize when a window gains or loses input focus.

void windowGainedFocus(WindowEvent we)

void windowLostFocus(WindowEvent we)

 

WindowListener

Defines seven methods to recognize when a window is activated, closed, deactivated, deiconified, iconified, opened,

void windowActivated(WindowEvent we)

void windowClosed(WindowEvent we)

void windowClosing(WindowEvent we)

void windowDeactivated(WindowEvent we)

void windowDeiconified(WindowEvent we)

void windowIconified(WindowEvent we)

void windowOpened(WindowEvent we)

 

 Event Listener Interfaces

  • java.awt.Event package : Listener interfaces to handle events.


All the interfaces and the methods in them.
 

Event

Generated by

Listener Interface

Methods in them

ActionEvent

Pressing a button

ActionListener

actionPerformed()

AdjustmentEvent

Scroll bar is manipulated

AdjustmentListener

adjustmentValueChanged()

TextEvent

Text value is changed

TextListener

textValueChanged()

ItemEvent

An item is selected or deselected

ItemListener

itemStateChanged()

ComponentEvent

A component is hidden, moved, resized, or shown

ComponentListener

componentHidden() 
componentMoved()  

componentResized() 
componentShown()

ContainerEvent

A component is added or removed from a container

ContainerListener

componentAdded() 
componentRemoved()

FocusEvent

A component gains or loses focus

FocusListener

focusGained() 
focusLost()

MouseEvent

Mouse button is clicked, pressed or released.  Mouse pointer enters leaves a component

MouseListener

mouseClicked() 
mouseEntered() 
mouseExited() 
mousePressed() 
mouseReleased()

MouseEvent

Mouse pointer is dragged or moved

MouseMotionListener

mouseDragged() 
mouseMoved()

KeyEvent

A key is pressed, released or typed

KeyListener

keyPressed() 
keyReleased() 
keyTyped()

WindowEvent

A window is activated, closed, deactivated, deiconfied, opened, or quit

WindowListener

windowActivated() 
windowClosed() 
windowClosing() 
windowDeactivated() 
windowDeiconified() 
windowIconified() 
windowOpened()





Getting ready to handle events


Step 1: Import classes from the package:
 

import java.awt.event.*;


Step 2: Implement the appropriate listener interfaces.
 

public class sample extends Applet implements listenerinterface1, listenerinterface2{

} //Several listener interfaces can be listed, separated by commas.
 

Step 3: Register the listener object with the appropriate event source.
 

event_source.addXXXListener(event_listener_object);



Step 4: Define all the methods of the implemented listener interfaces. 


MouseEvent

 

Event Class

MouseEvent


Listener Interface

MouseListener


Listener Methods

public void mouseEntered(MouseEvent event) 
public void mouseExited(MouseEvent event) 
public void mouseClicked(MouseEvent event) 
public void mousePressed(MouseEvent event) 
public void mouseReleased(MouseEvent event) 

By looking at the name of the methods, it is clear which activity invokes which method. 

event.getX() returns (int) the x coordinate of mouse position. 
event.getY() returns (int) the y coordinate of mouse position. 
event.getClickCount() returns (int) the number of mouse clicks.

Four steps:

Step 1: Include the following import statement:
 

import java.awt.event.*;


Step 2: Include Implements MouseListener :
 

public class w2 extends Applet implements MouseListener {

}
 

Step 3: Register addMouseListener method in the applet.
 

this.addMouseListener (this);




MouseMotion Events:

  • Moving and dragging the mouse generates an object of the MouseEvent class.

 

Event Class

MouseEvent


Listener Interface

MouseMotionListener


Listener Methods

public void mouseMoved(MouseEvent event) 

Invoked when the mouse button has been moved on a component (with no buttons down).

public void mouseDragged(MouseEvent event)

Invoked when a mouse button is pressed on a component and then dragged.

event.getX() returns (int) the x coordinate of mouse position. 

event.getY() returns (int) the y coordinate of mouse position. 

event.getClickCount() returns (int) the number of mouse clicks.



Keyboard Events

  Whenever a key is pressed, an object of the KeyEvent class is generated.

Event Class

  KeyEvent


Listener Interface

KeyListener


Listener Methods

public void keyPressed(KeyEvent event) 

Invoked when a key is pressed. 

public void keyReleased(KeyEvent event) 

Invoked when a key is released. 

public void keyTyped(KeyEvent event) 

Invoked when a key is typed (pressed and released).


KeyEvent class

For a list of Class variables (virtual key codes), which are defined as static and final, see Virtual Key Codes table below. 

event.getKeyChar() returns (char) the character pressed. 

event.getKeyCode() returns (int) the "virtual key code", see table below. 

event.getModifiers().

event.isShiftDown() returns (boolean) true if shift key is down. 

event.isControlDown() returns (boolean) true if control key is down. 

event.isAltDown() returns (boolean) true if alt key is down 

KeyEvent.getKeyModifiersText(int modifiers) returns (String).

KeyEvent.getKeyText(int keycode) returns (String).


 

Virtual Key Codes

  • Refer to the key on the keyboard returned by event.getKeyCode()

  • Produce a numeric value - but - use the symbol in the program. 

  • No guarantee that the numeric value produced is the same on all platforms.

Alpha keys

VK_A through VK_Z

Numeric keys

VK_0 through VK_9


Function keys

VK_F1 through VK_F12 


Action keys

VK_BACK_SPACE 

VK_ESCAPE, VK_PRINTSCREEN, VK_SCROLL_LOCK, VK_PAUSE 


Num pad number keys

VK_NUMPAD0 through VK_NUMPAD9


Other Num pad keys

VK_NUM_LOCK, 

VK_SLASH, 

VK_MULTIPLY, 

VK_SUBTRACT, 

VK_ADD, VK_HOME, 

VK_UP, 

VK_PAGE_UP, 

VK_LEFT, 

VK_RIGHT, 

VK_END, 

VK_DOWN, 

VK_PAGE_DOWN, 

VK_INSERT, 

VK_DELETE, 

VK_ENTER


Modifier keys

VK_ALT, 

VK_CAPS_LOCK, 

VK_CONTROL, 

VK_SHIFT

Punctuation keys

VK_SPACE, 

VK_ENTER, 

VK_TAB, 

VK_BACK_QUOTE, 

VK_SLASH, 

VK_BACK_SLASH, 

VK_OPEN_BRACKET, 

VK_CLOSE_BRACKET, 

VK_PERIOD, 

VK_QUOTE, 

VK_SEMICOLON, 

VK_SEPARATOR, 

VK_COMMA, 

VK_DECIMAL, 

VK_EQUALS, 

Other keys

VK_ACCEPT, 

VK_CANCEL, 

VK_CLEAR, 

VK_CONVERT, 

VK_FINAL, 

VK_HELP, 

VK_KANA, 

VK_KANJI, 

VK_MODECHANGE, 

VK_NONCONVERT, VK_UNDEFINED, 


// Demonstrate the mouse event handlers.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

 

/*<applet code="MouseEvents" width=300 height=100> </applet>*/

public class MouseEvents extends Applet implements MouseListener,  MouseMotionListener {

 

String msg = "";

int mouseX = 0, mouseY = 0; // coordinates of mouse

public void init() {

addMouseListener(this);

addMouseMotionListener(this);

}

// Handle mouse clicked.

public void mouseClicked(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse clicked.";

repaint();

}

// Handle mouse entered.

public void mouseEntered(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse entered.";

repaint();

}

 

// Handle mouse exited.

public void mouseExited(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse exited.";

repaint();

}

 

// Handle button pressed.

public void mousePressed(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Down";

repaint();

}

 

// Handle button released.

public void mouseReleased(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Up";

repaint();

}

// Handle mouse dragged.

public void mouseDragged(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "*";

showStatus("Dragging mouse at " + mouseX + ", " + mouseY);

repaint();

}

 

// Handle mouse moved.

public void mouseMoved(MouseEvent me) {

// show status

showStatus("Moving mouse at " + me.getX() + ", " + me.getY());

}

 

// Display msg in applet window at current X,Y location.

public void paint(Graphics g) {

g.drawString(msg, mouseX, mouseY);

}

}

Sample output:

 

THE// Demonstrate the key event handlers.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

 

/* <applet code="SimpleKey" width=300 height=100> </applet> */

public class SimpleKey extends Applet implements KeyListener {

String msg = "";

int X = 10, Y = 20; // output coordinates

public void init() {

addKeyListener(this);

requestFocus(); // request input focus

}

public void keyPressed(KeyEvent ke) {

showStatus("Key Down");

}

public void keyReleased(KeyEvent ke) {

showStatus("Key Up");

}

public void keyTyped(KeyEvent ke) {

msg += ke.getKeyChar();

repaint();

}

// Display keystrokes.

public void paint(Graphics g) {

g.drawString(msg, X, Y);

}

}

 JAVA LIBRARY

Sample output:

 

// Demonstrate some virtual key codes.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

 

/*<applet code="KeyEvents" width=300 height=100> </applet> */

 

public class KeyEvents extends Applet implements KeyListener {

String msg = "";

int X = 10, Y = 20; // output coordinates

public void init() {

addKeyListener(this);

requestFocus(); // request input focus

}

 

public void keyPressed(KeyEvent ke) {

showStatus("Key Down");

int key = ke.getKeyCode();

switch(key) {

 

case KeyEvent.VK_F1:

msg += "<F1>";

break;

case KeyEvent.VK_F2:

msg += "<F2>";

break;

case KeyEvent.VK_F3:

msg += "<F3>";

break;

case KeyEvent.VK_PAGE_DOWN:

msg += "<PgDn>";

break;

case KeyEvent.VK_PAGE_UP:

msg += "<PgUp>";

break;

case KeyEvent.VK_LEFT:

msg += "<Left Arrow>";

break;

case KeyEvent.VK_RIGHT:

msg += "<Right Arrow>";

break;

}

repaint();

}

public void keyReleased(KeyEvent ke) {

showStatus("Key Up");

}

public void keyTyped(KeyEvent ke) {

msg += ke.getKeyChar();

repaint();

}

// Display keystrokes.

public void paint(Graphics g) {

g.drawString(msg, X, Y);

}

}

Sample output:

 

Event Handling in Swing Event Handling in Swing Reviewed by Asst. Prof. Sunita Rai on August 24, 2022 Rating: 5

No comments:

Powered by Blogger.