presentation source

Download Report

Transcript presentation source

Chapter 6: Events in Java
• 1.0 Model
–
–
–
–
Event class
selecting component to handle
handleEvent method
helper methods (action, keyUp, mouseUp, etc.)
• 1.1 Model
– Listeners - connected to Event generatorsEvent
types: ActionEvent, ItemEvent, etc.
– corresponding Listeners: ActionListener, etc.
– connecting generator to listener
– Interfaces and Adapters
Abstract Classes
• Class may be abstract by adding modifier in
class header
public abstract class MyClass
• Resulting class cannot be instantiated
• Used to create general classes (Car) that you
expect to specialize
Interfaces
• A class may only inherit from one parent
• Sometimes want to create specialized class,
combines several capabilities
• Interface is a list of methods to instantiate
public interface Drawable {
public void draw() {} // empty body
}
• Class header, indicate implements interface
public class Rect extend GObj implements Drawable;
• must implement all methods of interface
• may have more than one interface
Event-Driven Programming
• Input “events” by the user caught by Java
– move mouse, click button, scroll window, type
key
• For each, Java creates an Event object
• Object added to queue, your program is
then expected to “handle” the events
1.0 Event Model
Event object:
instance vars:
Object target - which object generated the event
int id - a value indicating the type of event
Object arg - useful info about the event (dependent)
long when - time of event
int x - x location of event
int y - y location of event
int clickCount - number of times button clicked
int key - key pressed (for key events)
int modifiers - for key and mouse events
Event id Constants
ACTION_EVENT - Buttons, Checkboxes, Choices, Lists, MenuItems,
TextFields
KEY_PRESS, KEY_RELEASE, KEY_ACTION,
KEY_ACTION_RELEASE
MOUSE_DOWN, MOUSE_UP, MOUSE_DRAG, MOUSE_MOVE,
MOUSE_ENTER, MOUSE_EXIT - mouse
LIST_SELECT, LIST_DESELECT - List events
SCROLL_ABSOLUTE, SCROLL_LINE_UP, SCROLL_LINE_DOWN,
SCROLL_PAGE_UP, SCROLL_PAGE_DOWN
WINDOW_EXPOSE, WINDOW_ICONIFY, WINDOW_DEICONIFY,
WINDOW_DESTROY, WINDOW_MOVED
LOAD_FILE, SAVE_FILE
GOT_FOCUS, LOST_FOCUS
Handling Events
• Java does lots of stuff for you (keys in Text
objects, window moves, etc.)
• You add handling events for things you
want handled a particular way, or when no
obvious method (what to do when button
pushed)
Source of the Event
• Java sends event to Component it thinks is
responsible
• Component should
–
–
–
–
handle event and stop
pass event its parent class
say it can’t handle event (pass to parent in GUI)
handle event and pass on (rare)
• Java will automatically pass event to parent
in GUI hierarchy if not handled
– for Button, Comp (e.g. Panel) contains Button
Event-Handling Methods
• Every component has handleEvent method
public boolean handleEvent(Event e) {
if (e.id == Event.WINDOW_DESTROY) {
System.exit(0);
return true;
}}
• Return value indicates if handled
– true - event handled, terminate
– false - event not completely handled, try
someone else (parent in GUI hierarchy)
Passing On Events
• Sometimes we handle some events, want to
pass it on to others:
public boolean handleEvent(Event e) {
if (e.id == Event.WINDOW_DESTROY) { … }
else
return super.handleEvent(e);
}
• Give the next Component up in the class
hierarchy the chance to handle event
Helper Methods
• handleEvent rarely used
• Java provides “helper” methods specific to
particular types of events
–
–
–
–
–
can be implemented instead of handleEvent
called after handleEvent tried
action events - actions
key events - keyDown, keyUp
mouse events - mouseDown, mouseUp,
mouseDrag, mouseMove, mouseEnter,
mouseExit
action Method
• form:
public boolean action (Event e, Object arg) {}
• used for many widgets:
– Button
• e.target is button obj, arg is string name of button
– Checkbox
• e.target is Cb obj, arg is check value (true or false)
– Choice, List
• e.target is choice obj, arg is string of choice made
Helper Calling Parent
• As with handleEvent, if helper fails to
handle event, should call superclass action:
– return super.action(e,arg)
• Return values have same meaning as in
handleEvent
key Methods
• form:
public boolean keyUp (Event e, int key) {}
public boolean keyDown(Event e, int key) {}
• key is char pressed
– modifiers field indicates if Shift, Alt, Meta, or
Control held while pressed
– check with constants SHIFT_MASK,
META_MASK, CONTROL_MASK
(e.modifiers & Event.SHIFT_MASK) or e.shiftDown()
also has metaDown and controlDown, but none for Alt
– other keys (Functions like F1) use Action Key
events, Java has constants for such (Event.F1)
mouse Methods
• form:
public boolean method(Event e, int x, int y) {}
methods: mouseUp, mouseDown, mouseMove,
mouseDrag, mouseEnter, mouseExit
• x, y are locations of occurrence
–
–
–
–
modifiers used to indicate if left, right, center
no modifiers: left
meta set: right
alt set: center
import java.applet.*;
import java.awt.*;
public class TestAction extends Applet {
Button button = new Button("AButton");
Checkbox cbox1 = new Checkbox("CB1");
Checkbox cbox2 = new Checkbox("CB2");
CheckboxGroup cbg = new CheckboxGroup();
Choice choice = new Choice();
Panel panel = new Panel();
MyCanvas canvas = new MyCanvas();
public void init () {
panel.setLayout(new GridLayout(2,2));
cbox1.setCheckboxGroup(cbg);
cbox2.setCheckboxGroup(cbg);
choice.addItem("Item1");
choice.addItem("Item2");
choice.addItem("Item3");
panel.add(cbox1);
panel.add(cbox2);
panel.add(button);
panel.add(choice);
panel.layout();
setLayout(new GridLayout(2,1));
add(panel);
add(canvas);
}
}
public boolean action (Event e, Object arg) {
if (e.target == button) {
canvas.setMessage(arg + " pressed");
}
else if ((e.target == cbox1) || (e.target == cbox2)) {
Checkbox tempcb = (Checkbox) e.target;
canvas.setMessage(tempcb.getLabel() + " checked");
}
else if (e.target == choice) {
canvas.setMessage(arg + " chosen");
}
return true;
}
class MyCanvas extends Canvas {
private String theMessage = “”;
public MyCanvas() {
resize(500,40);
}
public void paint(Graphics g) {
g.drawString(theMessage,10,30);
}
}
public void setMessage(String s) {
theMessage = s;
repaint();
}
1.0 to the 1.1 Delegation Model
•
•
•
•
Event generators tend to be scattered in 1.0
Handlers often centralized
Difficult to write good general handlers
Idea: connect generators with appropriate
handlers
The Delegation Model (1.1)
• Any object can be a source of an Event
• Any object can listen for events
– implement (register) an appropriate listener
interface
– listeners stay close to generators
• Need to import java.awt.event.*
EventObject
AWTEvent
ComponentEvent
ActionEvent
ItemEvent
TextEvent
InputEvent
KeyEvent
MouseEvent
General methods
Object getSource() - generator of event, from EventObject
int getID() - constant for type of event (useful for some
Mouse or Key events) - from AWTEvent
Handling Events
• For different types of events we have
– an Event class (with useful methods)
– an EventListener interface with
• required methods that must be implemented as part
of listener
– after creating instance of class that can generate
events, connect to appropriate listener interface
• use addListenerType(Object generator) methods
Action Events
• click Button, double-click member in List,
select MenuItem, press <enter> in TextField
• ActionEvent methods:
– String getActionCommand() - string for source
• button - label
• list, menuitems - text of selected item
• textfield - content of textfield
– int getModifiers() - use to check if modifiers set
• Listener: ActionListener
– methods: void actionPerformed(ActionEvent e)
Item Events
• Select Checkbox, CheckboxMenuItem,
Choice item, or single-click List item
• ItemEvent methods:
– Object getItem() - item selected (usually String)
– int getStateChange() - returns value of state
• ItemEvent.SELECTED or ItemEvent.DESELECTED
– ItemSelectable getItemSelectable() - return
ItemSelectable object that generated event
• Listener: ItemListener
– methods: void itemStateChanged(ItemEvent e)
Input Events
• Abstract class for Key and Mouse Events
• Has constants for masks: ALT_MASK, etc.
• Also has boolean methods:
–
–
–
–
boolean isAltDown()
boolean isControlDown()
boolean isMetaDown()
boolean isShiftDown()
• Other method: int getModifiers()
Mouse Events
• MouseEvent, MouseMovedEvent methods:
–
–
–
–
int getX() - x location of mouse event
int getY() - y location of mouse event
Point getPoint() - x,y location
int getClickCount() - number of clicks
• Listeners:
– MouseListener - for click, press, enter, exits
• methods:
– void mouseClicked(MouseEvent e)
– mousePressed, mouseReleased, mouseEntered, mouseExited
– MouseMotionListener - for drag, move
• methods:
– void mouseMoved(MouseMovedEvent e)
– void mouseDragged(MouseMovedEvent e)
Key Events
• KeyEvent methods:
–
–
–
–
–
char getKeyChar() - char of key pressed
boolean isActionKey() - true if action key
int getKeyCode() - code for action keys
void setKeyChar(char c) - set char in event
void setKeyCode(int keyCode) - set keyCode
• Listener: KeyListener
– Methods:
• void keyPressed(KeyEvent e)
• void keyReleased(KeyEvent e)
• void keyTyped(KeyEvent e)
Text Events
• Changes to TextField or TextArea
• Listener: TextListener
– methods: void textValueChanged(TextEvent e)
Adapters
• To implement an interface you must
implement ALL methods of interface
– even if only an empty method
• Alternate solution: extend an Adapter
(interface with empty methods):
– MouseAdapter
– MouseMotionAdapter
– KeyAdapter
General Use of Listener
in declaring generator:
private Widget myWidget = new Widget();
private ApropListClass myListener;
in init or constructor:
myListener = new ApropListClass(myWidget);
myWidget.addApropListener(myListener)
new class:
class ApropListClass implements ApropListener {
private Widget copyWidget;
public ApropListClass(Widget w) {
copyWidget = w;
}
public void apropListenerMethod(Item e) {
// implement
}
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class TestAction extends Applet {
Button button = new Button("AButton");
private AButtonListener myButtonListener;
Checkbox cbox1 = new Checkbox("CB1");
private ACheckboxListener myCB1Listener;
Checkbox cbox2 = new Checkbox("CB2");
private ACheckboxListener myCB2Listener;
CheckboxGroup cbg = new CheckboxGroup();
Choice choice = new Choice();
private AChoiceListener myChoiceListener;
Panel panel = new Panel();
MyCanvas canvas = new MyCanvas();
public void init () {
myButtonListener = new AButtonListener(button,canvas);
button.addActionListener(myButtonListener);
myCB1Listener = new ACheckboxListener(cbox1,canvas);
cbox1.addItemListener(myCB1Listener);
myCB2Listener = new ACheckboxListener(cbox2,canvas);
cbox2.addItemListener(myCB2Listener);
myChoiceListener = new AChoiceListener(choice,canvas);
choice.addItemListener(myChoiceListener);
}
}
panel.setLayout(new GridLayout(2,2));
cbox1.setCheckboxGroup(cbg);
cbox2.setCheckboxGroup(cbg);
choice.addItem("Item1");
choice.addItem("Item2");
choice.addItem("Item3");
panel.add(cbox1);
panel.add(cbox2);
panel.add(button);
panel.add(choice);
panel.validate();
setLayout(new GridLayout(2,1));
add(panel);
add(canvas);
class AButtonListener implements ActionListener {
Button buttonCopy;
MyCanvas canvasCopy;
public AButtonListener(Button bcopy, MyCanvas ccopy) {
buttonCopy = bcopy;
canvasCopy = ccopy;
}
}
public void actionPerformed(ActionEvent e) {
canvasCopy.setMessage(buttonCopy.getLabel() + " pressed");
}
class ACheckboxListener implements ItemListener {
Checkbox checkboxCopy;
MyCanvas canvasCopy;
public ACheckboxListener(Checkbox cbcopy, MyCanvas ccopy) {
checkboxCopy = cbcopy;
canvasCopy = ccopy;
}
}
public void itemStateChanged(ItemEvent e) {
canvasCopy.setMessage(checkboxCopy.getLabel() + ” checked");
}
class AChoiceListener implements ItemListener {
Choice choiceCopy;
MyCanvas canvasCopy;
public AChoiceListener(Choice chcopy, MyCanvas ccopy) {
choiceCopy = chcopy;
canvasCopy = ccopy;
}
public void itemStateChanged(ItemEvent e) {
canvasCopy.setMessage(choiceCopy.getSelectedItem() + ”
chosen");
}
}
class MyCanvas extends Canvas {
private String theMessage = "";
public MyCanvas() {
setSize(500,40);
}
public void paint(Graphics g) {
g.drawString(theMessage,10,30);
}
public void setMessage(String s) {
theMessage = s;
repaint();
}
}