1. om
JDK 1.1 AWT
Event Handling
.c
=====================
DF
aP
vi
n ee
w.
ww
Object Computing, Inc.
1 AWT Event Handling
2. om
AWT
.c
DF
• Abstract Windowing Toolkit package
– java.awt
aP
• Easier to learn than Motif/X and MFC
• Not as easy as using graphical GUI
vi
builders
– several companies are creating them for Java
ee
– will output Java code that uses the AWT package
• AWT classes fall in four categories
– components
n
– containers
w.
– layout managers
– event handling
ww
Object Computing, Inc.
2 AWT Event Handling
3. om
Steps To Use AWT
.c
• Create a container
– Frame, Dialog, Window, Panel, ScrollPane
DF
• Select a LayoutManager
– Flow, Border, Grid, GridBag, Card, none (null)
• Create components
aP
– Button, Checkbox, Choice, Label, List, TextArea,
TextField, PopupMenu
• Add components to container
vi
• Specify event handling (changed in 1.1)
ee
– listeners are objects interested in events
– sources are objects that “fire” events
– register listeners with sources
n
• component.add<EventType>Listener
– EventTypes are ActionEvent, AdjustmentEvent,
w.
ComponentEvent, FocusEvent, ItemEvent, KeyEvent,
MouseEvent, TextEvent, WindowEvent
– implement methods of listener interfaces
in listener classes
ww
• an event object is passed to the methods
• ActionListener, AdjustmentListener, ComponentListener,
FocusListener, ItemListener, KeyListener, MouseListener,
MouseMotionListener, TextListener, WindowListener
Object Computing, Inc.
3 AWT Event Handling
4. om
Event Sources,
.c
Listeners, and Objects
DF
Event Object
• describes an event
• ex. ActionEvent holds state of Shift key
tes
crea
aP
Event Source
vi
• generates events
• ex. Button
pas
ses
to
ee
list
ene
rm
eth
od
Event Listener
• any object can implement these interfaces
• ex. ActionListener has method actionPerformed()
n
w.
ww
Object Computing, Inc.
4 AWT Event Handling
5. om
Simple AWT
Example
.c
DF
import java.awt.*;
import java.awt.event.*;
private
private
aP
public class SimpleAWT extends java.applet.Applet
implements ActionListener, ItemListener {
Button button = new Button("Push Me!");
Checkbox checkbox = new Checkbox("Check Me!");
private Choice choice = new Choice();
vi
private Label label = new Label("Pick something!");
public void init() {
button.addActionListener(this);
ee
checkbox.addItemListener(this);
choice.addItemListener(this);
// An Applet is a Container because it extends Panel.
setLayout(new BorderLayout());
n
choice.addItem("Red");
w.
choice.addItem("Green");
choice.addItem("Blue");
Panel panel = new Panel();
panel.add(button);
ww
panel.add(checkbox);
panel.add(choice);
add(label, "Center");
add(panel, "South");
}
Object Computing, Inc.
5 AWT Event Handling
6. om
Simple AWT Example
.c
(Cont’d)
DF
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
label.setText("The Button was pushed.");
}
}
aP
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == checkbox) {
label.setText("The Checkbox is now " +
vi
checkbox.getState() + ".");
} else if (e.getSource() == choice) {
label.setText(choice.getSelectedItem() + “ was selected.”);
}
ee
}
}
n
w.
ww
Object Computing, Inc.
6 AWT Event Handling
7. om
Event Classes
.c
DF
• Hierarchy
java.util.EventObject
– java.awt.AWTEvent aP
• java.awt.event.ComponentEvent
– java.awt.event.FocusEvent
vi
– java.awt.event.InputEvent
• java.awt.event.KeyEvent
• java.awt.event.MouseEvent
ee
• java.awt.event.ActionEvent
• java.awt.event.AdjustmentEvent
• java.awt.event.ItemEvent
• java.awt.event.TextEvent
n
• Can create custom, non-AWT event
w.
classes
– extend java.util.EventObject
ww
Object Computing, Inc.
7 AWT Event Handling
8. om
Event Object Contents
.c
DF
• java.util.EventObject
– source holds a reference to the object that fired the event
– java.awt.AWTEvent
• id indicates event type
aP
– set to a constant in specific event classes
(listed on following pages)
• java.awt.event.ActionEvent
– modifiers indicates state of control, shift, and meta (alt)
vi
keys
– actionCommand holds the action specific command
string
ee
• usually the label of a Button or MenuItem
• java.awt.event.AdjustmentEvent
– for Scrollbars
used for
n
– value holds value
checkboxes and
– adjustmentType is unit +/-, block +/-, track radio buttons
w.
• java.awt.event.ItemEvent
– for Choice, List, Checkbox, and CheckboxMenuItem
– stateChange indicates selected or deselected
• java.awt.event.TextEvent
ww
– listeners are notified of every keystroke that changes the
value
– listeners are also notified when setText() is called
• other subclasses are on the following pages
Object Computing, Inc.
8 AWT Event Handling
9. om
Event Object Contents
.c
(Cont’ d)
DF
• java.awt.AWTEvent
– java.awt.event.ComponentEvent
aP
• id indicates moved, resized, shown, or hidden
• java.awt.event.ContainerEvent
– id indicates added or removed
– child holds a reference to the component added or
vi
removed
• java.awt.event.FocusEvent
– id indicates gained or lost
ee
– temporary indicates temporary or permanent
(see documentation in source)
• java.awt.event.WindowEvent
n
– id indicates opened, closing, closed, iconified, deiconified,
activated, and deactivated
w.
brought to front
ww
Object Computing, Inc.
9 AWT Event Handling
10. om
Event Object Contents
.c
(Cont’ d)
DF
• java.awt.AWTEvent
– java.awt.event.InputEvent
aP
• modifiers is a mask that holds
– state of control, shift, and meta (alt) keys
– state of mouse buttons 1, 2, & 3
• when holds time the event occurred
vi
– probably should have been put in java.util.EventObject!
• java.awt.event.KeyEvent
ee
– id indicates typed, pressed, or released
– keyChar holds the ascii code of the key pressed
– keyCode holds a constant identifying the key pressed
(needed for non-printable keys)
n
• java.awt.event.MouseEvent
– id indicates clicked, pressed, released, moved, entered,
w.
exited, or dragged
– clickCount holds # of times button was clicked
– x,y hold location of mouse cursor
ww
Object Computing, Inc.
10 AWT Event Handling
11. om
Event Listener Interfaces
.c
• Class hierarchy and methods
DF
– java.util.EventListener
• java.awt.event.ActionListener
– actionPerformed
• java.awt.event.AdjustmentListener
aP
– adjustmentValueChanged
• java.awt.event.ComponentListener
– componentHidden, componentMoved, componentResized,
componentShown
• java.awt.event.FocusListener
vi
– focusGained, focusLost
• java.awt.event.ItemListener
ee
– itemStateChanged
• java.awt.event.KeyListener
– keyPressed, keyReleased, keyTyped
• java.awt.event.MouseListener
n
– mouseEntered, mouseExited,
mousePressed, mouseReleased, mouseClicked
w.
• java.awt.event.MouseMotionListener
– mouseDragged, mouseMoved
• java.awt.event.TextListener
– textValueChanged
ww
• java.awt.event.WindowListener
– windowOpened, windowClosing, windowClosed,
windowActivated, windowDeactivated, windowIconified,
windowDeiconified
Object Computing, Inc.
11 AWT Event Handling
12. om
Event Sources and
.c
Their Listeners
DF
• Component (ALL components extend this)
– ComponentListener, FocusListener, KeyListener,
• Dialog - WindowListener
aP
MouseListener, MouseMotionListener
• Frame - WindowListener
vi
• Button - ActionListener
ee
• Choice - ItemListener
• Checkbox - ItemListener
n
• CheckboxMenuItem - ItemListener
w.
• List - ItemListener, ActionListener when an item is
double-clicked
• MenuItem - ActionListener
ww
• Scrollbar - AdjustmentListener
• TextField - ActionListener, TextListener
• TextArea - TextListener
Object Computing, Inc.
12 AWT Event Handling
13. om
Listener Adapter Classes
.c
DF
• Provide empty default implementations of
methods in listener interfaces with more
than one method
• They include
aP
vi
– java.awt.event.ComponentAdapter
– java.awt.event.FocusAdapter
ee
– java.awt.event.KeyAdapter
– java.awt.event.MouseAdapter
– java.awt.event.MouseMotionAdapter
n
– java.awt.event.WindowAdapter
• To use, extend from them
w.
– override methods of interest
– usefulness is limited by single inheritance
ww
• can’ do if another class is already being extended
t
• implementation for methods that are not of interest could look
like this
public void windowIconified(WindowEvent e) {}
Object Computing, Inc.
13 AWT Event Handling
14. om
Design For Flexibility
.c
and Maintainability
DF
invokes app. methods Event
App
Handlers
• Can separate
rs
ne
pa ates
d
nts liste
cre
sse GU
co rs h re an
– application code
ss
of iste App dlers
t e as
aP elf I
mp an f.,
en rs
n
an
on dle
ve
sse ha
d
– GUI code
pa ates
reg s
cre
GUI
– event handling code
• Steps to achieve this separation
vi
– create a single class whose constructor creates the
entire GUI, possibly using other GUI-only classes
ee
– create the GUI by invoking this constructor from an
application class
– create classes whose only function is to be notified of
n
GUI events and invoke application methods
• their constructors should accept references to application
w.
objects whose methods they will invoke
– create event handling objects in a GUI class and
register them with the components whose events they
ww
will handle
Object Computing, Inc.
14 AWT Event Handling
15. om
AWT Example
.c
DF
aP
vi
• FontTest allows specification of text to be
displayed, font name, style, color and size
ee
• It illustrates
• creation of GUI components
n
• use of the Canvas and PopupMenu
w.
• component layout using BorderLayout,
FlowLayout, and GridLayout
• event handling
ww
• Invoke with
<APPLET CODE=FontTest.class WIDTH=580 HEIGHT=250>
</APPLET>
Object Computing, Inc.
15 AWT Event Handling
16. om
FontTest.java
.c
DF
import java.awt.*;
import java.awt.event.*;
import java.util.Enumeration;
import COM.ociweb.awt.ColorMap;
aP
public class FontTest extends java.applet.Applet
implements ActionListener, AdjustmentListener, ItemListener, MouseListener {
static final String DEFAULT_FONT = "Helvetica";
static final String DEFAULT_TEXT = "FontTest";
vi
static final int DEFAULT_SIZE = 24;
private static final int BOX_SIZE = 3;
private static final int MIN_SIZE = 6;
ee
private static final int MAX_SIZE = 250;
private CheckboxGroup styleGroup = new CheckboxGroup();
private Checkbox boldRadio = new Checkbox("Bold", false, styleGroup);
private Checkbox bothRadio = new Checkbox("Both", false, styleGroup);
n
private Checkbox italicRadio =
new Checkbox("Italic", false, styleGroup);
w.
private Checkbox plainRadio = new Checkbox("Plain", true, styleGroup);
private Choice fontChoice = new Choice();
private List colorList = new List(4, false);
private MyCanvas myCanvas = new MyCanvas();
private PopupMenu popup = new PopupMenu("Font");
ww
private Scrollbar scrollbar =
new Scrollbar(Scrollbar.HORIZONTAL, DEFAULT_SIZE, BOX_SIZE,
MIN_SIZE, MAX_SIZE + BOX_SIZE);
private TextField sizeField =
new TextField(String.valueOf(DEFAULT_SIZE), 3);
private TextField textField = new TextField(DEFAULT_TEXT, 40);
Object Computing, Inc.
16 AWT Event Handling
17. om
FontTest.java (Cont’d)
.c
DF
public void init() {
fontChoice.addItem("TimesRoman");
fontChoice.addItem("Helvetica");
fontChoice.addItem("Courier");
aP
fontChoice.select(DEFAULT_FONT);
Panel fontPanel = new Panel();
fontPanel.add(new Label("Font:"));
fontPanel.add(fontChoice);
vi
Panel stylePanel = new Panel();
stylePanel.add(plainRadio);
stylePanel.add(boldRadio);
stylePanel.add(italicRadio);
ee
stylePanel.add(bothRadio);
Enumeration e = ColorMap.getColorNames();
while (e.hasMoreElements()) {
colorList.addItem((String) e.nextElement());
n
}
colorList.select(0);
w.
Panel sizePanel = new Panel();
sizePanel.add
(new Label("Size (" + MIN_SIZE + "-" + MAX_SIZE + ")"));
sizePanel.add(sizeField);
ww
Panel westPanel = new Panel(new GridLayout(0, 1));
westPanel.add(fontPanel);
unknown # of rows,
westPanel.add(stylePanel);
one column
westPanel.add(colorList);
westPanel.add(sizePanel);
Object Computing, Inc.
17 AWT Event Handling
18. om
FontTest.java (Cont’d)
.c
DF
setLayout(new BorderLayout());
add(myCanvas, "Center");
add(westPanel, "West");
aP
add(textField, "North");
add(scrollbar, "South");
fontChoice.addItemListener(this);
plainRadio.addItemListener(this);
boldRadio.addItemListener(this);
vi
italicRadio.addItemListener(this);
bothRadio.addItemListener(this);
colorList.addItemListener(this);
sizeField.addActionListener(this);
ee
textField.addActionListener(this);
scrollbar.addAdjustmentListener(this);
fontPanel.addMouseListener(this);
stylePanel.addMouseListener(this);
sizePanel.addMouseListener(this);
n
myCanvas.addMouseListener(this);
MenuItem timesRomanItem = new MenuItem("TimesRoman");
w.
MenuItem helveticaItem = new MenuItem("Helvetica");
MenuItem courierItem = new MenuItem("Courier");
timesRomanItem.addActionListener(this);
helveticaItem.addActionListener(this);
ww
courierItem.addActionListener(this);
popup.add(timesRomanItem);
popup.add(helveticaItem);
popup.add(courierItem);
add(popup);
}
Object Computing, Inc.
18 AWT Event Handling
19. om
FontTest.java (Cont’d)
.c
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == textField) {
myCanvas.setText(textField.getText());
DF
} else if (source == sizeField) {
int size = Integer.parseInt(sizeField.getText());
scrollbar.setValue(size);
setFont();
} else if (source instanceof MenuItem) {
MenuItem menuItem = (MenuItem) source;
}
}
setFont();
aP
if (menuItem.getParent() == popup) {
fontChoice.select(e.getActionCommand());
}
vi
public void adjustmentValueChanged(AdjustmentEvent e) {
if (e.getSource() == scrollbar) {
ee
sizeField.setText(String.valueOf(scrollbar.getValue()));
setFont();
}
}
public void itemStateChanged(ItemEvent e) {
n
Object source = e.getSource();
if (source == fontChoice) {
w.
setFont();
} else if (source instanceof Checkbox) {
Checkbox checkbox = (Checkbox) source;
if (checkbox.getCheckboxGroup() == styleGroup) {
setFont();
ww
}
} else if (source == colorList) {
Color color = ColorMap.getColor(colorList.getSelectedItem());
myCanvas.setColor(color);
}
}
Object Computing, Inc.
19 AWT Event Handling
20. om
FontTest.java (Cont’d)
.c
DF
// MouseListener methods that need no action.
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
aP
public void mouseReleased(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
}
popup.show((Component) e.getSource(), e.getX(), e.getY());
vi
private void setFont() {
int style = Font.PLAIN;
Checkbox styleRadio = styleGroup.getSelectedCheckbox();
ee
if (styleRadio == plainRadio) {
style = Font.PLAIN;
} else if (styleRadio == boldRadio) {
style = Font.BOLD;
} else if (styleRadio == italicRadio) {
n
style = Font.ITALIC;
} else if (styleRadio == bothRadio) {
w.
style = Font.BOLD + Font.ITALIC;
}
Font font =
new Font(fontChoice.getSelectedItem(),
ww
style,
Integer.parseInt(sizeField.getText()));
myCanvas.setFont(font);
}
}
Object Computing, Inc.
20 AWT Event Handling
21. om
FontTest.java (Cont’d)
.c
DF
class MyCanvas extends Canvas {
private Color color = Color.black;
private Font font =
new Font(FontTest.DEFAULT_FONT,
Font.PLAIN,
aP
FontTest.DEFAULT_SIZE);
private String text = FontTest.DEFAULT_TEXT;
public void setColor(Color color) {
vi
this.color = color;
repaint();
}
ee
public void setFont(Font font) {
this.font = font;
repaint();
}
n
public void setText(String text) {
this.text = text;
repaint();
w.
}
public void paint(Graphics g) {
g.setColor(color);
g.setFont(font);
ww
g.drawString(text, 10, 200);
}
}
Object Computing, Inc.
21 AWT Event Handling
22. om
ColorMap.java
.c
DF
package COM.ociweb.awt;
import java.awt.Color;
import java.util.Enumeration;
import java.util.Hashtable;
public class ColorMap {
aP
private static Hashtable hashtable = new Hashtable();
static {
vi
hashtable.put("White", Color.white);
hashtable.put("Gray", Color.gray);
hashtable.put("DarkGray", Color.darkGray);
hashtable.put("Black", Color.black);
ee
hashtable.put("Red", Color.red);
hashtable.put("Pink", Color.pink);
hashtable.put("Orange", Color.orange);
hashtable.put("Yellow", Color.yellow);
hashtable.put("Green", Color.green);
n
hashtable.put("Magenta", Color.magenta);
hashtable.put("Cyan", Color.cyan);
hashtable.put("Blue", Color.blue);
w.
}
public static Color getColor(String name) {
return (Color) hashtable.get(name);
ww
}
public static Enumeration getColorNames() {
return hashtable.keys();
}
}
Object Computing, Inc.
22 AWT Event Handling
23. om
Appendix A
.c
DF
JDK 1.0
AWT aP
Event Handling
vi
n ee
w.
ww
Object Computing, Inc.
23 AWT Event Handling
24. om
1.0 Default Event Handling
.c
(delegation-based event handling was added in Java 1.1)
DF
• Provided by Component class
• handleEvent(Event evt)
aP
– first method invoked when an event occurs
– default implementation tests for specific types of
events and invokes the methods below
vi
• Methods to handle specific types of events
– default implementations do nothing
ee
– they are
• mouseDown and mouseUp
• mouseDrag and mouseMove
• mouseEnter and mouseExit
n
• keyDown and keyUp
• gotFocus and lostFocus
w.
– from mouse click, tab key, or requestFocus method
• action (discussed two slides ahead)
• All event handling methods return boolean
ww
– indicates whether they handled the event
– if false, the event is handled recursively by
containers
Object Computing, Inc.
24 AWT Event Handling
25. om
Overriding 1.0 Default
Event Handling
.c
• Custom event handling methods other than
DF
handleEvent
– created by overriding implementations in Component
which do nothing
aP
– invoked by the default handleEvent implementation
• Custom handleEvent method
vi
– created by overriding implementation in Component
– can handle all events by comparing id field to
constants in Event class to see what kind of event
ee
occurred
– if overridden, other event handling methods will not
be invoked unless
n
• they are invoked directly from this method
– not recommended approach
w.
• this method invokes the handleEvent method of a superclass
– recommended approach
– do this if the event is not one you wish to handle in your
ww
handleEvent method
– invoke with “return super.handleEvent(e); ”
– first superclass to implement handleEvent is typically
Component which disperses the event to methods which
handle specific types of events
Object Computing, Inc.
25 AWT Event Handling
26. om
1.0 Action Events
.c
• Most user interface components generate
“action” events
DF
– Label and TextArea don’ generate any events
t
– List and Scrollbar generate events that are not
“action” events
• must be handled in a handleEvent method,
aP
not an action method
• Default handleEvent invokes
public boolean action(Event evt, Object what)
vi
• Second argument varies based on the
component
ee
– Button
• String representing button label
– Checkbox (and radiobutton)
n
• Boolean state (true for on, false for off)
• generated when picked
w.
– Choice (option menu)
• String representing selected item
– TextField
ww
• null
• generated when user presses return key
• not when field is exited with mouse or tab key
– use lostFocus method to catch that
Object Computing, Inc.
26 AWT Event Handling
27. ww
Java Tutorial Extending Classes and Interfaces
Inheritance in Java
java-06.fm
w.
Inheritance is a compile-time mechanism in Java that allows you to extend a class (called the base
class or superclass) with another class (called the derived class or subclass). In Java,
ne
inheritance is used for two purposes:
1. class inheritance - create a new class as an extension of another class, primarily for the purpose
of code reuse. That is, the derived class inherits the public methods and public data of the
inheritance.
ev
base class. Java only allows a class to have one immediate base class, i.e., single class
2. interface inheritance - create a new class to implement the methods defined as part of an
ia
interface for the purpose of subtyping. That is a class that implements an interface “conforms
to” (or is constrained by the type of) the interface. Java supports multiple interface inheritance.
PD
In Java, these two kinds of inheritance are made distinct by using different language syntax. For
class inheritance, Java uses the keyword extends and for interface inheritance Java uses the
keyword implements.
public class derived-class-name extends base-class-name {
// derived class methods extend and possibly override
F.
co
// those of the base class
}
public class class-name implements interface-name {
}
// class provides an implementation for the methods
// as specified by the interface
m
Greg Lavender Slide 1 of 12 6/15/99
28. ww
Java Tutorial Extending Classes and Interfaces
Example of class inhertiance
java-06.fm
w.
package MyPackage;
ne
class Base {
private int x;
public int f() { ... }
ev
protected int g() { ... }
}
class Derived extends Base {
private int y;
ia
public int f() { /* new implementation for Base.f() */ }
PD
public void h() { y = g(); ... }
}
In Java, the protected access qualifier means that the protected item (field or method) is visible to a
F.
any derived class of the base class containing the protected item. It also means that the protected
item is visible to methods of other classes in the same package. This is different from C++.
co
Q: What is the base class of class Object? I.e., what would you expect to get if you executed the
following code?
Object x = new Object();
System.out.println(x.getClass().getSuperclass());
m
Greg Lavender Slide 2 of 12 6/15/99
29. ww
Java Tutorial Extending Classes and Interfaces
Order of Construction under Inheritance
java-06.fm
w.
Note that when you construct an object, the default base class constructor is called implicitly, before
the body of the derived class constructor is executed. So, objects are constructed top-down under
ne
inheritance. Since every object inherits from the Object class, the Object() constructor is always
called implicitly. However, you can call a superclass constructor explicitly using the builtin super
keyword, as long as it is the first statement in a constructor.
ev
For example, most Java exception objects inherit from the java.lang.Exception class. If you wrote
your own exception class, say SomeException, you might write it as follows:
ia
public class SomeException extends Exception {
public SomeException() {
}
public SomeException(String s) {
PD
super(); // calls Exception(), which ultimately calls Object()
}
F.
super(s); // calls Exception(String), to pass argument to base class
public SomeException (int error_code) {
this("error”); // class constructor above, which calls super(s)
System.err.println(error_code); co
}
}
m
Greg Lavender Slide 3 of 12 6/15/99
30. ww
Java Tutorial Extending Classes and Interfaces
Abstract Base Classes
java-06.fm
w.
An abstract class is a class that leaves one or more method implementations unspecified by
declaring one or more methods abstract. An abstract method has no body (i.e., no implementation). A
ne
subclass is required to override the abstract method and provide an implementation. Hence, an
abstract class is incomplete and cannot be instantiated, but can be used as a base class.
abstract public class abstract-base-class-name {
ev
// abstract class has at least one abstract method
public abstract return-type abstract-method-name ( formal-params );
ia
... // other abstract methods, object methods, class methods
PD
}
public class derived-class-name extends abstract-base-class-name {
public return-type abstract-method-name (formal-params) { stmt-list; }
... // other method implementations
F.
co
}
It would be an error to try to instantiate an object of an abstract type:
abstract-class-name obj = new abstract-class-name();
That is, operator new is invalid when applied to an abstract class.
// ERROR!
m
Greg Lavender Slide 4 of 12 6/15/99
31. ww
Java Tutorial Extending Classes and Interfaces
Example abstract class usage
java-06.fm
w.
abstract class Point {
private int x, y;
ne
public Point(int x, int y) { this.x = x; this.y = y; }
public void move(int dx, int dy)
{ x += dx; y += dy; plot(); }
ev
public abstract void plot(); // has no implementation
}
abstract class ColoredPoint extends Point {
private int color;
ia
protected public ColoredPoint(int x, int y, int color)
PD
{ super(x, y); this.color = color; }
}
class SimpleColoredPoint extends ColoredPoint {
F.
public SimpleColoredPoint(int x, int y, int color) { super(x,y,color); }
public void plot() { ... } // code to plot a SimpleColoredPoint
}
co
Since ColoredPoint does not provide an implementation of the plot method, it must be declared
abstract. The SimpleColoredPoint class does implement the inherited plot method. It would be an
error to try to instantiate a Point object or a ColoredPoint object. However, you can declare a Point
m
reference and initialize it with an instance of a subclass object that implements the plot method:
Point p = new SimpleColoredPoint(a, b, red); p.plot();
Greg Lavender Slide 5 of 12 6/15/99
32. ww
Java Tutorial Extending Classes and Interfaces
Interfaces
java-06.fm
w.
An abstract class mixes the idea of mutable data in the form of instance variables, non-abstract
methods, and abstract methods. An abstract class with only static final instance variables and all
ne
abstract methods is called an interface. An interface is a specification, or contract, for a set of
methods that a class that implements the interface must conform to in terms of the type signature of
the methods. The class that implements the interface provides an implementation for each method,
just as with an abstract method in an abstract class.
ev
So, you can think of an interface as an abstract class with all abstract methods. The interface itself
can have either public, package, private or protected access defined. All methods declared in an
ia
interface are implicitly abstract and implicitly public. It is not necessary, and in fact considered
redundant to declare a method in an interface to be abstract.
an interface, then they are implicitly defined to be:
• public.
PD
You can define data in an interface, but it is less common to do so. If there are data fields defined in
• static, and
• final
F.
In other words, any data defined in an interface are treated as public constants.
co
m
Note that a class and an interface in the same package cannot share the same name.
Methods declared in an interace cannot be declared final. Why?
Greg Lavender Slide 6 of 12 6/15/99
33. ww
Java Tutorial Extending Classes and Interfaces
Interface declaration
java-06.fm
w.
Interface names and class names in the same package must be distinct.
ne
public interface interface-name {
// if any data are defined, they must be constants
public static final type-name var-name = constant-expr;
ev
// one or more implicitly abstract and public methods
return-type method-name ( formal-params );
ia
}
An interface declaraion is nothing more than a specification to which some class that purports to
PD
implement the interface must conform to in its implementation. That is, a class the implements the
interface must have defined implementations for each of the interface methods.
The major reason for interfaces being distinct elements in Java is that you often want to define some
F.
operation to operate on objects that all conform to the same interface. So, you can define some code in
a very general way, with a guarantee that by only using the methods defined in the interface, that all
co
objects that implement the interface will have defined implementations for all the methods.
For example, you might define a Shape interface that defines an area() method, and so you would
expect that any class that implements the Shape interface, would define an area method. So, if I
m
have a list of references to objects that implement the Shape interface, I can legitimately invoke the
area method, abstractly, on each of these objects and expect to obtain as a result a value that
represents the area of some shape.
Greg Lavender Slide 7 of 12 6/15/99
34. ww
Java Tutorial Extending Classes and Interfaces
Separation of Interface from Implementations
java-06.fm
w.
Interfaces are specifications for many possible implementations. Interfaces are used to define a
contract for how you interact with an object, independent of the underlying implementation. The
ne
objective of an object-oriented programmer is to separate the specification of the interface from the
hidden details of the implementation.
Consider the specification of a common LIFO stack.
public interface StackInterface {
boolean empty(); ev
ia
void push(Object x);
Object pop() throws EmptyStackException;
Object peek() throws EmptyStackException;
}
PD
Note that the methods in this interface are defined to operate on objects of type Object. Since a stack
is a “container type”, it is very common to use the base class for all objects, namely Object, as the
F.
type of the arguments and results to a container type. Since all objects ultimately inherit from class
Object, we can always generically refer to any object in the system using an Object reference.
co
However, when we pop from a stack, we have to explicitly type case from the very general type
Object to a concrete type, so that we can manipulate the object concretely.
Q: How many different ways are there to implement a stack? If we are using just using a Stack object
m
(as opposed to implementing it ourselves) should we care?
Greg Lavender Slide 8 of 12 6/15/99
35. ww
Java Tutorial Extending Classes and Interfaces
Stack implementation of the StackInterface
java-06.fm
w.
public class Stack implements StackInterface {
ne
private Vector v = new Vector(); // use java.util.Vector class
ev
public boolean empty() { return v.size() == 0; }
public void push(Object item) { v.addElement(item); }
public Object pop() {
Object obj = peek();
ia
PD
v.removeElementAt(v.size() - 1);
return obj;
}
F.
public Object peek() throws EmptyStackException {
if (v.size() == 0)
throw new EmptyStackException();
co
return v.elementAt(v.size() - 1);
}
}
m
Greg Lavender Slide 9 of 12 6/15/99
36. ww
Java Tutorial Extending Classes and Interfaces
Should a stack use or inherit from a vector?
java-06.fm
w.
The java.util.Stack class is defined as a subclass of the java.util.Vector class, rather than using a
Vector object as in the previous example. This sort of inheritance is not subtype inheritance, because
ne
the interface of a Stack object can be violated because a Vector has a “wider” interface than a Stack,
i.e., a vector allows insertion into the front and the rear, so it is possible to violate the stack contract
by treating a stack object as a vector, and violating the LIFO specification of a stack.
public class Stack extends Vector {
ev
public Object push(Object item) {addElement(item); return item;}
public Object pop() {
ia
Object obj;
int len = size();
PD
obj = peek();
removeElementAt(len - 1);
return obj;
}
public Object peek() {
int len = size();
if (len == 0) throw new EmptyStackException();
F.
co
return elementAt(len - 1);
}
public boolean empty() { return size() == 0;}
}
Vector v = new Stack(); // legal - base class reference to subclass object
v.insertElementAt(x, 2); // insert object x into Vector slot 2!! m
Greg Lavender Slide 10 of 12 6/15/99
37. ww
Java Tutorial Extending Classes and Interfaces
When to use an Interface vs when to use an abstract class
java-06.fm
w.
Having reviewed their basic properties, there are two primary differences between interfaces and
abstract classes:
ne
• an abstract class can have a mix of abstract and non-abstract methods, so some default
implementations can be defined in the abstract base class. An abstract class can also have static
methods, static data, private and protected methods, etc. In other words, a class is a class, so it
ev
can contain features inherent to a class. The downside to an abstract base class, is that since their
is only single inheritance in Java, you can only inherit from one class.
• an interface has a very restricted use, namely, to declare a set of public abstract method
ia
singatures that a subclass is required to implement. An interfaces defines a set of type
constraints, in the form of type signatures, that impose a requirement on a subclass to implement
the methods of the interface. Since you can inherit multiple interfaces, they are often a very
PD
useful mechanism to allow a class to have different behaviors in different situations of usage by
implementing multiple interfaces.
F.
It is usually a good idea to implement an interface when you need to define methods that are to be
explicitly overridden by some subclass. If you then want some of the methods implemented with
co
default implementations that will be inherited by a subclass, then create an implementation class
for the interface, and have other class inherit (extend) that class, or just use an abstract base class
instead of an interface.
m
Greg Lavender Slide 11 of 12 6/15/99
38. ww
Java Tutorial Extending Classes and Interfaces
Example of default interface implementations
java-06.fm
interface X {
void f(); w.
ne
int g();
}
ev
class XImpl implements X {
void g() { return -1; } // default implementation for g()
}
class Y extends XImpl implements X {
void f() { ... } // provide implementation for f()
ia
PD
}
Note that when you invoke an abtract method using a reference of the type of an abstract class or an
interface, the method call is dynamically dispatched.
X x = new Y();
x.f();
F.
co
The call x.f() causes a run-time determination of the actual type of object that ‘x’ refers to, then a
method lookup to determine which implementation of f() to invoke. In this case, Y.f(x) is called, but
the type of x is first converted to Y so that the ‘this’ reference is initialized to a reference of type Y
inside of f(), since the implicit type signature of Y.f() is really Y.f(final Y this);
m
Greg Lavender Slide 12 of 12 6/15/99
40. DF
Agenda
aP
● What is an array
vi
● Declaration of an array
ee
● Instantiation of an array
● Accessing array element
.n
● Array length
● Multi-dimensional array
w
ww
2
42. DF
Introduction to Arrays
aP
● Suppose we have here three variables of type int with
vi
different identifiers for each variable.
ee
int number1;
int number2;
int number3;
.n
number1 = 1;
number2 = 2;
w
number3 = 3;
ww
As you can see, it seems like a tedious task in order to just
initialize and use the variables especially if they are used for
the same purpose.
4
43. DF
Introduction to Arrays
aP
● In Java and other programming languages, there is one
vi
capability wherein we can use one variable to store a list of
data and manipulate them more efficiently. This type of
ee
variable is called an array.
.n
● An array stores multiple data items of the same data type, in
a contiguous block of memory, divided into a number of
slots.
w
ww
5
45. DF
Declaring Arrays
aP
● To declare an array, write the data type, followed by a set of
vi
square brackets[], followed by the identifier name.
ee
● For example,
int []ages;
.n
or
int ages[];
w
ww
7
46. DF
aP
vi
ee
.n
Instantiation of
w
ww
an Array
8
47. DF
Array Instantiation
aP
● After declaring, we must create the array and specify its
vi
length with a constructor statement.
ee
● Definitions:
– Instantiation
.n
● In Java, this means creation
w
– Constructor
● In order to instantiate an object, we need to use a constructor for this. A
ww
constructor is a method that is called to create a certain object.
● We will cover more about instantiating objects and constructors later.
9
48. DF
Array Instantiation
aP
● To instantiate (or create) an array, write the new keyword,
vi
followed by the square brackets containing the number of
elements you want the array to have.
ee
● For example,
//declaration
.n
int ages[];
//instantiate object
w
ages = new int[100];
or, can also be written as,
ww
//declare and instantiate object
int ages[] = new int[100];
10
50. DF
Array Instantiation
aP
● You can also instantiate an array by directly initializing it with
vi
data.
ee
● For example,
int arr[] = {1, 2, 3, 4, 5};
.n
This statement declares and instantiates an array of integers
with five elements (initialized to the values 1, 2, 3, 4, and 5).
w
ww
12
51. DF
Sample Program
aP
1 //creates an array of boolean variables with identifier
2 //results. This array contains 4 elements that are
vi
3 //initialized to values {true, false, true, false}
4
5 boolean results[] = { true, false, true, false };
ee
6
7 //creates an array of 4 double variables initialized
8 //to the values {100, 90, 80, 75};
9
.n
10 double []grades = {100, 90, 80, 75};
11
12 //creates an array of Strings with identifier days and
w
13 //initialized. This array contains 7 elements
14
15 String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”,
ww
“Sun”};
13
52. DF
aP
vi
ee
.n
w
Accessing Array
ww
Element
14
53. DF
Accessing an Array Element
aP
● To access an array element, or a part of the array, you use
vi
a number called an index or a subscript.
ee
● index number or subscript
– assigned to each member of the array, to allow the program to
.n
access an individual member of the array.
– begins with zero and progress sequentially by whole numbers to the
w
end of the array.
– NOTE: Elements inside your array are from 0 to (sizeOfArray-1).
ww
15
54. DF
Accessing an Array Element
aP
● For example, given the array we declared a while ago, we
vi
have
//assigns 10 to the first element in the array
ee
ages[0] = 10;
//prints the last element in the array
.n
System.out.print(ages[99]);
w
ww
16
55. DF
Accessing an Array Element
aP
● NOTE:
vi
– once an array is declared and constructed, the stored value of each
member of the array will be initialized to zero for number data.
ee
– for reference data types such as Strings, they are NOT initialized to
blanks or an empty string “”. Therefore, you must populate the String
arrays explicitly.
w .n
ww
17
56. DF
Accessing an Array Element
aP
● The following is a sample code on how to print all the
vi
elements in the array. This uses a for loop, so our code is
shorter.
ee
1 public class ArraySample{
2 public static void main( String[] args ){
.n
3 int[] ages = new int[100];
4 for( int i=0; i<100; i++ ){
5 System.out.print( ages[i] );
w
6 }
7 }
8 }
ww
18
57. DF
Coding Guidelines
aP
1. It is usually better to initialize or instantiate the
vi
array right away after you declare it. For example,
the declaration,
ee
int []arr = new int[100];
.n
is preferred over,
w
int []arr;
ww
arr = new int[100];
19
58. DF
Coding Guidelines
aP
2. The elements of an n-element array have indexes
vi
from 0 to n-1. Note that there is no array element
arr[n]! This will result in an array-index-out-of-
ee
bounds exception.
.n
3. Remember: You cannot resize an array.
w
ww
20
60. DF
Array Length
aP
● In order to get the number of elements in an array, you can
vi
use the length field of an array.
ee
● The length field of an array returns the size of the array. It
can be used by writing,
.n
arrayName.length
w
ww
22
61. DF
Array Length
aP
1 public class ArraySample {
2 public static void main( String[] args ){
vi
3 int[] ages = new int[100];
4 ee
5 for( int i=0; i<ages.length; i++ ){
6 System.out.print( ages[i] );
7 }
8 }
.n
9 }
w
ww
23
62. DF
Coding Guidelines
aP
1. When creating for loops to process the elements of an
vi
array, use the array object's length field in the condition
statement of the for loop. This will allow the loop to adjust
ee
automatically for different-sized arrays.
.n
2. Declare the sizes of arrays in a Java program using named
constants to make them easy to change. For example,
w
final int ARRAY_SIZE = 1000; //declare a constant
ww
. . .
int[] ages = new int[ARRAY_SIZE];
24
63. DF
aP
vi
ee
.n
Multi-Dimensional
w
ww
Array
25
64. DF
Multidimensional Arrays
aP
● Multidimensional arrays are implemented as arrays of
vi
arrays.
ee
● Multidimensional arrays are declared by appending the
appropriate number of bracket pairs after the array name.
w .n
ww
26
65. DF
Multidimensional Arrays
aP
● For example,
vi
// integer array 512 x 128 elements
ee
int[][] twoD = new int[512][128];
// character array 8 x 16 x 24
char[][][] threeD = new char[8][16][24];
.n
// String array 4 rows x 2 columns
w
String[][] dogs = {{ "terry", "brown" },
{ "Kristin", "white" },
{ "toby", "gray"},
ww
{ "fido", "black"}
};
27
66. DF
Multidimensional Arrays
aP
● To access an element in a multidimensional array is just the
vi
same as accessing the elements in a one dimensional array.
ee
● For example, to access the first element in the first row of
the array dogs, we write,
.n
System.out.print( dogs[0][0] );
w
This will print the String "terry" on the screen.
ww
28
67. DF
Summary
aP
● Arrays
vi
– Definition
ee
– Declaration
– Instantiation and constructors (brief overview – to be discussed
more later)
.n
– Accessing an element
– The length field
w
– Multidimensional Arrays
ww
29
69. ww
Agenda
w.
•
•
ne
General event-handling strategy
Handling events with separate listeners
• ev
Handling events by implementing interfaces
• Handling events with named inner classes
ia
• Handling events with anonymous inner
classes PD
• The standard AWT listener types
• Subtleties with mouse events F.
• Examples co
m
2 Handling Mouse and Keyboard Events www.corewebprogramming.com
70. ww
General Strategy
w.
ne
• Determine what type of listener is of interest
– 11 standard AWT listener types, described on later slide.
ev
• ActionListener, AdjustmentListener,
ComponentListener, ContainerListener,
ia
FocusListener, ItemListener, KeyListener,
WindowListener
• Define a class of that type
PD
MouseListener, MouseMotionListener, TextListener,
F.
– Implement interface (KeyListener, MouseListener, etc.)
– Extend class (KeyAdapter, MouseAdapter, etc.)
• Register an object of your listener class co
with the window
– w.addXxxListener(new MyListenerClass());
• E.g., addKeyListener, addMouseListener
m
3 Handling Mouse and Keyboard Events www.corewebprogramming.com
71. ww Events with a
Handling
w.
Separate Listener: Simple Case
ne
• Listener does not need to call any methods
of the window to which it is attached
ev
import java.applet.Applet;
ia
import java.awt.*;
PD
public class ClickReporter extends Applet {
public void init() {
F.
setBackground(Color.yellow);
addMouseListener(new ClickListener());
}
}
co
m
4 Handling Mouse and Keyboard Events www.corewebprogramming.com
72. ww Listener: Simple Case
Separate
w.
(Continued)
ne
import java.awt.event.*;
ev
public class ClickListener extends MouseAdapter {
public void mousePressed(MouseEvent event) {
ia
System.out.println("Mouse pressed at (" +
event.getX() + "," +
} PD event.getY() + ").");
}
F.
co
m
5 Handling Mouse and Keyboard Events www.corewebprogramming.com
73. ww
Generalizing Simple Case
w.
ne
• What if ClickListener wants to draw a circle
wherever mouse is clicked?
ev
• Why can’t it just call getGraphics to get a
Graphics object with which to draw?
ia
• General solution:
PD
– Call event.getSource to obtain a reference to window or
GUI component from which event originated
– Cast result to type of interest F.
– Call methods on that reference co
m
6 Handling Mouse and Keyboard Events www.corewebprogramming.com
74. ww Events with Separate
Handling
w.
Listener: General Case
ne
import java.applet.Applet;
ev
import java.awt.*;
ia
public class CircleDrawer1 extends Applet {
public void init() {
PD
setForeground(Color.blue);
addMouseListener(new CircleListener());
}
}
F.
co
m
7 Handling Mouse and Keyboard Events www.corewebprogramming.com
75. ww Listener: General
Separate
w.
Case (Continued)
ne
import java.applet.Applet;
import java.awt.*;
ev
import java.awt.event.*;
ia
public class CircleListener extends MouseAdapter {
private int radius = 25;
PD
public void mousePressed(MouseEvent event) {
Applet app = (Applet)event.getSource();
F.
Graphics g = app.getGraphics();
g.fillOval(event.getX()-radius,
co
event.getY()-radius,
2*radius,
}
}
2*radius);
m
8 Handling Mouse and Keyboard Events www.corewebprogramming.com
76. ww Listener: General
Separate
w.
Case (Results)
ne
ev
ia
PD
F.
co
m
9 Handling Mouse and Keyboard Events www.corewebprogramming.com
77. ww 2: Implementing a
Case
w.
Listener Interface
ne
import java.applet.Applet;
import java.awt.*;
ev
import java.awt.event.*;
ia
public class CircleDrawer2 extends Applet
implements MouseListener {
PD
private int radius = 25;
public void init() {
F
setForeground(Color.blue);
addMouseListener(this);
.c
}
om
10 Handling Mouse and Keyboard Events www.corewebprogramming.com
78. ww
Implementing a Listener
w.
Interface (Continued)
ne
public
public
void
void
mouseEntered(MouseEvent event) {}
mouseExited(MouseEvent event) {}
public
public ev void
void
mouseReleased(MouseEvent event) {}
mouseClicked(MouseEvent event) {}
ia
PD
public void mousePressed(MouseEvent event) {
Graphics g = getGraphics();
g.fillOval(event.getX()-radius,
F
event.getY()-radius,
2*radius,
2*radius); .c
}
}
om
11 Handling Mouse and Keyboard Events www.corewebprogramming.com
79. ww
Case 3: Named Inner Classes
w.
import java.applet.Applet;
import java.awt.*; ne
import java.awt.event.*;
ev
ia
public class CircleDrawer3 extends Applet {
public void init() {
setForeground(Color.blue);
addMouseListener(new CircleListener());PD
}
F.
co
m
12 Handling Mouse and Keyboard Events www.corewebprogramming.com
80. ww Inner Classes
Named
w.
(Continued)
ne
• Note: still part of class from previous slide
ev
private class CircleListener
extends MouseAdapter {
ia
private int radius = 25;
PD
public void mousePressed(MouseEvent event) {
Graphics g = getGraphics();
F
g.fillOval(event.getX()-radius,
event.getY()-radius,
2*radius, .c
}
}
2*radius);
om
}
13 Handling Mouse and Keyboard Events www.corewebprogramming.com
81. ww 4: Anonymous Inner
Case
w.
Classes
ne
public class CircleDrawer4 extends Applet {
public void init() {
ev
setForeground(Color.blue);
addMouseListener
(new MouseAdapter() {
ia
private int radius = 25;
PD public void mousePressed(MouseEvent event) {
Graphics g = getGraphics();
F. g.fillOval(event.getX()-radius,
event.getY()-radius,
}
co 2*radius,
2*radius);
}
}
});
m
14 Handling Mouse and Keyboard Events www.corewebprogramming.com
82. ww Handling Strategies:
Event
w.
Pros and Cons
ne
• Separate Listener
– Advantages
ev
• Can extend adapter and thus ignore unused methods
• Separate class easier to manage
ia
– Disadvantage
PD
• Need extra step to call methods in main window
• Main window that implements interface
– Advantage
F.
• No extra steps needed to call methods in main
window
– Disadvantage
co
• Must implement methods you might not care about
m
15 Handling Mouse and Keyboard Events www.corewebprogramming.com
83. ww Handling Strategies:
Event
w.
Pros and Cons (Continued)
ne
• Named inner class
– Advantages
ev
• Can extend adapter and thus ignore unused methods
• No extra steps needed to call methods in main
ia
window
– Disadvantage
PD
• A bit harder to understand
• Anonymous inner class
– Advantages F.
co
• Same as named inner classes
• Even shorter
– Disadvantage
m
• Much harder to understand
16 Handling Mouse and Keyboard Events www.corewebprogramming.com
84. ww AWT Event Listeners
Standard
w.
(Summary)
ne Adapter Class
ev
Listener
ActionListener
(If Any) Registration Method
addActionListener
ia
AdjustmentListener
ComponentListener ComponentAdapter
addAdjustmentListener
addComponentListener
FocusListener
ItemListener
PD
ContainerListener ContainerAdapter
FocusAdapter
addContainerListener
addFocusListener
addItemListener
KeyListener
MouseListener
F. KeyAdapter
MouseAdapter
addKeyListener
addM ouseListener
MouseMotionListener
TextListener
WindowListener co MouseMotionAdapter
WindowAdapter
addM ouseMotionListener
addTextListener
addWindowListener
m
17 Handling Mouse and Keyboard Events www.corewebprogramming.com
85. ww AWT Event Listeners
Standard
w.
(Details)
ne
• ActionListener
– Handles buttons and a few other actions
ev
• actionPerformed(ActionEvent event)
• AdjustmentListener
ia
– Applies to scrolling
PD
• adjustmentValueChanged(AdjustmentEvent event)
• ComponentListener
• F.
– Handles moving/resizing/hiding GUI objects
componentResized(ComponentEvent event)
•
•
co
componentMoved (ComponentEvent event)
componentShown(ComponentEvent event)
•
m
componentHidden(ComponentEvent event)
18 Handling Mouse and Keyboard Events www.corewebprogramming.com
86. ww AWT Event Listeners
Standard
w.
(Details Continued)
ne
• ContainerListener
– Triggered when window adds/removes GUI controls
ev
• componentAdded(ContainerEvent event)
• componentRemoved(ContainerEvent event)
• FocusListeneria
PD
– Detects when controls get/lose keyboard focus
• focusGained(FocusEvent event)
F.
• focusLost(FocusEvent event)
co
m
19 Handling Mouse and Keyboard Events www.corewebprogramming.com
87. ww AWT Event Listeners
Standard
w.
(Details Continued)
ne
• ItemListener
– Handles selections in lists, checkboxes, etc.
ev
• itemStateChanged(ItemEvent event)
• KeyListener
ia
– Detects keyboard events
PD
• keyPressed(KeyEvent event) -- any key pressed
down
F.
• keyReleased(KeyEvent event) -- any key released
• keyTyped(KeyEvent event) -- key for printable char
released
co
m
20 Handling Mouse and Keyboard Events www.corewebprogramming.com
88. ww AWT Event Listeners
Standard
w.
(Details Continued)
ne
• MouseListener
– Applies to basic mouse events
•
•ev mouseEntered(MouseEvent event)
mouseExited(MouseEvent event)
•
ia
mousePressed(MouseEvent event)
•
• PD
mouseReleased(MouseEvent event)
mouseClicked(MouseEvent event) -- Release without
drag
F.
– Applies on release if no movement since press
• MouseMotionListener
co
– Handles mouse movement
m
• mouseMoved(MouseEvent event)
• mouseDragged(MouseEvent event)
21 Handling Mouse and Keyboard Events www.corewebprogramming.com
89. ww AWT Event Listeners
Standard
w.
(Details Continued)
ne
• TextListener
– Applies to textfields and text areas
ev
• textValueChanged(TextEvent event)
• WindowListener
ia
– Handles high-level window events
PD
• windowOpened, windowClosing, windowClosed,
windowIconified, windowDeiconified,
F.
windowActivated, windowDeactivated
– windowClosing particularly useful
co
m
22 Handling Mouse and Keyboard Events www.corewebprogramming.com
90. ww
Mouse Events: Details
w.
ne
• MouseListener and MouseMotionListener
share event types
• Location of clicks ev
– event.getX() and event.getY()
• Double clicks ia
– Determined by OS, not by programmer
– Call event.getClickCount()
PD
• Distinguishing mouse buttons F.
– Call event.getModifiers() and compare to
MouseEvent.Button2_MASK for a middle click and co
MouseEvent.Button3_MASK for right click.
– Can also trap Shift-click, Alt-click, etc. m
23 Handling Mouse and Keyboard Events www.corewebprogramming.com
91. ww Example: Spelling-
Simple
w.
Correcting Textfield
ne
• KeyListener corrects spelling during typing
• ActionListener completes word on ENTER
ev
• FocusListener gives subliminal hints
ia
PD
F.
co
m
24 Handling Mouse and Keyboard Events www.corewebprogramming.com
92. ww
Example: Simple Whiteboard
w.
import java.applet.Applet;
import java.awt.*; ne
import java.awt.event.*;
ev
public class SimpleWhiteboard extends Applet {
protected int lastX=0, lastY=0;
ia
public void init() {
setBackground(Color.white); PD
setForeground(Color.blue);
addMouseListener(new PositionRecorder());
F.
}
addMouseMotionListener(new LineDrawer());
co
protected void record(int x, int y) {
}
lastX = x; lastY = y; m
25 Handling Mouse and Keyboard Events www.corewebprogramming.com
93. ww
Simple Whiteboard (Continued)
w.
ne
private class PositionRecorder extends MouseAdapter {
ev
public void mouseEntered(MouseEvent event) {
requestFocus(); // Plan ahead for typing
}
record(event.getX(), event.getY());
ia
PD
public void mousePressed(MouseEvent event) {
record(event.getX(), event.getY());
}
}
F.
...
co
m
26 Handling Mouse and Keyboard Events www.corewebprogramming.com
94. ww
Simple Whiteboard (Continued)
w.
... ne
ev
private class LineDrawer extends MouseMotionAdapter {
public void mouseDragged(MouseEvent event) {
int x = event.getX();
int y = event.getY();
ia
Graphics g = getGraphics();
g.drawLine(lastX, lastY, x, y);
record(x, y); PD
}
}
F.
}
co
m
27 Handling Mouse and Keyboard Events www.corewebprogramming.com
95. ww
Simple Whiteboard (Results)
w.
ne
ev
ia
PD
F.
co
m
28 Handling Mouse and Keyboard Events www.corewebprogramming.com
96. ww
Whiteboard: Adding Keyboard
w.
Events
ne
import java.applet.Applet;
import java.awt.*;
ev
import java.awt.event.*;
public class Whiteboard extends SimpleWhiteboard {
ia
protected FontMetrics fm;
PD
public void init() {
super.init();
F.
Font font = new Font("Serif", Font.BOLD, 20);
setFont(font);
}
co
fm = getFontMetrics(font);
addKeyListener(new CharDrawer());
m
29 Handling Mouse and Keyboard Events www.corewebprogramming.com
97. ww
Whiteboard (Continued)
w.
...
ne
private class CharDrawer extends KeyAdapter {
ev
// When user types a printable character,
// draw it and shift position rightwards.
ia
public void keyTyped(KeyEvent event) {
PD
String s = String.valueOf(event.getKeyChar());
getGraphics().drawString(s, lastX, lastY);
record(lastX + fm.stringWidth(s), lastY);
}
}
F.
}
co
m
30 Handling Mouse and Keyboard Events www.corewebprogramming.com
98. ww
Whiteboard (Results)
w.
ne
ev
ia
PD
F.
co
m
31 Handling Mouse and Keyboard Events www.corewebprogramming.com
99. ww
Summary
w.
• General strategy
ne
– Determine what type of listener is of interest
ev
• Check table of standard types
– Define a class of that type
ia
• Extend adapter separately, implement interface,
in anonymous inner class PD
extend adapter in named inner class, extend adapter
– Register an object of your listener class with the window
• Call addXxxListener F.
• Understanding listeners
– Methods give specific behavior. co
• Arguments to methods are of type XxxEvent
– Methods in MouseEvent of particular interest m
32 Handling Mouse and Keyboard Events www.corewebprogramming.com