liang, introduction to java programming, eighth edition, (c) 2011 pearson education, inc. all rights...
TRANSCRIPT
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 11
Chapter 14 Abstract Classes and Interfaces
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
2
Interfaces
What is an interface?
Why is an interface useful?
How do you define an interface?
How do you use an interface?
2
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
3
What is an interface? Why is an interface useful?
An interface is a classlike construct that contains only constants and abstract methods. In many ways, an interface is similar to an abstract class, but the intent of an interface is to specify behavior for objects. For example, you can specify that the objects are comparable, edible, cloneable using appropriate interfaces.
3
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
4
Define an InterfaceTo distinguish an interface from a class, Java uses the following syntax to define an interface:
4
public interface InterfaceName { constant declarations; method signatures;}
Example:
public interface Edible {
/** Describe how to eat */
public abstract String howToEat();
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
5
Omitting Modifiers in Interfaces
All data fields are public final static and all methods are public abstract in an interface. For this reason, these modifiers can be omitted, as shown below:
5
public interface T1 { public static final int K = 1; public abstract void p(); }
Equivalent public interface T1 { int K = 1; void p(); }
A constant defined in an interface can be accessed using syntax InterfaceName.CONSTANT_NAME (e.g., T1.K).
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
6
The ActionListener Interfaces
6
HandleEventHandleEvent RunRun
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
7
Handling GUI Events
Source object (e.g., button)
Listener object contains a method for processing the event.
7
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
8
Interfaces vs. Abstract Classes, cont.
Suppose that c is an instance of Class2. c is also an instance of Object, Class1, Interface1, Interface1_1, Interface1_2, Interface2_1, and Interface2_2.
8
Object Class1
Interface1 Interface1_1
Interface1_2
Class2
Interface2_1
Interface2_2
All classes share a single root, the Object class, but there is no single root for interfaces. Like a class, an interface also defines a type. A variable of an interface type can reference any instance of the class that implements the interface. If a class extends an interface, this interface plays the same role as a superclass. You can use an interface as a data type and cast a variable of an interface type to its subclass, and vice versa.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
9
Wrapper Classes Boolean
Character
Short
Byte
9
Integer Long
Float
Double
java.lang.Object
-
Double -
Float -
Long -
Integer -
Short -
Byte -
Character -
Boolean -
Number -
java.lang.Comparable -
NOTE: (1) The wrapper classes do not have no-arg constructors. (2) The instances of all wrapper classes are immutable, i.e., their internal values cannot be changed once the objects are created.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
10
Conversion MethodsEach numeric wrapper class implements the abstract methods doubleValue, floatValue, intValue, longValue, and shortValue, which are defined in the Number class. These methods “convert” objects into primitive type values.
10
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
11
The Static valueOf MethodsThe numeric wrapper classes have a useful class method, valueOf(String s). This method creates a new object initialized to the value represented by the specified string. For example:
Double doubleObject = Double.valueOf("12.4");
Integer integerObject = Integer.valueOf("12");
11
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
12
The Methods for Parsing Strings into Numbers
You have used the parseInt method in the Integer class to parse a numeric string into an int value and the parseDouble method in the Double class to parse a numeric string into a double value. Each numeric wrapper class has two overloaded parsing methods to parse a numeric string into an appropriate numeric value.
12
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
13
TIP
Java provides a static sort method for sorting an array of Object in the java.util.Arrays class. So you can use the following code to sort arrays in this example:
java.util.Arrays.sort(intArray);
java.util.Arrays.sort(doubleArray);
java.util.Arrays.sort(charArray);
java.util.Arrays.sort(stringArray);
13
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
14
BigInteger and BigDecimal
If you need to compute with very large integers or high precision floating-point values, you can use the BigInteger and BigDecimal classes in the java.math package. Both are immutable. Both extend the Number class and implement the Comparable interface.
14
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 15
Chapter 15 Graphics
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
Java Coordinate System
16
(0, 0) X Axis
Y Axis
(x, y)
x
y
Java Coordinate System
X Axis Conventional Coordinate System
(0, 0)
Y Axis
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 17
Each GUI Component Has its Own Coordinate System
(0, 0) Component c2
Component c1
(0, 0)
(0, 0) (x1, y1)
(x2, y2)
(x3, y3) Component c3 c3’s coordinate
system
c2’s coordinate system
c1’s coordinate system
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 18
The Graphics ClassYou can draw strings, lines, rectangles, ovals, arcs, polygons, and polylines, using the methods in the Graphics class.
java.awt.Graphics
+setColor(color: Color): void
+setFont(font: Font): void
+drawString(s: String, x: int, y: int): void
+drawLine(x1: int, y1: int, x2: int, y2: int): void
+drawRect(x: int, y: int, w: int, h: int): void
+fillRect(x: int, y: int, w: int, h: int): void
+drawRoundRect(x: int, y: int, w: int, h: int, aw: int, ah: int): void
+fillRoundRect(x: int, y: int, w: int, h: int, aw: int, ah: int): void
+draw3DRect(x: int, y: int, w: int, h: int, raised: boolean): void
+fill3DRect(x: int, y: int, w: int, h: int, raised: boolean): void
+drawOval(x: int, y: int, w: int, h: int): void
+fillOval(x: int, y: int, w: int, h: int): void
+drawArc(x: int, y: int, w: int, h: int, startAngle: int, arcAngle: int): void
+fillArc(x: int, y: int, w: int, h: int, startAngle: int, arcAngle: int): void
+drawPolygon(xPoints: int[], yPoints: int[], nPoints: int): void
+fillPolygon(xPoints: int[], yPoints: int[], nPoints: int): void
+drawPolygon(g: Polygon): void
+fillPolygon(g: Polygon): void
+drawPolyline(xPoints: int[], yPoints: int[], nPoints: int): void
Sets a new color for subsequent drawings.
Sets a new font for subsequent drwings.
Draws a string starting at point (x, y).
Draws a line from (x1, y1) to (x2, y2).
Draws a rectangle with specified upper-left corner point at (x, y) and width w and height h.
Draws a filled rectangle with specified upper-left corner point at (x, y) and width w and height h.
Draws a round-cornered rectangle with specified arc width aw and arc height ah.
Draws a filled round-cornered rectangle with specified arc width aw and arc height ah.
Draws a 3-D rectangle raised above the surface or sunk into the surface.
Draws a filled 3-D rectangle raised above the surface or sunk into the surface.
Draws an oval bounded by the rectangle specified by the parameters x, y, w, and h.
Draws a filled oval bounded by the rectangle specified by the parameters x, y, w, and h.
Draws an arc conceived as part of an oval bounded by the rectangle specified by the parameters x, y, w, and h.
Draws a filled arc conceived as part of an oval bounded by the rectangle specified by the parameters x, y, w, and h.
Draws a closed polygon defined by arrays of x and y coordinates. Each pair of (x[i], y[i]) coordinates is a point.
Draws a filled polygon defined by arrays of x and y coordinates. Each pair of (x[i], y[i]) coordinates is a point.
Draws a closed polygon defined by a Polygon object.
Draws a filled polygon defined by a Polygon object.
Draws a polyline defined by arrays of x and y coordinates. Each pair of (x[i], y[i]) coordinates is a point.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 19
paintComponent ExampleIn order to draw things on a component, you need to define a class that extends JPanel and overrides its paintComponent method to specify what to draw. The first program in this chapter can be rewritten using paintComponent.
TestPaintComponentTestPaintComponent RunRun
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 20
Drawing Geometric Figures
Drawing Strings Drawing Lines Drawing Rectangles Drawing Ovals Drawing Arcs Drawing Polygons
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 21
Drawing Strings
(0, 0) (getWidth(), 0)
(getWidth(), getHeight()) (0, getHeight())
(x, y) s is display here
(0, 0) (getWidth(), 0)
(getWidth(), getHeight()) (0, getHeight())
(x1, y1)
(x2, y2)
drawLine(int x1, int y1, int x2, int y2);drawString(String s, int x, int y);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 22
Drawing Rounded Rectangles
drawRoundRect(int x, int y, int w, int h, int aw, int ah);
fillRoundRect(int x, int y, int w, int h, int aw, int ah);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 23
Drawing OvalsdrawOval(int x, int y, int w, int h);
fillOval(int x, int y, int w, int h);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 24
Case Study: The FigurePanel Class This example develops a useful class for displaying various figures. The class enables the user to set the figure type and specify whether the figure is filled, and displays the figure on a panel.
FigurePanel
+LINE = 1
+RECTANGLE = 2
+ROUND_RECTANGLE = 3
+OVAL = 4
-type: int
-filled: boolean
+FigurePanel()
+FigurePanel(type: int)
+FigurePanel(type: int, filled: boolean)
+getType(): int
+setType(type: int): void
+isFilled(): boolean
+setFilled(filled: boolean): void
javax.swing.JPanel -char token +getToken +setToken +paintComponet +mouseClicked
LINE, RECTANGLE, ROUND_RECTANGLE, and OVAL are constants.
Specifies the figure type (default: 1).
Specifies whether the figure is filled (default: false).
Creates a default figure panel.
Creates a figure panel with the specified type.
Creates a figure panel with the specified type and filled property.
Returns the figure type.
Sets a new figure type.
Checks whether the figure is filled with a color.
Sets a new filled property.
FigurePanelFigurePanel
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 25
Test FigurePanelThis example develops a useful class for displaying various figures. The class enables the user to set the figure type and specify whether the figure is filled, and displays the figure on a panel.
TestFigurePanelTestFigurePanel RunRun
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 26
Displaying Image IconsYou learned how to create image icons and display image icons in labels and buttons. For example, the following statements create an image icon and display it in a label:
ImageIcon icon = new ImageIcon("image/us.gif");JLabel jlblImage = new JLabel(imageIcon);
An image icon displays a fixed-size image. To display an image in a flexible size, you need to use the java.awt.Image class. An image can be created from an image icon using the getImage() method as follows:
Image image = imageIcon.getImage();
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 27
Displaying ImagesUsing a label as an area for displaying images is simple and convenient, but you don't have much control over how the image is displayed. A more flexible way to display images is to use the drawImage method of the Graphics class on a panel. Four versions of the drawImage method are shown here.
java.awt.Graphics +drawImage(image: Image, x: int, y: int,
bgcolor: Color, observer: ImageObserver): void
+drawImage(image: Image, x: int, y: int, observer: ImageObserver): void
+drawImage(image: Image, x: int, y: int, width: int, height: int, observer: ImageObserver): void
+drawImage(image: Image, x: int, y: int, width: int, height: int, bgcolor: Color, observer: ImageObserver): void
Draws the image in a specified location. The image's top-left corner is at (x, y) in the graphics context's coordinate space. Transparent pixels in the image are drawn in the specified color bgcolor. The observer is the object on which the image is displayed. The image is cut off if it is larger than the area it is being drawn on.
Same as the preceding method except that it does not specify a background color.
Draws a scaled version of the image that can fill all of the available space in the specified rectangle.
Same as the preceding method except that it provides a solid background color behind the image being drawn.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 28
Displaying Images ExampleThis example gives the code that displays an image from image/us.gif. The file image/us.gif is under the class directory. The Image from the file is created in the program. The drawImage method displays the image to fill in the whole panel, as shown in the figure.
RunRunDisplayImageDisplayImage
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 29
Case Study: ImageViewer ClassDisplaying an image is a common task in Java programming. This case study develops a reusable component named ImageViewer that displays an image in a panel. The ImageViewer class contains the properties image, imageFilename, stretched, xCoordinate, and yCoordinate.
ImageViewer
-image: Image
-stretched: boolean
-xCoordinate: int
-yCoordinate: int
+ImageViewer()
+ImageViewer(imageFile: String)
javax.swing.JPanel
Image in the image viewer.
True if the image is stretched in the viewer.
x-coordinate of the upper-left corner of the image in the viewer.
y-coordinate of the upper-left corner of the image in the viewer.
Constructs an image viewer with no image.
Constructs an image viewer with the specified image file.
The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 30
ImageView ExampleThis example gives an example that creates six images using the ImageViewer class.
RunRunSixFlagsSixFlags
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 31
Chapter 16 Event-Driven Programming
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 32
Procedural vs. Event-Driven Programming
Procedural programming is executed in procedural order.
In event-driven programming, code is executed upon activation of events.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 33
Revisit Listing 11.7Taste of Event-Driven Programming
The example displays a button in the frame. A message is displayed on the console when a button is clicked.
HandleEventHandleEvent
RunRun
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 34
Events
An event can be defined as a type of signal to the program that something has happened.
The event is generated by external user actions such as mouse movements, mouse clicks, and keystrokes, or by the operating system, such as a timer.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 35
Event Classes
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 36
Event Information
An event object contains whatever properties are pertinent to the event. You can identify the source object of the event using the getSource() instance method in the EventObject class. The subclasses of EventObject deal with special types of events, such as button actions, window events, component events, mouse movements, and keystrokes. Table 15.1 lists external user actions, source objects, and event types generated.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 37
Selected User ActionsSource Event Type
User Action Object Generated
Click a button JButton ActionEvent
Click a check box JCheckBox ItemEvent, ActionEvent
Click a radio button JRadioButton ItemEvent, ActionEvent
Press return on a text field JTextField ActionEvent
Select a new item JComboBox ItemEvent, ActionEvent
Window opened, closed, etc. Window WindowEvent
Mouse pressed, released, etc. Component MouseEvent
Key released, pressed, etc. Component KeyEvent
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 38
The Delegation Model
source: SourceClass
+addXListener(listener: XListener)
listener: ListenerClass
User Action
Trigger an event
XListener +handler(event: XEvent)
Register by invoking source.addXListener(listener);
(a) A generic source component with a generic listener
source: JButton
+addActionListener(listener: ActionListener)
listener: CustomListenerClass
ActionListener
+actionPerformed(event: ActionEvent)
Register by invoking source.addActionListener(listener);
(b) A JButton source component with an ActionListener
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 39
Internal Function of a Source Component
source: SourceClass
+addXListener(XListener listener)
(a) Internal function of a generic source object
event: XEvent listener1 listener2 … listenern
+handler(
Keep it a list
Invoke listener1.handler(event) listener2.handler(event) … listenern.handler(event)
An event is triggered
source: JButton
+addActionListener(ActionListener listener)
(b) Internal function of a JButton object
event: ActionEvent
listener1 listener2 … listenern
+handler(
Keep it a list
Invoke listener1.actionPerformed(event) listener2.actionPerformed(event) … listenern.actionPerformed(event)
An event is triggered
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 40
The Delegation Model: Example
JButton jbt = new JButton("OK");
ActionListener listener = new OKListener();
jbt.addActionListener(listener);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 41
Selected Event Handlers Event Class Listener Interface Listener Methods (Handlers)ActionEvent ActionListener actionPerformed(ActionEvent)ItemEvent ItemListener itemStateChanged(ItemEvent)WindowEvent WindowListener windowClosing(WindowEvent)
windowOpened(WindowEvent)windowIconified(WindowEvent)windowDeiconified(WindowEvent)windowClosed(WindowEvent)windowActivated(WindowEvent)windowDeactivated(WindowEvent)
ContainerEvent ContainerListener componentAdded(ContainerEvent)componentRemoved(ContainerEvent)
MouseEvent MouseListener mousePressed(MouseEvent)mouseReleased(MouseEvent)
mouseClicked(MouseEvent) mouseExited(MouseEvent) mouseEntered(MouseEvent)KeyEvent KeyListener keyPressed(KeyEvent)
keyReleased(KeyEvent) keyTypeed(KeyEvent)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 42
Example: Second Version for ControlCircle (with listener for Enlarge)
Now let us consider to write a program that uses two buttons to control the size of a circle.
ControlCircle2ControlCircle2 RunRun
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 43
Inner Class Listeners
A listener class is designed specifically to create a listener object for a GUI component (e.g., a button). It will not be shared by other applications. So, it is appropriate to define the listener class inside the frame class as an inner class.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 44
Inner Classes
Inner class: A class is a member of another class.
Advantages: In some applications, you can use an inner class to make programs simple.
An inner class can reference the data and methods defined in the outer class in which it nests, so you do not need to pass the reference of the outer class to the constructor of the inner class.
ShowInnerClassShowInnerClass
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 45
Inner Classes, cont. public class Test { ... } public class A { ... }
public class Test { ... // Inner class public class A { ... } }
(a)
(b)
// OuterClass.java: inner class demo public class OuterClass { private int data; /** A method in the outer class */ public void m() { // Do something } // An inner class class InnerClass { /** A method in the inner class */ public void mi() { // Directly reference data and method // defined in its outer class data++; m(); } } }
(c)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 46
Inner Classes (cont.)
Inner classes can make programs simple and concise.
An inner class supports the work of its containing outer class and is compiled into a class named OuterClassName$InnerClassName.class. For example, the inner class InnerClass in OuterClass is compiled into OuterClass$InnerClass.class.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 47
Inner Classes (cont.)
An inner class can be declared public, protected, or private subject to the same visibility rules applied to a member of the class.
An inner class can be declared static. A static inner class can be accessed using the outer class name. A static inner class cannot access nonstatic members of the outer class
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 48
Anonymous Inner Classes An anonymous inner class must always extend a superclass or
implement an interface, but it cannot have an explicit extends or implements clause.
An anonymous inner class must implement all the abstract methods in the superclass or in the interface.
An anonymous inner class always uses the no-arg constructor from its superclass to create an instance. If an anonymous inner class implements an interface, the constructor is Object().
An anonymous inner class is compiled into a class named OuterClassName$n.class. For example, if the outer class Test has two anonymous inner classes, these two classes are compiled into Test$1.class and Test$2.class.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 49
Anonymous Inner Classes (cont.)
Inner class listeners can be shortened using anonymous inner classes. An anonymous inner class is an inner class without a name. It combines declaring an inner class and creating an instance of the class in one step. An anonymous inner class is declared as follows:
new SuperClassName/InterfaceName() { // Implement or override methods in superclass or interface // Other methods if necessary}
AnonymousListenerDemoAnonymousListenerDemo RunRun
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 50
Alternative Ways of Defining Listener Classes
There are many other ways to define the listener classes. For example, you may rewrite Listing 6.3 by creating just one listener, register the listener with the buttons, and let the listener detect the event source, i.e., which button fires the event.
DetectSourceDemoDetectSourceDemo RunRun
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 51
Alternative Ways of Defining Listener Classes
You may also define the custom frame class that implements ActionListener.
FrameAsListenerDemoFrameAsListenerDemo RunRun
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 52
Example: Handling Window Events
TestWindowEventTestWindowEvent RunRun
Objective: Demonstrate handling the window events. Any subclass of the Window class can generate the following window events: window opened, closing, closed, activated, deactivated, iconified, and deiconified. This program creates a frame, listens to the window events, and displays a message to indicate the occurring event.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 53
MouseEvent
java.awt.event.MouseEvent
+getButton(): int
+getClickCount(): int
+getPoint(): java.awt.Point
+getX(): int
+getY(): int
Indicates which mouse button has been clicked.
Returns the number of mouse clicks associated with this event.
Returns a Point object containing the x and y coordinates.
Returns the x-coordinate of the mouse point.
Returns the y-coordinate of the mouse point.
java.awt.event.InputEvent
+getWhen(): long
+isAltDown(): boolean
+isControlDown(): boolean
+isMetaDown(): boolean
+isShiftDown(): boolean
Returns the timestamp when this event occurred.
Returns whether or not the Alt modifier is down on this event.
Returns whether or not the Control modifier is down on this event.
Returns whether or not the Meta modifier is down on this event
Returns whether or not the Shift modifier is down on this event.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 54
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 foractions such as dragging or moving themouse.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 55
Handling Mouse Events
java.awt.event.MouseListener
+mousePressed(e: MouseEvent): void
+mouseReleased(e: MouseEvent): void
+mouseClicked(e: MouseEvent): void
+mouseEntered(e: MouseEvent): void
+mouseExited(e: MouseEvent): void
Invoked when the mouse button has been pressed on the source component.
Invoked when the mouse button has been released on the source component.
Invoked when the mouse button has been clicked (pressed and released) on the source component.
Invoked when the mouse enters the source component.
Invoked when the mouse exits the source component.
java.awt.event.MouseMotionListener
+mouseDragged(e: MouseEvent): void
+mouseMoved(e: MouseEvent): void
Invoked when a mouse button is moved with a button pressed.
Invoked when a mouse button is moved without a button pressed.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 56
Example: Moving Message Using Mouse
Objective: Create a program to display a message in a panel. You can use the mouse to move the message. The message moves as the mouse drags and is always displayed at the mouse point.
MoveMessageDemoMoveMessageDemo RunRun
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 57
Handling Keyboard Events
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 thenreleased.
To process a keyboard event, use the following handlers in the KeyListener interface:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 58
The KeyEvent Class Methods:
getKeyChar() method
getKeyCode() method
Keys:Home VK_HOMEEnd VK_ENDPage Up VK_PGUPPage Down VK_PGDNetc...
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 59
The KeyEvent Class, cont.
java.awt.event.KeyEvent
+getKeyChar(): char
+getKeyCode(): int
Returns the character associated with the key in this event.
Returns the integer keyCode associated with the key in this event.
java.awt.event.InputEvent
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 60
Example: Keyboard Events Demo
Objective: Display a user-input character. The user can also move the character up, down, left, and right using the arrow keys.
KeyEventDemoKeyEventDemo RunRun
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 61
The Timer Class Some non-GUI components can fire events. The javax.swing.Timer class
is a source component that fires an ActionEvent at a predefined rate.
javax.swing.Timer
+Timer(delay: int, listener: ActionListener)
+addActionListener(listener: ActionListener): void
+start(): void
+stop(): void
+setDelay(delay: int): void
Creates a Timer with a specified delay in milliseconds and an ActionListener.
Adds an ActionListener to the timer.
Starts this timer.
Stops this timer.
Sets a new delay value for this timer.
The Timer class can be used to control animations. For example, you
can use it to display a moving message.
AnimationDemoAnimationDemo RunRun