Lecture 12 Event Hadling Part 2
Lecture 12 Event Hadling Part 2
Lecture # 12
1
Course Books
Text Book:
Herbert Schildt, Java: The Complete Reference, McGraw-Hill
Education, Eleventh Edition
Craig Larman, Applying UML & patterns, 2 edition
Reference Books:
Cay S. Horstmann, Big Java: Early Objects, Wiley, 7th Edition
Herbert Schildt, Java: A Beginner's Guide, McGraw-Hill Education,
Eighth Edition
2
Course Instructors
Umm-e-Laila [email protected]
Assistant Professor, CED
Room Number: BS-04
Tel: 111-994-994, Ext. 536
3
Course Website
http://sites.google.com/site/ulaila206
4
Event-Driven Programming
Procedural programming is executed in
procedural order.
In event-driven programming, code is
executed upon activation of events.
5
Event Handling
Event-handling model
Three parts
Event source
GUI component with which user interacts
Event object
Encapsulates information about event that occurred
Event listener
Receives event object when notified, then responds
Programmer must perform two tasks
Register event listener for event source
Implement event-handling method (event handler)
6
Event listener interfaces
interface
«interface»
ActionListener
ActionListener
interface
«interface»
AdjustmentListener
AdjustmentListener
«interface»
interface
ComponentListener
ComponentListener
«interface»
interface
ContainerListener
ContainerListener
interface
«interface»
FocusListener
FocusListener
«interface»
interface «interface»
interface
EventListener ItemListener
EventListener ItemListener
«interface»
interface
KeyListener
KeyListener
interface
«interface»
MouseListener
MouseListener
interface
«interface»
MouseMotionListener
MouseMotionListener
interface
«interface»
TextListener
TextListener
«interface»
interface
WindowListener
WindowListener
7
Standard AWT Event Listeners
Listener Adapter class (if Registration
any) method
ActionListener addActionListener
AdjustmentListener addAdjustmentListen
er
ComponentListener ComponentAdapter addComponentListen
er
ContainerListener ContainerAdapter addContainerListener
FocusListener FocusAdapter addFocusListener
ItemListener addItemListener
KeyListener KeyAdapter addKeyListener
MouseListener MouseAdapter addMouseListener
MouseMotionListen MouseAdapter addMouseMotionListe
er ner
8
TextListener addTextListener
Event Source
9
Event Source
10
Some Events and Their
Associated Event Listeners
Act that Results in the Listener Type
Event
User clicks a button, presses Enter while ActionListener
typing in a text field, or chooses a menu
item
User closes a frame (main window) WindowListener
User presses a mouse button while the MouseListener
cursor is over a component
User moves the mouse over a MouseMotionListener
component
Component becomes visible ComponentListener
Component gets the keyboard focus FocusListener
Table or list selection changes ListSelectionListener
Any property in a component changes PropertyChangeListen
11
Standard AWT Event Listeners
ActionListener
Handles buttons and a few other actions
actionPerformed(ActionEvent event)
AdjustmentListener
Applies to scrolling
adjustmentValueChanged(AdjustmentEvent event)
ComponentListener
Handles moving/resizing/hiding GUI objects
componetResized(ComponentEvent event)
componentMoved(ComponentEvent event)
componentShown(ComponentEvent event)
componentHidden(ComponentEvent event)
12
Standard AWT Event Listeners
ContainerListener
Triggered when window adds/removes GUI controls
componentAdded(ContainerEvent event)
componentRemoved(ContainerEvent event)
FocusListener
Detects when controls get/lose keyboard focus
focusGained(FocusEvent event)
focusLost(FocusEvent event)
13
Standard AWT Event Listeners
ItemListener
Handles selections in lists, checkboxes, etc.
itemStateChanged(ItemEvent event)
KeyListener
Detects keyboard events
keyPressed(KeyEvent event) – any key pressed down
keyReleased(KeyEvent event) – any key released
keyTyped(KeyEvent event) – key for printable char
released
14
Standard AWT Event Listeners
MouseListener
Applies to basic mouse events
mouseEntered(MouseEvent event)
mouseExited(MouseEvent event)
mousePressed(MouseEvent event)
mouseReleased(MouseEvent event)
mouseClicked(MouseEvent event) – release without
drag
Applies on release if no movement since pressed
MouseMotionListener
Handles mouse movement
mouseMoved(MouseEvent event)
mouseDragged(MouseEvent event)
15
Standard AWT Event Listeners
TextListener
Applies to textfields and text areas
textValuedChanged(TextEvent event)
WindowListener
Handles high-level window events
windowOpened, windowClosing,
windowClosed, windowIconified,
windowDeiconified, windowActivated,
windowDeactivated
16
Handling ItemEvent
An instance of the ItemEvent class is passed to the ItemListener
whenever the item selected in a list control (such as a list box or
combo box) is changed. You can use this object to determine
information about the event such as which item the user selected.
Field Description
17
ItemListener
This interface deals with the Item events.
The Java ItemListener is notified whenever you click on
the checkbox,radiobutton
Following are the event handling methods available in
the ItemListener interface:
public void itemStateChanged(ItemEvent e)
18
Example ItemEvent
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
19
this.setLayout(new FlowLayout()); this.getContentPane().setBackground(new
Color(233,210,100));
setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500); this.add(this.cb_panel);
this.add(p); this.setVisible(true); }
public void itemStateChanged(ItemEvent ie) {
if(ie.getSource().getClass().getName().equals("javax.swing.JCheckBox")){
JCheckBox cb_temp = (JCheckBox) ie.getSource();
String item=cb_temp.getText() ;
if(ie.getSource().equals(cb[0])){
if (ie.getStateChange() == ItemEvent.SELECTED) {
item +=" is selected";
this.getContentPane().setBackground(Color.yellow);
} else if (ie.getStateChange() == ItemEvent.DESELECTED) {
this.getContentPane().setBackground(Color.CYAN);
item +=" is Deselected";
} } System.out.println(""+item);
tarea.append(item+"\n");
} } public static void main(String[] args) {
EventDemo o=new EventDemo();
}}
20
Handling Mouse Events
Java provides two listener interfaces,
MouseListener and MouseMotionListener, to
handle mouse events.
The MouseListener listens for actions such as when
the mouse is pressed, released, entered, exited, or
clicked.
The MouseMotionListener listens for
actions such as dragging or moving the
mouse.
21
There are five types of events that MouseListener can generate. There are
five abstract functions that represent these five events. The abstract
functions are :
void mouseReleased(MouseEvent e) : Mouse key is released
void mouseClicked(MouseEvent e) : Mouse key is pressed/released
void mouseExited(MouseEvent e) : Mouse exited the component
void mouseEntered(MouseEvent e) : Mouse entered the component
void mousepressed(MouseEvent e) : Mouse key is pressed
There are two types of events that MouseMotionListener can generate.
There are two abstract functions that represent these five events. The
abstract functions are :
void mouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in the
component and dragged. Events are passed until the user releases the mouse button.
void mouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from one point to
22
Method Description
Returns the absolute x, y position of
public Point getLocationOnScreen()
the MouseEvent.
Returns the x-coordinate of
public int getX() the MouseEvent.
23
Example
public class EventDemo extends JFrame implements MouseMotionListener,
MouseListener{
JLabel status;
EventDemo(){
status=new Jlabel();
this.setLayout(new FlowLayout());
this.getContentPane().setBackground(new Color(233,210,100));
setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500); this.add(status);
this.addMouseMotionListener(this);
this.addMouseListener(this);
this.setVisible(true);
}
public static void main(String[] args) {
EventDemo o=new EventDemo();
}
24
//Mouse Motion Events
@Override
public void mouseDragged(MouseEvent me) {
}
@Override
public void mouseMoved(MouseEvent me) {
int xValue = me.getX();
int yValue = me.getY();
status.setText(String.valueOf("X
value="+xValue+"yValue="+yValue));
repaint();
}
25
@Override
getButton()Determi
public void mouseClicked(MouseEvent me) { nes which button
status.setText("MouseClicked"); was pressed, right
or left
int button = me.getButton();
System.out.println(button);
Getmodifier()States
String modifiers = whether the Ctrl, Alt
me.getMouseModifiersText(me.getModifiers()); or Shift buttons
were pressed
System.out.println(modifiers); }
@Override
public void mousePressed(MouseEvent me) {
status.setText("Mouse Pressed"); }
@Override
public void mouseReleased(MouseEvent me) {
status.setText("Mouse released"); }
@Override
public void mouseEntered(MouseEvent me) {
status.setText("Mouse Entered"); }
@Override
public void mouseExited(MouseEvent me) {
status.setText("Mouse Exited"); }}
26
After a left click then
right click on a number
output is:
1
Button1
3
Meta+Button3
After left click then
right click on a number
with ctrl down output is:
1
Ctrl+Button1
3
Meta+Ctrl+Button3
27
Handling Keyboard Events
To process a keyboard event, use the following
handlers in the KeyListener interface:
keyPressed(KeyEvent e)
Called when a key is pressed.
keyReleased(KeyEvent e)
Called when a key is released.
keyTyped(KeyEvent e)
Called when a key is pressed and then
released.invoked when a Unicode character is
entered. If the key dosen’t has one (eg modifier key),
the keyTyped handler will not be invoked.
28
The KeyEvent Class
Methods:
getKeyChar() method Returns the character associated with the key
in this event. For example, the KEY_TYPED event for shift + "a" returns the
value for "A"
Keys:
Home VK_HOME
End VK_End
Page Up VK_PGUP
Page Down VK_PGDN
etc...
29
There are many other integer constants that are defined by
KeyEvent.
For example
VK_0 to VK_9
VK_A to VK_Z define the ASCII equivalents of the numbers and
letters.
Here are some others:
VK_ENTER, VK_ESCAPE, VK_CANCEL, VK_UP, VK_DOWN,
VK_LEFT, VK_RIGHT, VK_PAGE_DOWN,VK_PAGE_UP,
VK_SHIFT, VK_ALT, VK_CONTROL
The VK constants specify virtual key codes and are independent of
any modifiers, such as control, shift, or alt.
30
The KeyEvent Class, cont.
java.awt.event.InputEvent
java.awt.event.KeyEvent
+getKeyChar(): char Returns the character associated with the key in this event.
+getKeyCode(): int Returns the integer keyCode associated with the key in this event.
31
Example
public class EventDemo extends JFrame implements
KeyListener {
JLabel status; JTextField txt_name;
EventDemo(){
status=new JLabel();
// text field
txt_name=new JTextField(10);
txt_name.setEnabled(true);
txt_name.addKeyListener(this);
this.add(status);
this.add(txt_name);
this.setVisible(true);
32
@Override
public void keyTyped(KeyEvent ke) {
}
public void keyPressed(KeyEvent ke) {
}
@Override
public void keyReleased(KeyEvent ke) {
String charString,keyCodeString,modString;
char c=ke.getKeyChar();
int keyCode=ke.getKeyCode();
int modifiers=ke.getModifiers();
charString="Key character='"+c+“’”;
keyCodeString="key code="+keyCode+"("+KeyEvent.getKeyText(keyCo
modString="modifiers="+modifiers;
status.setText("Key released"+charString+keyCodeString+modString);
}}
33
Output
34
Handling Container Event
A low-level event which indicates that a
container's contents changed because a
component was added or removed
This class has following constants.
public static final int COMPONENT_ADDED
35
public ContainerEvent(Component source,
int id, Component child)
Constructs a ContainerEvent object.
Parameters: source - the Component object
(container) that originated the event
id - an integer indicating the type of event
child - the component that was added or removed
36
public Container getContainer()
Returns the originator of the event.
Returns: the Container object that originated the
event, or null if the object is not a Container.
public Component getChild()
Returns the component that was affected by the
event.
Returns: the Component object that was added or
removed.
37
Container Listener interface
The listener interface for receiving container
events.
void componentAdded(ContainerEvent e)
Invoked when a component has been added to the
container.
void componentRemoved (ContainerEvent e)
Invoked when a component has been removed from the
container.
38
Example
public class ContainerDemo extends JFrame implements
ContainerListener,ActionListener {
JComboBox cb_sub;
JPanel cb_panel;
JButton removeComp,addComp;
public ContainerDemo(){
cb_panel=new JPanel();
removeComp=new JButton("Remove");
removeComp.addActionListener(this);
addComp=new JButton("Add");
addComp.addActionListener(this);
// ComboBox
String c_data[]={" Choose your Sub","Chicken Tikka", "BBQ Chicken", "Peri Peri
Chicken"};
cb_sub=new JComboBox(c_data);
cb_sub.setSelectedIndex(0);
cb_panel.addContainerListener(this);
cb_panel.add(cb_sub);
39
this.setLayout(new FlowLayout());
this.getContentPane().setBackground(new Color(200,210,100));
setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
this.add(this.cb_panel);
this.add(removeComp);
this.add(addComp);
this.setVisible(true);
}
@Override
public void componentAdded(ContainerEvent ce) {
System.out.println("Componet added");
}
@Override
public void componentRemoved(ContainerEvent ce) {
System.out.println("Componet removed");
}
40
public static void main(String[] args) {
ContainerDemo o=new ContainerDemo();
}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==removeComp){
cb_panel.remove(cb_sub);}
else{
cb_panel.add(cb_sub);
}
repaint();
}
}
41
Output
42
FocusEvent class
A low-level event which indicates that a
Component has gained or lost the input
focus.
This class has following constants.
public static final int FOCUS_GAINED
This event indicates that the Component is now
the focus owner.
public static final int FOCUS_LOST
This event indicates that the Component is no
longer the focus owner.
43
Constructors
public FocusEvent(Component source,int
id,boolean temporary, Component opposite)
44
public FocusEvent(Component source,int
id,boolean temp orary)
id - an integer indicating the type of event
temporary - true if the focus change is temporary;
false otherwise.
public FocusEvent(Component source,int id)
source - the Component that originated the event
id - an integer indicating the type of event
45
Methods
46
FocusListener interface
void focusGained(FocusEvent e)
Invoked when a component gains the keyboard
focus.
void focusLost(FocusEvent e)
Invoked when a component loses the keyboard
focus.
47
Example
public class ContainerDemo extends JFrame implements
FocusListener, {
JComboBox cb_sub;
JPanel cb_panel;
JButton removeComp,addComp;
JTextField txt= new JTextField();
public ContainerDemo(){
//TextField
txt.setText("Demo for Focus event");
txt.addFocusListener(this);
this.setLayout(new FlowLayout());
this.getContentPane().setBackground(new Color(200,210,100));
this.setSize(500, 500);
this.add(txt);
this.setVisible(true);
} 48
@Override
public void focusGained(FocusEvent fe) {
System.out.println("Gain Focus"
+ (fe.isTemporary() ? " (temporary):" : ":")
+ fe.getComponent().getClass().getName()
+ "; Opposite component: "
+ (fe.getOppositeComponent() != null ?
fe.getOppositeComponent().getClass().getName()
: "null"));
}
@Override
public void focusLost(FocusEvent fe) {
}
}
49
Output
50
Handling Text Event
52
Text Listener
void textValueChanged(TextEvent e)
Invoked when the value of the text has
changed
53