Top Banner
JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation slides for published by Prentice Hall Second Edition
62

JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

Jan 19, 2018

Download

Documents

Jason Hensley

Java, Java, Java, 2E by R. Morelli Copyright All rights reserved. Chapter 4: Applets 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).
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

JAVA, JAVA, JAVAObject-Oriented Problem Solving

Ralph MorelliTrinity CollegeHartford, CT

presentation slides for

published by Prentice Hall

Second Edition

Page 2: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

Java, Java, JavaObject Oriented Problem Solving

Chapter 4 Applets:Programming for the

World Wide Web

Page 3: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

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).

Page 4: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Page 5: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

Page 6: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Page 7: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Applications vs. Applets

Java Applications• Stand-alone program• Runs independently• Has a main() method• No HTML file• Run using JDK’s java

interpreter

Java Applets• Embedded program.• Runs in a Web browser• No main() method.• Requires an HTML file• Run using JDK’s

appletviewer

Page 8: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

The HelloWorld Application

/* * The HelloWorld application program */

public class HelloWorld // Class header{ // Start of class body

public static void main(String argv[]) // Main method { System.out.println("Hello world!"); } // End of main

} // End of HelloWorld

Multi-linecomment block

Single-line comments

Execution starts on the first line of main()

Page 9: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

The HelloWorld Applet

/* * HelloWorld applet program */

import java.applet.Applet; // Import the Applet classimport java.awt.Graphics; // and the Graphics class

public class HelloWorld extends Applet // Class header{ // Start of body

public void paint(Graphics g) // The paint method { g.drawString("HelloWorld",10,10); } // End of paint

} // End of HelloWorld This statement displays “HelloWorld” on the browser window.

Page 10: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Editing, Compiling, and Running

Page 11: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Running a Java Applet

• Running an applet requires an HTML file containing an <applet> tag:

•Running an applet requires an HTML file containing an <applet> tag:

• JDK Command: appletviewer file.html• Browser: Open the applet’s HTML file

<HTML>...<APPLET CODE=“HelloWorld.class” WIDTH=200 HEIGHT=200></APPLET>...</HTML>

Page 12: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Running a HelloApplet

Try running HelloApplet

Page 13: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

The java.applet.Applet ClassApplet’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.

Page 14: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

An Applet isa Panel which isa Container which isa

Component

By default, applets use a FlowLayout.

Page 15: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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 ContainerComponent comp = p; // Valid: A Panel is a ComponentObject o = p; // Valid: A Panel is an Object

Container c = new Container();Panel p = c; // Invalid: A container is

// not necessarily a Panel

Page 16: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Page 17: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

Subclasses inherit getCreditCardNumber()

and add their own special methods.

Methods in the superclass can be shared by the

subclasses.

Page 18: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

