Event Handling. Event Driven Programming Flow of programs is determined by events. The Operating...

Preview:

Citation preview

Event Handling

Event Driven Programming

Flow of programs is determined by events.The Operating system recognizes events and passes them to

the particular application.• The signals that a program receives from the operating

system as a result of your actions are called events.• Each event is associated with a method that is called when

event occurs.

Event Handling

• Source Object

• Event Object (An object passed to the java program as a result of an event)

• Listener Object (that receives the event)

Java Packages for events

• java.awt.event package – contains most of the events relating to the GUI

• javax.swing.event – defines classes for events that are specific to

Swing components.

Example:

Event Classes

• Low Level Events– These are system-level events that arise from the

keyboard or from the mouse, or events associated with operations on a window

• Semantic Events– These are specific component-related events

such as pressing a button by clicking it to cause some program action or adjusting a scrollbar.

Low Level Event Classes

Hierarchy of Event Classes

The AWTEvent class is itself a subclass of

java.util.EventObject.

AWT Event Class

The AWTEvent class defines constants that are public final values identifying the various kinds of events. These constants are named for the sake of consistency as the event name in capital letters, followed by _MASK. The constants identifying the low-level events that you are most likely to be interested in :

Windows Event Handling

• Window can handle its own events.• For Example : Closing a Window

enableEvents(WINDOW_EVENT_MASK)// Handle window eventsprotected void processWindowEvent(WindowEvent e) {if (e.getID() == WindowEvent.WINDOW_CLOSING) {dispose(); // Release resourcesSystem.exit(0); // Exit the program}super.processWindowEvent(e); // Pass on the event}

Other Windows Events

• Handling more that one event– enableEvents(WINDOW_EVENT_MASK |

MOUSE_EVENT_MASK); using processMouseEvent()

• To handle window focus event– processWindowFocusEvent(WindowEvent e)

• For window changing State– processWindowStateEvent(WindowEvent e)

Methods for Other Components

• processEvent(AWTEvent e)

• processFocusEvent(FocusEvent e)

• processKeyEvent(KeyEvent e)

• processMouseEvent(MouseEvent e)

• processMouseMotionEvent(MouseEvent e)

• processMouseWheelEvent(MouseWheelEvent e)

Listeners

• A listener is an object that waits for a specific event to occur and that responds to the event in some manner.

• Each listener has a relationship with an event or with a group of similar events.

• Listener objects must be carefully designed to respond to its type of events.

Example:Button:ActionEvent: Listener

Contd…

• The listener object must be set to respond to the event object generated by component.

• This is known as registering the listener object with the button object .

Creating Listener Objects

• A listener object is made by making a class implements a listener interface– E.g. In ButtonClick the ActionListener interface needs

to be implemented to receive the event from the button.• The code that is to receive the event object and

respond to the event is implemented in a method declared in the listener interface.

• register a listener object with a source by calling a particular method in the source object.

• E.g addActionListener() for the component object (JButton in this case).

Low Level Event Listeners

• Implement listener interface

• All event listener interfaces extend the interface java.util.EventListener.

Window Listener Interfaces

WindowFocusListenerInterface

WindowStateListenerInterface

• windowStateChanged(WindowEvent e)– Called when the window state changes—when

it is maximized or iconified, for example

The MouseListenerInterface

The MouseMotionListenerInterface

• mouseMoved(MouseEvent e)– Called when the mouse is moved within a

component

• mouseDragged(MouseEvent e)– Called when the mouse is moved within a

component while a mouse button is held down

The MouseWheelListenerInterface

• mouseWheelMoved(MouseWheelEvent e)– Called when the mouse wheel is rotated

The KeyListenerInterface

• keyTyped(KeyEvent e)

• keyPressed(KeyEvent e)

• keyReleased(KeyEvent e)

The FocusListenerInterface

• focusGained(FocusEvent e)– Called when a component gains the keyboard

focus

• focusLost(FocusEvent e)– Called when a component loses the keyboard

focus

Handling “Window Closing” event through WindowListener

1. Create a class which implements WindowListener Interface2. Create a window3. Set its bounds4. Set its flow layout5. Register event object with listener object6. Handle closing window event.

Exampleimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class B implements WindowListener{JFrame frame = new JFrame("HelloWorldSwing"); void createAndShowGUI() { frame.setBounds(50,50,400,300);

frame.addWindowListener(this); Container c=frame.getContentPane(); FlowLayout f=new FlowLayout(FlowLayout.LEFT,20,30);c.setLayout(f);for(int i=0;i<6;i++){c.add(new JButton("Button" + i));}JLabel label = new JLabel("Hello World");

c.add(label); frame.setVisible(true); }public void windowClosing(WindowEvent e) {

ExampleSystem.out.println(“Window In Closing Mode");frame.dispose(); // Release the window resources}public void windowOpened(WindowEvent e) {}public void windowClosed(WindowEvent e) {}public void windowIconified(WindowEvent e) {}public void windowDeiconified(WindowEvent e) {}public void windowActivated(WindowEvent e) {}public void windowDeactivated(WindowEvent e) {} public static void main(String[] args) { B b=new B();

b.createAndShowGUI();}}

Handling “Window Closing” & “MouseWheelMoved” events through

WindowListener,MouseWheelListerner Interfaces

1. Create a class which implements WindowListener & MouseWheelListener Interfaces

1. Create a window2. Set its bounds3. Set its flow layout4. Register event object with both listener objects5. Handle closing window event.6. Handle mouse wheel moved event.

Using Adapter Classes

• An adapter class is a term for a class that implements a listener interface with methods that have no content.

• The idea of this is to enable you to derive your own listener class from any of the adapter classes that are provided.

• Implement just the methods that you are interested in.

• The other empty methods will be inherited from the adapter class so you don’t have to worry about them.

Contd…

• Adapter classes defined in the java.awt.event

package that cover the methods in the other low-level listener interfaces;1. FocusAdapter

2. WindowAdapter

3. KeyAdapter

4. MouseAdapter

5. MouseMotionAdapter

6. MouseInputAdapter

Example: Handling Window Closing Event Through Adapter Classes

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class B1

{

JFrame frame = new JFrame("HelloWorldSwing");

void createAndShowGUI() {

frame.setBounds(50,50,400,300);

frame.addWindowListener(new WH());

Container c=frame.getContentPane();

FlowLayout f=new FlowLayout(FlowLayout.LEFT,20,30);

c.setLayout(f);

for(int i=0;i<6;i++){

c.add(new JButton("Button" + i));}

JLabel label = new JLabel("Hello World");

c.add(label);

frame.setVisible(true); }

class WH extends WindowAdapter{

public void windowClosing(WindowEvent e) {

System.out.println("Window In Closing Mode");

frame.dispose(); // Release the window resources

}}

public static void main(String[] args)

{ B1 b=new B1();

b.createAndShowGUI();}}

Semantic Events

• Semantic events relate to operations on the components in the GUI for your program.

• If you select a menu item or click a button, for example, a semantic event is generated.

Types Of Semantic Events

• An ActionEvent is generated when you perform an action on a component such as clicking on a menu item or a button.

• An ItemEvent occurs when a component is selected or deselected.

• An AdjustmentEvent is produced when an adjustable object, such as a scrollbar, is adjusted.

Semantic Event Listeners

Exampleimport javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.util.*;

class Selection implements ActionListener {

static JFrame frame = new JFrame("FrameDemo");

JButton pickButton = new JButton("Lucky Numbers!");

JButton colorButton = new JButton("Color");

class WH extends WindowAdapter{

public void windowClosing(WindowEvent e) {

System.out.println("Window In Closing Mode");

frame.dispose(); // Release the window resources}}

void Creat(){

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton pickButton = new JButton("Lucky Numbers!");

JButton colorButton = new JButton("Color");

pickButton.addActionListener(new Selection());

colorButton.addActionListener(new Selection());

frame.addWindowListener(new WH());

FlowLayout f=new FlowLayout();

Container c=frame.getContentPane();

c.setLayout(f);

c.add(pickButton);

c.add(colorButton);

frame.pack();

frame.setVisible(true);}

public void actionPerformed(ActionEvent e) {

//Object source = e.getSource();

//if(source == pickButton)

System.out.println(“Button Presses”);}

public static void main(String args[]){

Selection s=new Selection();

s.Creat();}}

ActionEvent Class

• ActionEvent(Object src, int type, String cmd)

• ActionEvent(Object src, int type, String cmd, int modifiers)

• ActionEvent(Object src, int type, String cmd, long when, int modifiers

• src is a reference to the object that generated this event.

• type specify the type of the event.• cmd specify command string. • modifiers indicates which modifier keys (ALT,

CTRL, META, and/or SHIFT) were pressed when the event was generated.

• when parameter specifies when the event occurred.

ActionEvent Class

• String getActionCommand( )

• int getModifiers( )

• long getWhen( )

ActionEvent Class Methods

• AdjustmentEvent (Adjustable src, int id, int type, int data)

1. src is a reference to the object that generated this event.

2. id equals ADJUSTMENT_VALUE_CHANGED.

3. type specifies the type of the event,

4. Data specifies associated data.

AdjustmentEvent Class

• The getAdjustable( ) method returns the object that generated the event.

Adjustable getAdjustable( )• The type of the adjustment event may be obtained by

the getAdjustmentType( ) method. It returns one of the constants defined by AdjustmentEvent.

int getAdjustmentType( )• The amount of the adjustment can be obtained from the

getValue( ) method, shown here:

int getValue( )

AdjustmentEvent Class Methods

• 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.

AdjustmentEvent Class

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

1. src is a reference to the component that generated this event. For example, this might be a list or choice element.

2. The type of the event is specified by type. 3. The specific item that generated the item event is

passed in entry. 4. The current state of that item is in state.

ItemEvent Class

• The getItem( ) method can be used to obtain a reference to the item that generated an event.

Object getItem( )

• The getStateChange( ) method returns the state change (i.e., SELECTED or DESELECTED) for the event.

int getStateChange( )

ItemEvent Class Methods

Adding a Toolbar

• JToolBar toolBar = new JToolBar();

• Frame.getContentPane().add(toolBar, BorderLayout.NORTH);

• toolBar.setFloatable(false);

Adding Button to ToolBar:

• JButton button = new JButton(openAction);

• ToolBar.add(button); // Add a toolbar button

Recommended