0% found this document useful (0 votes)
3 views30 pages

Java Lec 9 - Events

Uploaded by

Amgd Talal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views30 pages

Java Lec 9 - Events

Uploaded by

Amgd Talal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Making Java GUIs Functional

What is an Event?
◼ Change in the state of an object is known as event
◼ Event describes the change in state of source.
◼ Events are generated as result of user interaction
with the graphical user interface components.
◼ For example, the following activities cause events
to happen
❑ clicking on a button,
❑ moving the mouse,
❑ entering a character through keyboard,
❑ selecting an item from list,
❑ scrolling the page
2
Events

◼ Events are Component-specific.


◼ Events are objects that store information like
❑ the type of event that occurred,
❑ the source of the event,
❑ the time of an event to name a few.

3
Types of Event
◼ Foreground Events - Those events which require the
direct interaction of user.
❑ They are generated as consequences of a person interacting with
the graphical components in Graphical User Interface.
❑ For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling
the page etc.
◼ Background Events - Those events that don’t require
the interaction of end user are known as background
events.
❑ Examples of background events like: Operating system
interrupts, hardware or software failure, timer expires, an
operation completion.

4
Foreground Events

• Learned about GUI


Programming.
• Created two GUIs
– UppercaseConverter
– Calculator
• Now we will make
them work.

5
What is Event Handling?
◼ Event Handling is the mechanism that controls the
event and decides what should happen if an event
occurs.
◼ This mechanism have the code which is known as
event handler that is executed when an event
occurs.
◼ Java Uses the Event Delegation Model to handle
the events. This model defines the standard
mechanism to generate and handle the events.

6
Event Delegation Model

◼ Once the event is generated, then the event


is passed to other objects which handle or
react to the event, thus the term event
delegation.
◼ The objects which react to or handle the
events are called event listeners.

7
Three Players

◼ Event source which generates the event


object
◼ Event listener which receives the event object
and handles it
◼ Event object that describes the event

8
Why Event Delegation Model?
◼ The benefit of this approach is that the user
interface logic is completely separated from the logic
that generates the event.
◼ The user interface element is able to delegate the
processing of an event to the separate piece of
code.
◼ In this model, Listener needs to be registered with
the source object so that the listener can receive the
event notification.
◼ This is an efficient way of handling the event
because the event notifications are sent only to
those listener that want to receive them
9
Revisiting our GUI

• We have already
created a GUI.
• How many
components?
• What are some
possible events?

11
Example
• Click on UPPER
JButton
• Generates an Event
ActionEvent
• Event object is sent to
an ActionListener that is
registered with the
UPPER JButton public class Handler implements ActionListener
{
• ActionListener handles public void actionPerformed(ActionEvent e){
in actionPerformed System.out.println(“Handling ” + e);
}
method. }

12
Registering Listeners

◼ By having a class implement a listener


interface, it can contain code to handle an
event.
◼ However, unless an instance of the class is
registered with the component , the code will
never be executed. (Common beginner
error.)

13
Methods for Registering Listeners
◼ JButton
❑ addActionListener(ActionListener a)
❑ addChangeListener(ChangeListener c)
❑ addItemListener(ItemListener i)
❑ addMouseListener(MouseListener m)
❑ addMouseMotionListener(MouseMotionListener m)

◼ JList
❑ addListSelectionListener(ListSelectionListener l)

14
UpperCaseConverter Example

◼ Goal
❑ When UPPER button is pressed, the text in the
textfield will be converted to upper case and
appended into the text area.
❑ When CLEAR button is pressed, both the text field
and the text area will be cleared.
◼ Things to consider to accomplish goal
❑ What type of events do we need to respond to?
❑ What listener interfaces do we need to
implement?

15
Implementing an ActionListener

◼ Create as a separate class


❑ No access to data in JFrame
◼ Create as an inner class
❑ Access to JFrame data
❑ Must instantiate an object of this class to pass to
addActionListener method
◼ Make the JFrame implement the interface
❑ Access to JFrame data
❑ No need to instanciate an object of this class –
have the this reference
16
Implementing ActionListener
import java.awt.event.*;
public class UpperCaseConverter extends JFrame implements
ActionListener
{ //omitted code
upper = new JButton("UPPER");
clear = new JButton("CLEAR"); Good to test for expected
upper.addActionListener(this); interaction as you go
clear.addActionListener(this);
//omitted code
public void actionPerformed(ActionEvent e){
Object obj = e.getSource();
if(obj.equals(clear)) System.out.println("Clear");
else if(obj.equals(upper)) System.out.println("Upper");
}
}

