Sunteți pe pagina 1din 55

presentation slides for

Object-Oriented Problem Solving


JAVA, JAVA, JAVA
Second Edition

Ralph Morelli
Trinity College
Hartford, CT

published by Prentice
Hall
Java, Java, Java
Object Oriented Problem Solving

Chapter 4 Applets:
Programming for the
World Wide Web
Objectives
• Be able to design and implement a Java
applet.
• Understand Java's event handling model.
• Be able to handle button clicks in your
programs.
• Have a better appreciation of inheritance and
polymorphism.
• Know how to design a simple Graphical
User Interface (GUI).
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Outline
• Introduction
• The java.applet.Applet Class
• Class Inheritance
• Applet Subclasses
• A Simple Applet
• Event-Driven Programming
• Case Study: The CyberPetApplet
• Object-Oriented Design: Inheritance and
Polymorphism
• From the Java Library: Image
• In the Laboratory: CyberPetApplet

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Introduction
• An applet  is a Java program embedded
within a Web page and run by a Web
browser.
• An applet has a graphical user interface
(GUI ).
• Java applet programming is event-driven
programming.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
The java.applet.Applet Class
Applet’s public methods help define an
interface between the applet and the browser .

Applets can easily


incorporate multimedia
resources.

Applet execution begins in


the init() method.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Java's GUI Components

GUI components that


can be put into an
applet.

By default, applets use a


FlowLayout.

An Applet isa Panel which


isa Container which isa
Component

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Objects, Assignments, and Types
• An instance of a class can be validly
assigned to variables whose type is any of
its superclasses.
Panel p = new Panel();
Container cont = p; // Valid: A Panel is a Container
Component comp = p; // Valid: A Panel is a Component
Object o = p; // Valid: A Panel is an Object

Container c = new Container();


Panel p = c; // Invalid: A container is
// not necessarily a Panel

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
The Java Class Hierarchy

• By default, a class is a subclass of the


java.lang.Object class.
CyberPet is a direct
subclass of Object

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Inheritance: Specializing a Class
• Inheritance allows us to specialize a class.

Methods in the superclass


can be shared by the
subclasses.

Subclasses inherit
getCreditCardNumber()
and add their own
special methods.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Specialization: A Square is a Rectangle
• A Square is a Rectangle whose length equals width.

Only protected and


public elements can
be inherited.

