Download presentation
Presentation is loading. Please wait.
Published byMarilynn Harrell Modified over 9 years ago
1
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 1 Chapter 14 Abstract Classes and Interfaces
2
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
3
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
4
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 4 Define an Interface To 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(); }
5
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 A constant defined in an interface can be accessed using syntax InterfaceName.CONSTANT_NAME (e.g., T1.K).
6
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 6 The ActionListener Interfaces 6 HandleEvent Run
7
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
8
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 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.
9
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 9 Wrapper Classes F Boolean F Character F Short F Byte 9 F Integer F Long F Float F Double 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.
10
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 10 Conversion Methods Each 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
11
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 11 The Static valueOf Methods The 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
12
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
13
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
14
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
15
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 15 Chapter 15 Graphics
16
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Java Coordinate System 16
17
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
18
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 18 The Graphics Class You can draw strings, lines, rectangles, ovals, arcs, polygons, and polylines, using the methods in the Graphics class.
19
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 19 paintComponent Example In 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. TestPaintComponentRun
20
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 20 Drawing Geometric Figures F Drawing Strings F Drawing Lines F Drawing Rectangles F Drawing Ovals F Drawing Arcs F Drawing Polygons
21
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 21 Drawing Strings drawLine(int x1, int y1, int x2, int y2);drawString(String s, int x, int y);
22
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);
23
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 23 Drawing Ovals drawOval(int x, int y, int w, int h); fillOval(int x, int y, int w, int h);
24
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
25
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 25 Test FigurePanel 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. TestFigurePanelRun
26
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 26 Displaying Image Icons You 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();
27
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 27 Displaying Images Using 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.
28
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 28 Displaying Images Example This 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. RunDisplayImage
29
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 29 Case Study: ImageViewer Class Displaying 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.
30
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 30 ImageView Example This example gives an example that creates six images using the ImageViewer class. RunSixFlags
31
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 31 Chapter 16 Event-Driven Programming
32
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 32 Procedural vs. Event-Driven Programming F Procedural programming is executed in procedural order. In event-driven programming, code is executed upon activation of events.
33
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 33 Revisit Listing 11.7 Taste of Event-Driven Programming F The example displays a button in the frame. A message is displayed on the console when a button is clicked. HandleEvent Run
34
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 34 Events F An event can be defined as a type of signal to the program that something has happened. F 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.
35
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 35 Event Classes
36
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.
37
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 37 Selected User Actions SourceEvent Type User ActionObjectGenerated Click a button JButtonActionEvent Click a check box JCheckBoxItemEvent, ActionEvent Click a radio button JRadioButtonItemEvent, ActionEvent Press return on a text field JTextFieldActionEvent Select a new item JComboBoxItemEvent, ActionEvent Window opened, closed, etc. WindowWindowEvent Mouse pressed, released, etc. ComponentMouseEvent Key released, pressed, etc. ComponentKeyEvent
38
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 38 The Delegation Model
39
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 39 Internal Function of a Source Component
40
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);
41
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 41 Selected Event Handlers Event ClassListener InterfaceListener Methods (Handlers) ActionEventActionListeneractionPerformed(ActionEvent) ItemEventItemListeneritemStateChanged(ItemEvent) WindowEventWindowListenerwindowClosing(WindowEvent) windowOpened(WindowEvent) windowIconified(WindowEvent) windowDeiconified(WindowEvent) windowClosed(WindowEvent) windowActivated(WindowEvent) windowDeactivated(WindowEvent) ContainerEventContainerListenercomponentAdded(ContainerEvent) componentRemoved(ContainerEvent) MouseEventMouseListenermousePressed(MouseEvent) mouseReleased(MouseEvent) mouseClicked(MouseEvent) mouseExited(MouseEvent) mouseEntered(MouseEvent) KeyEventKeyListenerkeyPressed(KeyEvent) keyReleased(KeyEvent) keyTypeed(KeyEvent)
42
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. ControlCircle2Run
43
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.
44
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. F 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. ShowInnerClass
45
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 45 Inner Classes, cont.
46
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 46 Inner Classes (cont.) F Inner classes can make programs simple and concise. F 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.
47
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 47 Inner Classes (cont.) F An inner class can be declared public, protected, or private subject to the same visibility rules applied to a member of the class. F 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
48
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 48 Anonymous Inner Classes F An anonymous inner class must always extend a superclass or implement an interface, but it cannot have an explicit extends or implements clause. F An anonymous inner class must implement all the abstract methods in the superclass or in the interface. F 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(). F 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.
49
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 } AnonymousListenerDemo Run
50
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. DetectSourceDemo Run
51
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. FrameAsListenerDemo Run
52
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 52 Example: Handling Window Events TestWindowEvent Run 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.
53
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 53 MouseEvent
54
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 for actions such as dragging or moving the mouse.
55
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 55 Handling Mouse Events
56
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. MoveMessageDemoRun
57
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 then released. To process a keyboard event, use the following handlers in the KeyListener interface:
58
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_HOME End VK_END Page Up VK_PGUP Page Down VK_PGDN etc...
59
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 59 The KeyEvent Class, cont.
60
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. KeyEventDemo Run
61
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. The Timer class can be used to control animations. For example, you can use it to display a moving message. AnimationDemo Run
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.