17
Implement Desired Behavior
public void actionPerformed(ActionEvent e)
{
Object obj = e.getSource();
JButtons, JLabels,
if(obj.equals(clear)) { JTextFields and
input.setText(""); JTextAreas all
output.setText(""); have setText()
} method to change
else if(obj.equals(upper)) { their content
String result = input.getText();
String buffer = output.getText();
output.append(“\n” + result);
JTextAreas have
} append() method
} to add to their
content

18
Adding Functionality to the Calculator

◼ Need capability for telling the number to go to


the left or right TextField.
❑ If click and holding the ctrl button then number
goes to the left, else the right.
◼ Need to be able to perform operations.
❑ Use the operators themselves for the operations.
◼ Need to be able to clear fields.
❑ Convert the equal sign to a C for clear.

19
Add Listeners

plus.addActionListener(this);
minus.addActionListener(this);
mult.addActionListener(this);
div.addActionListener(this);
clears.addActionListener(this);
dot.addActionListener(this);
for(int i = 0; i < 10 ; i++)
numbers[i].addActionListener(this);

21
More ActionEvent Methods

public void
actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
System.out.println(command);
int modifiers = e.getModifiers();
if(modifiers == ActionEvent.CTRL_MASK)
System.out.println("CTRL PRESSED");
}

23
Problem

◼ Unfortunately, the code on the previous code


can not differentiate between a button click
with the control key down and a button click
alone.
◼ Next… try MouseListener interface.
❑ mousePressed
❑ mouseReleased
❑ mouseExited
❑ mouseClicked
❑ mouseEntered
24
Changing to a MouseListener
◼ Change all ActionListener references to MouseListener references
◼ Remove actionPerformed method and add:
public void mouseClicked(MouseEvent e){
int button = e.getButton(); Determines which
System.out.println(button); button was pressed,
String modifiers = right or left
e.getMouseModifiersText(e.getModifiers());
System.out.println(modifiers);
} States whether
public void mouseReleased(MouseEvent e){} the Ctrl, Alt or
public void mousePressed(MouseEvent e){} Shift buttons
were pressed
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}

25
Output
◼ 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

26
mouseClicked Method

◼ Need to use getSource method to determine


which button was pressed.
◼ Easiest way to differentiate is left click and
right click

◼ For operators doesn’t matter

27
Functional mouseClicked Method
public void mouseClicked(MouseEvent e){
int button = e.getButton(); JTextField dest = null;
if(button == 1) dest = operand1; //left click == left operand
if(button == 3) dest = operand2; //right click == right operand
Object src = e.getSource();
if(src == clears) clear(); //helper method
else if(src == mult||src == div||src == plus||src == minus)
performOperation(src); //helper method
else{
int i = 0;
for(; i < numbers.length; i++)
if(src == numbers[i]) break;
StringBuffer text = new StringBuffer(dest.getText());
if (src == dot) text.append(dot.getText());
else text.append(numbers[i].getText());
dest.setText(text.toString());
}
}

28
Helper Method
private void performOperation(Object src){
float f1 = 0;float f2 = 0;
try {
f1 = Float.parseFloat(operand1.getText());
f2 = Float.parseFloat(operand2.getText());
}catch (NumberFormatException e){
output.setText("Invalid Number Format");
}
try{
float ans = 0;
if(src == mult) ans = f1 * f2;
else if(src == plus) ans = f1 + f2;
else if(src == minus) ans = f1 - f2;
else if(src == div) ans = f1 / f2;
output.setText(Float.toString(ans));
} catch (Exception e) {
output.setText("Invalid Operation");
}
}

29
Adapter Classes

◼ In the previous implementation, we


implemented four empty methods.
◼ We can create a listener class that extends
its corresponding adapter class.
◼ Adapter classes provide the empty
implementation of all the methods in a
listener interface
◼ We only need to override the method(s)
whose behavior we want to influence.
30
Anonymous Inner Classes

◼ Adapter classes are often implemented as


anonymous inner classes.

mult.addListener(new MouseAdapter(){
public void mouseReleased(){
// specialized code just for mult
// that will only be executed when mouse is
// released on the ‘x’ JButton
}
});

31
A Few More Java Events

◼ FocusEvent – component gains or loses focus


◼ MouseEvent – mouse is moved, dragged, pressed,
released or clicked
◼ WindowEvent – window is iconified, deiconified,
opened or closed
◼ TextEvent – text is modified
◼ KeyEvent – key is pressed, depressed or both
◼ ContainerEvent – components are added or
removed from Container

32
Corresponding Listeners

◼ FocusEvent – FocusListener
◼ MouseEvent – MouseListener, MouseMotionListener
◼ WindowEvent – WindowStateListener,
WindowListener, WindowFocusListener
◼ TextEvent – TextListener
◼ KeyEvent – KeyListener
◼ ItemEvent- ItemListener
◼ ContainerEvent – ContainerListener

33

You might also like