To construct a Square,
you specify its side.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
A Square is an Extension of a Rectangle
public class Rectangle The Square() constructor
{
protected double length; calls the Rectangle()
protected double width; constructor, passing it side
public Rectangle (double l, double w)
as a value for both length
{ and width.
length = l;
width = w; public class Square extends Rectangle
} // Rectangle() {
public Square (double side)
public double calculateArea() {
{ //Call the superconstructor
return length * width; super(side, side);
} // calculateArea() }
} // Rectangle } // Square

The super keyword refers to


the superclass.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Using the Square Class
Create a new Square
with a side of 10.
public class TestSquare
{
public static void main(String argv[])
{
Square square = new Square (10);
System.out.println("square's area is " + square.calculateArea());
}
} // TestSquare

Output
The inherited calculateArea() Produced
method can be used just as if
it were defined in Square.
square’s area is 100.0

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
An Applet Example
• SimpleApplet contains a single button.
• When the button is clicked, its label is
toggled from “The machine is off” to the
“The machine is on”

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Applets
• Java applets are made by first creating a
subclass of java.applet.Applet.
• And then instantiating the subclass.
public class SimpleApplet extends Applet { ... } // Define subclass

SimpleApplet myApplet = new SimpleApplet(); // and instantiate it

• The Applet class cannot be instantiated.


Applet a = new Applet(); // Not the way to do it!

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
A Simple Applet
• SimpleApplet inherits from Applet and
implements the ActionListener interface.
These methods are inherited
by SimpleApplet

An interface is an abstract
class with no variables.

The actionPerformed() method is


defined abstractly in
ActionListener and implemented
here.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Java Definition of SimpleApplet
import java.applet.*;
Import class names
import java.awt.*;
import java.awt.event.*; Create a subclass
public class SimpleApplet extends Applet implements ActionListener
{
private Button toggle; // From java.awt.*
The applet handles
public void init()
{ button clicks
toggle = new Button ("The machine is off");
toggle.addActionListener(this);
add(toggle);
} // init() Execution begins here
public void actionPerformed(ActionEvent e)
{
String str = toggle.getLabel(); // Get the Button's label
if (str.equals("The machine is on")) // and change it
toggle.setLabel("The machine is off");
else // or
toggle.setLabel("The machine is on"); // change it back
} // actionPerformed()
} // SimpleApplet
Called when toggle is clicked.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
SimpleApplet Inherits Functionality
Use: A SimpleApplet can use the add()
method inherited from
java.awt.Container.

Override: This init()


overrides the init()
method inherited from
java.applet.Applet

Implement: This
actionPerformed() is
implemented according to the
definition inherited from
ActionListener interface
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Interacting Objects
• A Web browser creates a SimpleApplet named
applet1 and tells it to initialize itself. The applet
creates a Button named toggle and adds it to itself.

• When the browser detects a click, it tells the applet


to perform an action. The applet tells Button to
toggle its label.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Overriding the Applet.init() Method
• The init() method initializes the applet. It is
where applet execution begins. It may be
overridden in the applet subclass.
public void init () Create a new Button.
{
toggle = new Button ("The machine is off");
toggle.addActionListener(this);
add(toggle);
} // init() This applet will listen
for button clicks.

The add() method, inherited from


Container, puts the button in the applet.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Implementing an Interface
• An interface contains abtract methods that must be
implemented in the subclass.
public abstract interface ActionListener extends EventListener
{
public abstract void actionPerformed (ActionEvent e);
}

• The implementation must have the exact


same signature.
public void actionPerformed (ActionEvent e)
{
String str = toggle.getLabel(); // Get the toggle's label
if (str.equals("The machine is on")) // and change it
toggle.setLabel("The machine is off");
else // or
toggle.setLabel("The machine is on"); // change it back
} // actionPerformed()

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Polymorphism and Extensibility
• Polymorphism = many (poly) forms (morph)
• A polymorphic method -- init() -- has
different behavior for different objects.
• Overriding Applet.init() creates a method
that performs appropriate initializations for
your applet.
• Extensibility: Applet functionality (init())
defined in the superclass (Applet) is
extended to the subclass (SimpleApplet).

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
The Polymorphic eat() Method
• Polymorphism: The eat() method has different
behavior for CyberDogs and CyberCats.
CyberPet p1 = new CyberDog();
p1.eat(); // Eats dog food
p1 = new CyberCat();
p1.eat(); // Eats cat food

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
The Polymorphic init() Method
• Polymorphism: The init() method has different
behavior for AppletA and AppletB.
public class AppletA extends Applet {
public void init() {
System.out.println(“AppletA”);
}
}
public class AppletB extends Applet {
public void init() {
System.out.println(“AppletB”);
}
}

Applet applet= new AppletA();


applet.init(); // Prints “AppletA”
applet = new AppletB();
applet.init(); // Prints “AppletB”

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Event-Driven Programming

Java’s Event Model


Events are handled by
methods in the applet.

Events are triggered


by user actions
(mouse, keyboard).

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
The Java Event Hierarchy

An action event occurs


when an applet Button is
clicked.

An key event occurs when


the user types a key.

An mouse event occurs


when the mouse is moved.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Creating an ActionListener

toggle = new Button ("The machine is off");


toggle.addActionListener(this);

After this applet is


The this keyword is self-
designated as a
referential. It’s like saying “I”.
ActionListener for the
toggle Button...

… it listens for clicks on


toggle.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Handling Action Events
1. Applet subclass implements the
ActionListener interface
import java.applet.*;
import java.awt.*;
import java.awt.event.*; 2. Declare a Button instance.

public class SimpleApplet extends Applet implements ActionListener {


private Button toggle; // From java.awt.*
3. Create a Button instance.
public void init() {
toggle = new Button ("The machine is off");
toggle.addActionListener(this);
add(toggle); 4. Designate this applet as the button’s
} // init() listener.
public void actionPerformed(ActionEvent e) {
String str = toggle.getLabel(); // Get the toggle Button's label
if (str.equals("The machine is on")) // and change it
toggle.setLabel("The machine is off");
5. Add the button to the applet.
else // or
toggle.setLabel("The machine is on"); // change it back
} // actionPerformed()
} // SimpleApplet 6. Define the specific actions to
be performed when the button is
clicked..

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Responding to a Click Event

The Java Virtual Machine is


embedded in the Browser.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Running an (Embedded) Applet
• A summary of what happens from the browser’s (or
appletviewer’s) perspective.

Create an instance of the applet.


SimpleApplet applet1 = new SimpleApplet(); // Create an applet
object
applet1.init() ; // and call its init()
... // Handle other tasks

repeat until applet_is_stopped


{
... // Handle other tasks
if (ACTION_EVENT) // If an action occurs,
applet1.actionPerformed(anActionEvent); // pass it to the
applet
if (user_quits_browser) // If the user quits,
applet1.destroy(); Repeatedly
// pass
killevents
the that belong to
applet
} the applet to its actionPerformed()
method.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Tracing the Applet
The order in which applet
statements are executed when the
user makes two successive clicks
import java.applet.*;
import java.awt.*;
on its toggle button.
import java.awt.event.*;

public class SimpleApplet extends Applet implements ActionListener {


private Button toggle; // From java.awt.*

public void init() { The applet is initialized.


toggle = new Button ("The machine is off"); 1
toggle.addActionListener(this);
add(toggle); 2
} // init() 3
public void actionPerformed(ActionEvent e) {
String str = toggle.getLabel(); // Get the Button's label
if (str.equals("The machine is on")) // and change it
toggle.setLabel("The machine is off");
The user clicks on the button.
else First Click// or
Second Click
toggle.setLabel("The machine is on"); // change it back
} // actionPerformed() 4 7
} // SimpleApplet 5 8
6 9

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Case Study: The CyberPetApplet

The applet will serve as


an user interface
between the CyberPet
and a user.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
CyberPetApplet’s GUI Interface

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
CyberPetApplet: Design Specification

Uses

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Defining CyberPetApplet
Step 1. Define a subclass of
java.applet.Applet that implements the
ActionListener interface.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class CyberPetApplet extends Applet implements


ActionListener
{
} // CyberPetApplet

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Defining CyberPetApplet (cont.)
Step 2. Declare the instance variables.
public class CyberPetApplet extends Applet implements ActionListener {
// Declare instance variables.
private CyberPet pet1; // The CyberPet
private Label nameLabel; // Label
private TextField stateField; // TextField
private Button eatButton, sleepButton; // Buttons

public void init()


{
}
} // CyberPetApplet

Stub version of init()

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Defining CyberPetApplet (cont.)
Step 3. Define the init() method.
public void init()
{ // Instantiate the instance variables
pet1 = new CyberPet("Socrates"); // The CyberPet
nameLabel = new Label("Hi! My name is " + pet1.getName() +
" and currently I am : ");
stateField = new TextField(12); // TextField
eatButton = new Button("Eat!"); // Buttons
eatButton.addActionListener(this); // Assign the listeners
sleepButton = new Button("Sleep!");
sleepButton.addActionListener(this);

stateField.setText(pet1.getState()); // Initialize the TextField

stateField.setEditable(false);

add(nameLabel); // Add the components to the applet.


add(stateField);
add(eatButton);
add(sleepButton);
} // init()

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Default Layout: FlowLayout

add(nameLabel); // Add the components to the applet.


add(stateField);
add(eatButton);
add(sleepButton);

The applet’s default


FlowLayout means
components are arranged
from left to right in the
container, wrapping around
to the next row if necessary.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Interacting Objects

stateField.setText(pet1.getState()); // Initialize the TextField

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Defining CyberPetApplet (cont.)
Step 4. Implement the
actionPerformed() method.
public class CyberPetApplet extends Applet implements ActionListener {

// Variable declarations and init() method not shown.

public void actionPerformed(ActionEvent e)


{
if (e.getSource() == eatButton) // If eat button clicked,
pet1.eat(); // tell the pet to eat
else if (e.getSource() == sleepButton) // If sleep button clicked,
pet1.sleep(); // tell the pet to sleep

stateField.setText(pet1.getState()); // Display the pet's state


} // actionPerformed()

} // CyberPetApplet The getSource() method


returns the source of the
ActionEvent.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
The CyberPetApplet Program

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Object-Oriented Design: ToggleButton
• A ToggleButton isa Button that toggles its own
label.

Whenever it is clicked,
it toggles between
label1 and label2.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Design Spec: The ToggleButton Class
• Design Specification
– Class Name: ToggleButton
– Role: To be a button that toggles between two
labels
– Information (instance variables)
• Label1: Primary label (initial value of label)
• Label2: Secondary label
– Actions (public methods)
• ToggleButton: constructor initializes the two
labels
• actionPerformed(): Toggles between the two
labels
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Class Definition: ToggleButton
import java.awt.*;
import java.awt.event.*; Inheritance: A ToggleButton is a Button
public class ToggleButton extends Button implements ActionListener {
private String label1; // Two Labels to toggle between
private String label2;
Invoke Button’s constructor to set initial label
public ToggleButton (String l1, String l2) { // Constructor method
super(l1); // Use l1 as the default label
label1 = l1;
label2 = l2; A ToggleButton acts as its own ActionListener
addActionListener(this);
}

public void actionPerformed (ActionEvent e) { Each time a ToggleButton is


String tempS = label1; // Swap the labels clicked it swaps labels.
label1 = label2;
label2 = tempS;
setLabel (label1); Inheritance: setLabel() is inherited
} // actionPerformed()
} // ToggleButton
from Button superclass.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Using a ToggleButton
import java.applet.*;
import java.awt.*; This applet uses a ToggleButton.
import java.awt.event.*;

public class ToggleTest extends Applet implements ActionListener {


private ToggleButton lightSwitch;
Initialize the ToggleButton.
public void init() {
lightSwitch = new ToggleButton ("off","on");
add(lightSwitch);
lightSwitch.addActionListener(this); The applet is the listener.
} // init()

public void actionPerformed(ActionEvent e)


{
showStatus("The light is " + lightSwitch.getLabel());
} // actionPerformed()
} // ToggleTest The applet just displays
the button’s label.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Interacting Objects
• The ToggleButton has two ActionListeners,
itself and the applet.
The JVM calls
both
ActionListeners

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Java Library: Using Images in an Applet

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Using the java.awt.Image Class
Declare a reference
variable for each image.
import java.applet.*;
import java.awt.*;
Applet.getImage() loads the
public class Lights extends Applet images from GIF files.
{
private Image lightOn, lightOff; // Declare two Image variables

public void init() { GIF is a data


lightOn = getImage(getCodeBase(),"lighton.gif");
lightOff = getImage(getCodeBase(),"lightoff.gif"); format for
} // init() images.
public void paint (Graphics g) {
g.drawImage(lightOn, 10, 10, this); Draw the image in the
g.drawImage(lightOff, 70, 10, this); applet’s paint() method
} // paint()
} // Lights
drawImage(Image, x, y, ImageObserver) is part
of java.awt.Graphics.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
In the Laboratory: CyberPetApplet

The objectives of this lab are:


• To introduce the principles of writing a Java
applet.
• To introduce some of the basic GUI
Components.
• To give additional practice using the if and
if-else control structures.
• To introduce the Image object (optional)

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
In the Laboratory: CyberPetApplet
Problem Statement
Extend the CyberPet and CyberPetApplet by
adding a third state to the pet simulation -- for
example, thinking. The applet GUI should
continue to display the CyberPet’s name and
state. An image can be used to depict the state.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Technical Terms
• abstract class
• abstract interface
• abstract method
• applet
• Application Programming Interface (API)
• event-driven programming
• Graphical User Interface (GUI)
• import declaration
• inheritance
• inheritance hierarchy
• interface
• polymorphic method
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Summary Of Important Points
• An applet is an embedded  program that runs
within the context of a Web browser.
• The Java Application Programming Interface
(API) is a set of predefined classes that can be
used to write programs.
• A Graphical User Interface (GUI) enables the
user to interact with a program via graphical
elements such as windows, button, menus and so
on. Java's GUI components are defined in the
Abstract Windowing Toolkit (AWT) package.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Summary of Important Points (cont)
• The import statement is used to import definitions
of predefined classes into a Java program.
• The extend  keyword is used to define a class's
pedigree  -- its place in the Java class hierarchy.
• A class that extends another class is said to be a
subclass of that class which is its superclass.
• A subclass inherits the public and protected
methods and fields (variables) of its superclasses.
• Methods defined in a class’s superclasses can be
overridden  in the subclass by defining a method
with the same signature -- same name, return type,
and same number and type of parameters.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Summary of Important Points (cont)
• A method that behaves differently for different
objects is said to be polymorphic.
• The Applet.init() method is an example, since it is
redefined in all of Applet subclasses.
• Applets are event-driven: they react to certain
events.
• An Event object records specific information about
a particular event.
• Clicking on a Button in an applet generates an
ACTION_EVENT which should be handled by an
actionPerformed() method.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets
Summary of Important Points (cont)
• A Label is a GUI component that displays a single
line of uneditable text on the applet. A Button is a
labeled GUI component that is used to trigger
some kind of action when clicked. A TextField is
a GUI component that displays a single line of
editable text. The setText() and getText() methods
can be used to set a Button's label or a TextField's
text.
• The default layout pattern for Java applets is the
FlowLayout.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 4: Applets

S-ar putea să vă placă și