Page 19: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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 { protected double length; protected double width;

public Rectangle (double l, double w) { length = l; width = w; } // Rectangle()

public double calculateArea() { return length * width; } // calculateArea()} // Rectangle

public class Square extends Rectangle { public Square (double side) { //Call the superconstructor super(side, side); }} // Square

The super keyword refers to the superclass.

The Square() constructor calls the Rectangle()

constructor, passing it side as a value for both length

and width.

Page 20: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Using the Square Class

public class TestSquare{ public static void main(String argv[]) { Square square = new Square (10); System.out.println("square's area is " + square.calculateArea()); }} // TestSquare

The inherited calculateArea() method can be used just as if

it were defined in Square.

Create a new Square with a side of 10.

Output Produced

square’s area is 100.0

Page 21: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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”

Page 22: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

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

public class SimpleApplet extends Applet { ... } // Define subclass SimpleApplet myApplet = new SimpleApplet(); // and instantiate it

• The Applet class cannot be instantiated.

Page 23: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

A Simple Applet

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.

• SimpleApplet inherits from Applet and implements the ActionListener interface.

Page 24: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Java Definition of SimpleAppletimport java.applet.*;import java.awt.*;import java.awt.event.*;

public class SimpleApplet extends Applet implements ActionListener { private Button toggle; // From java.awt.*

public void init() { toggle = new Button ("The machine is off"); toggle.addActionListener(this); add(toggle); } // init()

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

Import class names

Create a subclass

Execution begins here

The applet handles button clicks

Called when toggle is clicked.

Page 25: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

SimpleApplet Inherits Functionality

Override: This init() overrides the init()

method inherited fromjava.applet.Applet

Implement: This actionPerformed() is

implemented according to the definition inherited fromActionListener interface

Use: A SimpleApplet can use the add() method inherited from java.awt.Container.

Page 26: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

Page 27: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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 (){ toggle = new Button ("The machine is off"); toggle.addActionListener(this); add(toggle);} // init()

Create a new Button.

This applet will listen for button clicks.

The add() method, inherited from Container, puts the button in the applet.

Page 28: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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);}

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()

• The implementation must have the exact same signature.

Page 29: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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).

Page 30: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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 foodp1 = new CyberCat();p1.eat(); // Eats cat food

Page 31: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

The Polymorphic init() Method

Applet applet= new AppletA();applet.init(); // Prints “AppletA”applet = new AppletB();applet.init(); // Prints “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”); }}

• Polymorphism: The init() method has different behavior for AppletA and AppletB.

Page 32: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Event-Driven Programming

Events are triggered by user actions

(mouse, keyboard).

Events are handled by methods in the applet.

Java’s Event Model

Page 33: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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 mouse event occurs when the mouse is moved.

An key event occurs when the user types a key.

Page 34: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

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

Creating an ActionListener

After this applet is designated as a

ActionListener for the toggle Button...

… it listens for clicks on toggle.

The this keyword is self-referential. It’s like saying “I”.

Page 35: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Handling Action Events

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

public class SimpleApplet extends Applet implements ActionListener { private Button toggle; // From java.awt.*

public void init() { toggle = new Button ("The machine is off"); toggle.addActionListener(this); add(toggle); } // init()

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"); else // or toggle.setLabel("The machine is on"); // change it back } // actionPerformed()} // SimpleApplet

1. Applet subclass implements the ActionListener interface

2. Declare a Button instance.

3. Create a Button instance.

4. Designate this applet as the button’s listener.

5. Add the button to the applet.

6. Define the specific actions to be performed when the button is

clicked..

Page 36: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

Page 37: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

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(); // kill the applet }

Create an instance of the applet.

Repeatedly pass events that belong to the applet to its actionPerformed()

method.

Page 38: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Tracing the Applet

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

public class SimpleApplet extends Applet implements ActionListener { private Button toggle; // From java.awt.*

public void init() { toggle = new Button ("The machine is off"); toggle.addActionListener(this); add(toggle); } // init()

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

The order in which applet statements are executed when the user makes two successive clicks

on its toggle button.

The applet is initialized.123

The user clicks on the button.First Click Second Click 4 7 5 8 6 9

Page 39: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

Page 40: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

CyberPetApplet’s GUI Interface

Page 41: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

CyberPetApplet: Design Specification

Uses

Page 42: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Defining CyberPetApplet

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

public class CyberPetApplet extends Applet implements ActionListener{} // CyberPetApplet

Step 1. Define a subclass of java.applet.Applet that implements the

ActionListener interface.

Page 43: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Defining CyberPetApplet (cont.)

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

Step 2. Declare the instance variables.

Stub version of init()

Page 44: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Defining CyberPetApplet (cont.)

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()

Step 3. Define the init() method.

Page 45: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

Page 46: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Interacting Objects

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

Page 47: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Defining CyberPetApplet (cont.)

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

Step 4. Implement the actionPerformed() method.

The getSource() method returns the source of the

ActionEvent.

Page 48: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

The CyberPetApplet Program

Page 49: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

Page 50: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Page 51: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.*;

public class ToggleButton extends Button implements ActionListener { private String label1; // Two Labels to toggle between private String label2;

public ToggleButton (String l1, String l2) { // Constructor method super(l1); // Use l1 as the default label label1 = l1; label2 = l2; addActionListener(this); }

public void actionPerformed (ActionEvent e) { String tempS = label1; // Swap the labels label1 = label2; label2 = tempS; setLabel (label1); } // actionPerformed()} // ToggleButton

Inheritance: A ToggleButton is a Button

Invoke Button’s constructor to set initial label

A ToggleButton acts as its own ActionListener

Each time a ToggleButton is clicked it swaps labels.

Inheritance: setLabel() is inherited from Button superclass.

Page 52: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Using a ToggleButton

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

public class ToggleTest extends Applet implements ActionListener { private ToggleButton lightSwitch;

public void init() { lightSwitch = new ToggleButton ("off","on"); add(lightSwitch); lightSwitch.addActionListener(this); } // init()

public void actionPerformed(ActionEvent e) { showStatus("The light is " + lightSwitch.getLabel()); } // actionPerformed()} // ToggleTest

This applet uses a ToggleButton.

Initialize the ToggleButton.

The applet is the listener.

The applet just displays the button’s label.

Page 53: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Page 54: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Java Library: Using Images in an Applet

Page 55: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Using the java.awt.Image Class

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

public class Lights extends Applet{ private Image lightOn, lightOff; // Declare two Image variables

public void init() { lightOn = getImage(getCodeBase(),"lighton.gif"); lightOff = getImage(getCodeBase(),"lightoff.gif"); } // init()

public void paint (Graphics g) { g.drawImage(lightOn, 10, 10, this); g.drawImage(lightOff, 70, 10, this); } // paint()} // Lights

Declare a reference variable for each image.

Applet.getImage() loads the images from GIF files.

GIF is a data format for images.

Draw the image in the applet’s paint() method

drawImage(Image, x, y, ImageObserver) is part of java.awt.Graphics.

Page 56: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

In the Laboratory: CyberPetApplet

• 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)

The objectives of this lab are:

Page 57: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

Page 58: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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

Page 59: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

Page 60: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

Page 61: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.

Page 62: JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation…

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.