Objects at their best l.jpg
This presentation is the property of its rightful owner.
Sponsored Links
1 / 120

Objects At their Best PowerPoint PPT Presentation


Objects At their Best Introduction to Applet Programming and Java’s Abstract Window Toolkit http://www.sci.brooklyn.cuny.edu/~arnow/ Gerald Weiss and David Arnow Department of Computer and Information Science Brooklyn College, City University of New York The Abstract Window Toolkit (AWT)

Download Presentation

Objects At their Best

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Objects at their best l.jpg

Objects At their Best

Introduction to Applet Programming

and

Java’s Abstract Window Toolkit

http://www.sci.brooklyn.cuny.edu/~arnow/

Gerald Weiss and David Arnow

Department of Computer and Information Science

Brooklyn College, City University of New York

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The abstract window toolkit awt l.jpg

The Abstract Window Toolkit (AWT)

  • Supports GUI

  • Offers a set of classes

    • packages java.awt, java.applet, ...

    • no new Java

  • Forms a framework for writing

    • stand-alone graphic applications

    • applets

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Gui in action l.jpg

interrupt

Event notification

button object

textfieldobject

Event handling object

val++;

update textfield

Native OS Environment

Java AWT Environment

GUI In Action

The native OS displays our GUI controls; but there must be some connection to our Java code

The native OS receives an interrupt from mouse click; but there must be a Java object, modeling the button, to receive the interrupt from the OS.

The button object should not be responsible for handling the addition; that is the job of a separate, event handling object

How does the button object know the identity of the event handling object (how does it know whom to notify of events)?

How does the event object know what event occured?

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


What gui support entails l.jpg

What GUI Support Entails

  • Windows, Controls, Graphics (“Doodles”)

  • Articulation with

    • application code

    • external environment

  • Layout

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Gui tasks and issues l.jpg

GUI Tasks and Issues

  • Control creation

  • Control positioning

  • Responding to events

  • Maintaining the display

  • Components vs “Doodles”

    • Component objects: buttons, text fields: Java objects

    • Graphic “objects”: ovals, lines— drawn, passive doodles

  • Initialization vs. Ongoing Execution

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Applets l.jpg

Applets

  • Code referenced in web page

  • Downloaded by browser

  • Executes within a browser’s GUI context

    • Portion of pre-existing window

    • Executes as threads within browser process

    • No main! Must provide hooks for browser

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Life cycle of an applet l.jpg

Life Cycle of An Applet

  • Initialization

    • Control creation and placement

    • Initialize event handling

    • Method: init()

  • Ongoing Execution

    • Event handling

    • Maintenance of display— “doodles”

    • Methods: paint() + various event handlers

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Applet class default behavior l.jpg

Applet Class (Default) Behavior

  • Control creation: none

  • Control placement: none

  • Event handling: none

  • Display maintenance: dull gray

    Programmer Task: Extend Applet Class

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


A sample applet basicelements l.jpg

A Sample Applet: BasicElements

Not your default Applet behavior

Must extend Applet class

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Extending the applet class 1 l.jpg

Extending The Applet Class (1)

import java.awt.*;

import java.applet.*;

public class BasicElements extends Applet {

public void init() { … }

public void paint(Graphics g) { … }

// event-handling code

// instance variables

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Overriding init control creation and placement l.jpg

Overriding init:Control Creation and Placement

public void init() {

Button red = new Button("red");

Button green = new Button("green");

Label textlabel = new Label("(oval/rect)");

TextField shapeSpec = new TextField("oval");

add(red);

add(green);

add(textlabel);

add(shapeSpec);

...

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Event handling l.jpg

Event Handling

  • The applet must be notified of events:

    • example: a button is clicked

  • Three objects of interest:

    • The event source – the object causing the event (e.g., a button)

    • The event - represented by an object

    • The listener - our applet — must react in some way

  • Source notifies the listener

    • sends message with event object as argument

      • Particular message is specified in an interface

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Is anyone listening l.jpg

Button

Event

BasicElements

event source

listener

Is Anyone Listening?

  • Our applet must implement the listener interface, particular to the event.

  • Event source must know who is listening:

    • registration

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Overriding init listener registration l.jpg

Overriding init:Listener Registration

public void init() {

red = new Button("red");

green = new Button("green");

Label textlabel = new Label("(oval/rect)");

shapeSpec = new TextField("oval");

add(red);

add(green);

add(textlabel);

add(shapeSpec);

red.addActionListener(this);

green.addActionListener(this);

...

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Extending the applet class 2 l.jpg

Extending The Applet Class (2)

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class BasicElements extends Applet

implements ActionListener {

public void init() { … }

public void paint(Graphics g) { … }

public void actionPerformed(ActionEvent e) { … }

// instance variables

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Maintaining the display l.jpg

Maintaining the Display

  • Applet's paint method: paint(Graphics g)

    • Draws an empty gray box

    • Invoked as needed

      • By environment

      • Programmatically

  • To get USEFUL paint behavior:

    • Override Applet’s paint method

    • Applet is responsible for “Doodles” only!

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Components vs doodles l.jpg

Components vs “Doodles”

  • Components

    • Objects— independent of applet

      • Possess behavior

      • RESPONSIBLE FOR THEIR OWN DISPLAY

      • Require placement on applet

  • “Doodles”

    • Stuff WE draw directly on surface

    • No behavior!

      • OUR APPLET RESPONSIBLE FOR THEIR DISPLAY

    • Text is a “doodle” too

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Graphic behavior the graphics class l.jpg

Graphic Behavior:The Graphics Class

  • Provides drawing and other graphic behavior

    • drawRect/fillRect

    • drawOval/fillOval

    • setColor

  • Shields programmer from device dependencies

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Overriding paint drawing the doodles l.jpg

Overriding paint:Drawing the doodles

public void paint(Graphics g) {

setBackground(Color.black);

g.setColor(Color.black);

g.fillOval(5,5,80,80);

g.fillRect(5,5,80,80);

g.setColor(currentColor);

if (shapeSpec.getText().equals("oval"))

g.fillOval(5,5,80,80);

else

g.fillRect(5,5,80,80);

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Back to events actionperformed method l.jpg

Back to events:actionPerformed method

  • Promised by actionListener interface

    public void actionPerformed(ActionEvent e) {

    if (e.getSource()==red)

    currentColor = new Color(255,0,0);

    else

    currentColor = new Color(0,255,0);

    repaint();

    }

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Needed instance variables l.jpg

Needed: Instance Variables

public class BasicElements extends Applet implements ActionListener {

public void init() { … }

public void paint(Graphics g) { … }

public void actionPerformed(ActionEvent e) { … }

Button red, green;

TextField shapeSpec;

Color currentColor;

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Overriding init initializing currentcolor l.jpg

Overriding init:Initializing currentColor

public void init() {

red = new Button("red");

green = new Button("green");

Label textlabel = new Label("(oval/rect)");

shapeSpec = new TextField("oval");

add(red);

add(green);

add(textlabel);

add(shapeSpec);

red.addActionListener(this);

green.addActionListener(this);

currentColor = new Color(255,0,0);

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The basicelements applet l.jpg

The BasicElements Applet

public void paint(Graphics g) {

setBackground(Color.black);

g.setColor(Color.black);

g.fillOval(5,5,80,80);

g.fillRect(5,5,80,80);

g.setColor(currentColor);

if ( shapeSpec.getText(). equals("oval"))

g.fillOval(5,5,80,80);

else

g.fillRect(5,5,80,80);

}

public void actionPerformed

(ActionEvent e) {

if (e.getSource()==red)

currentColor =

new Color(255,0,0);

else

currentColor =

new Color(0,255,0);

repaint();

}

Button red, green;

TextField shapeSpec;

Color currentColor;

}

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class BasicElements extends Applet implements ActionListener {

public void init() {

red = new Button("red");

green = new Button("green");

Label textlabel = new Label("(oval/rect)");

shapeSpec = new TextField("oval");

add(red);

add(green);

add(textlabel);

add(shapeSpec);

red.addActionListener(this);

green.addActionListener(this);

currentColor = new Color(255,0,0);

setBackground(Color.black);

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Running an applet l.jpg

Running an Applet

  • Compile

  • Move class files as needed

  • Create HTML file with class file reference

    <APPLET CODE="BasicElements.class"

    WIDTH=250 HEIGHT=100>

    </APPLET>

  • Access HTML file using

    • browser

    • Appletviewer

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Using basicelements applet what s the problem l.jpg

Using BasicElements Applet:What's The Problem?

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Wanted component for drawing l.jpg

Wanted: Component for Drawing

  • Our doodles

    • Should not occlude buttons, text areas etc

    • Should not be occluded by buttons, text areas etc

  • Need Component:

    • Provides drawing surface

    • Can be placed along with buttons, text areas, etc.

    • Solves occlusion problem

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Improving basicelements canvas l.jpg

Improving BasicElements: Canvas

  • The add method:

    • Places components

    • NEVER on top of each other

  • Canvas: a component class for doodling!

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


General strategy for using canvas l.jpg

General Strategy For Using Canvas

  • Extend Canvas class: MyCanvas

  • Move drawing to MyCanvas

  • Move appropriate event-handling to MyCanvas

  • Applet's init creates and adds

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Mycanvas overview l.jpg

MyCanvas: Overview

class MyCanvas extends Canvas implements ActionListener {

// constructor ???

public void paint(Graphics g) {

// just like earlier paint method of applet

}

public void actionPerformed(ActionEvent e) {

// just like earlier actionPerformed method of applet

}

// instance variables ???

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Mycanvas paint l.jpg

MyCanvas: paint

public void paint(Graphics g) {

setBackground(Color.black);

g.setColor(Color.black);

g.fillOval(5,5,80,80);

g.fillRect(5,5,80,80);

g.setColor(currentColor);

if (shapeSpec.getText().equals("oval"))

g.fillOval(5,5,80,80);

else

g.fillRect(5,5,80,80);

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Mycanvas actionperformed l.jpg

MyCanvas: actionPerformed

public void actionPerformed(ActionEvent e) {

if (e.getSource()==red)

currentColor = new Color(255,0,0);

else

currentColor = new Color(0,255,0);

repaint();

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Mycanvas instance variables l.jpg

MyCanvas: Instance Variables

class MyCanvas extends Canvas implements ActionListener {

// constructor ???

public void paint(Graphics g) {

// requires shapeSpec, currentColor

}

public void actionPerformed(ActionEvent e) {

// requires red, green, currentColor

}

// instance variables

Button red, green;

TextField shapeSpec;

Color currentColor;

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Mycanvas constructor l.jpg

MyCanvas: Constructor

public MyCanvas(Button red, Button green,

TextField shapeSpec) {

super();

this.shapeSpec = shapeSpec;

this.red = red;

this.green = green;

red.addActionListener(this);

green.addActionListener(this);

currentColor = new Color(255,0,0);

setBackground(Color.black);

setSize(100,100);

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Improved applet betterbasicelements l.jpg

Improved Applet: BetterBasicElements

public class BetterBasicElements extends Applet {

public void init() {

Button red = new Button("red");

Button green = new Button("green");

Label textlabel = new Label("(oval/rect)");

TextField shapeSpec = new TextField("oval");

MyCanvas mycanvas = new MyCanvas(red,green,shapeSpec);

add(red);

add(green);

add(textlabel);

add(shapeSpec);

add(mycanvas);

setBackground(Color.black);

}

// NOTHING ELSE! (in this case)

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Placing controls l.jpg

Placing Controls

  • Control not visible or usable until PLACED in the applet

  • Carried out in init, after creation

  • Accomplished using the add method

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Components and containers l.jpg

Components and Containers

  • Components

    • controls, canvas, applet

    • NOT doodles

  • Container

    • a component on which other components are placed

    • purpose: support positioning of components

    • example: an Applet!

  • Components are not visible or usable until PLACED in a container

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The add method l.jpg

The add Method

  • Inherited from Container class

    • Therefore a method of Applet

  • Places a component onto the container

  • A container often sends the add message to itself:

    Button b = new Button("OK");

    this.add(b);

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Layoutmanager objects l.jpg

LayoutManager Objects

  • Used by containers to position their components.

  • LayoutManager: an interface

    • specifies methods invoked by containers’ add method

  • Implementations of LayoutManager differ in

    • ways of laying out components

    • degree of programmer control

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Two layout managers l.jpg

North

West

Center

East

South

Two Layout Managers:

  • FlowLayout

    • Components laid out left to right

  • BorderLayout

    • Defines 5 regions:

      • North South East West Center

      • Component can be placed in any region

      • 5 Components at most!

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Using layout managers setlayout method l.jpg

Using Layout Managers: setLayout method

  • Method of Container class

    • Inherited by Applet

    • Inherited by your subclass

  • Specifies layout manager:

    prototype:setLayout(LayoutManager)

    example:setLayout(new FlowLayout())

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Add method l.jpg

add method

  • Method of Container class

    • Inherited by Applet

    • Inherited by your subclass

  • Adds component to the receiving container:

    add(Component, other arguments)

    • Delegates actual placement to container's layout manager

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Panel class l.jpg

Panel Class

  • Container class

  • Sole purpose:

    • group components

    • apply LayoutManager to its components independently of rest of applet

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Using panels l.jpg

Using Panels

  • Strategy:

    • divide applet's real estate into different Panels

    • add components to the Panel objects

    • send setLayout message to each Panel object

  • Panels within Panels

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Using panels bestbasicelements l.jpg

Using Panels: BestBasicElements

public class BestBasicElements extends Applet {

public void init() {

// create controls as before

Panel buttonGroup = new Panel();

// add buttons to buttonGroup

Panel textGroup = new Panel();

// add textfield and label to textGroup

// add buttonGroup, canvas, textGroup to applet

// set everyone's background color

}

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Using panels bestbasicelements45 l.jpg

Using Panels: BestBasicElements

public void init() {

// create controls as before

Panel buttonGroup = new Panel();

buttonGroup.setLayout(new BorderLayout(2,2));

buttonGroup.add("North", red);

buttonGroup.add("South", green);

Panel textGroup = new Panel();

textGroup.setLayout(new BorderLayout(0,0));

textGroup.add("North", textlabel);

textGroup.add("South", shapeSpec);

add(buttonGroup);

add(textGroup);

add(mycanvas);

// set everyone's background color

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Using panels bestbasicelements46 l.jpg

Using Panels: BestBasicElements

public class BestBasicElements extends Applet {

public void init() {

...

buttonGroup.setBackground(Color.black);

textGroup.setBackground(Color.black);

red.setBackground(Color.red);

green.setBackground(Color.green);

textlabel.setBackground(Color.white);

shapeSpec.setBackground(Color.white);

setBackground(Color.black);

}

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Using panels bestbasicelements47 l.jpg

Using Panels: BestBasicElements

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Calculator layout same strategy l.jpg

Calculator Layout: Same Strategy

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Gui ain t just buttons l.jpg

GUI Ain’t Just Buttons

  • Other components:

    • Text fields

    • Windows

  • Associated with different events

    • Changing text

    • Closing a window

  • Different events, different Event classes

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Event summary l.jpg

Event Summary

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Event classes l.jpg

Event Classes

  • Each Event class is associated with

    • One or more component classes

      • event source

    • A listener interface

      • Implemented by event handler (listener) class

    • A registration method

      • allows listener to register with the event source

      • defined in component class (event source)

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Java event naming conventions l.jpg

Java Event Naming Conventions

  • Event classes

    • EventTypeEvent

    • Example: TextEvent, ActionEvent

  • Listener interfaces

    • EventTypeListener

    • Example: TextListener, ActionListener

  • Listener registration method

    • addEventTypeListener or setEventTypeListener

    • Example: addTextListener, addActionListener

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Listener interfaces l.jpg

Listener Interfaces

  • Contain methods invoked by the event source

  • No strict naming conventions

  • Single method (often)

    • Example: textValueChanged, actionPerformed

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Bestbasicelements with textevents l.jpg

BestBasicElements With TextEvents

  • Responds immediately to changes in text field

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Bestbasicelements with textevents55 l.jpg

BestBasicElements With TextEvents

  • Canvas must

    • LISTEN for:

      • ActionEvents (as before)

      • TextEvents (new)

    • REGISTER with

      • Buttons (as before)

      • TextField (new)

    • IMPLEMENT:

      • Interface ActionListener (as before): actionPerformed

      • Interface TextListener (new): textValueChanged

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Mycanvas with textevents l.jpg

MyCanvas With TextEvents

class MyCanvas extends Canvas

implements ActionListener, TextListener {

public MyCanvas(•••) {

•••

green.addActionListener(this);

shapeSpec.addTextListener(this);

•••

}

public void paint(Graphics g) { ••• }

public void actionPerformed(ActionEvent e) { ••• }

public void textValueChanged(TextEvent e) {

if (shapeSpec.getText().equals("oval") ||

shapeSpec.getText().equals("rect"))

repaint();

}

// instance variables •••

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Listener interfaces with multiple methods l.jpg

Listener Interfaces WithMultiple Methods

  • Some listener interfaces have multiple methods

    • Example: MouseListener

      • mouseClicked, mouseEntered, mouseExited, mousePressed, mouseReleased

  • Often the event handler is interested in only one

    • mouseClicked

  • What a pain!

    • We want one method

    • Gotta implement five ???

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Pain reliever adapter classes l.jpg

Pain Reliever: Adapter Classes

  • Java supplies adapter classes for such interfaces.

    class MouseAdapter implements MouseListener {

    public void mouseClicked(MouseEvent e) { }

    public void mouseEntered(MouseEvent e) { }

    public void mouseExited(MouseEvent e) { }

    public void mousePressed(MouseEvent e) { }

    public void mouseReleased(MouseEvent e) { }

    }

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Using the adapter class l.jpg

Using the Adapter Class

  • Event handler can now inherit from this class

    • just implement desired method (mouseClicked):

      class MyMouseHandler extends MouseAdapter {

      public void mouseClicked(MouseEvent e) {

      // handle mouse click

      }

      }

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The model view controller paradigm l.jpg

The Model-View-Controller

Paradigm

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


A counter applet l.jpg

A Counter Applet

  • Two buttons

  • Value field

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The counterapplet class l.jpg

The CounterApplet Class

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class CounterApplet extends Applet

implements ActionListener {

public void init() {…}

public void actionPerformed(ActionEvent e) {…}

Button incButton, decButton;// Instance variables

TextField valField;

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The init method l.jpg

The init Method

public void init() {

incButton = new Button("+");// Create Controls

decButton = new Button("-");

valField = new TextField();

valField.setText("0");

Panel p = new Panel();// Lay them out

p.setLayout(new BorderLayout());

p.add(incButton, "North");

p.add(decButton, "South");

add(p);

add(valField);

// Register as listener

incButton.addActionListener(this);

decButton.addActionListener(this);

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The actionperformed method l.jpg

The actionPerformed Method

public void actionPerformed(ActionEvent e) {

// Retrieve text field

int val = Integer.parseInt(valField.getText());

if (e.getSource() == incButton)

val++;

else

val--;

// Update text field

valField.setText(Integer.toString(val));

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


An unexpected benefit bug l.jpg

An Unexpected Benefit (Bug?)

  • Can directly modify the counter value through the TextField

    • We’re using the contents of the TextField as our counter value.

      We’ll call it a feature

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Concern i l.jpg

Concern I

  • CounterApplet is modeling too many things:

    • General behavior of an applet (inherited from Applet)

    • GUI of our particular application

      • Display of the two buttons and the text field

      • Role as listener to the two buttons

    • Behavior of an up/down counter

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Concern ii l.jpg

Concern II

  • The counter logic is all over the place

    • Initialization is in applet’s init method

    • Maintenance logic is in actionPerformed

  • No real counter value

    • "maintained" indirectly as a string in a text field

  • Makes it difficult to understand and maintain

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Concern iii l.jpg

Concern III

  • What if we want

    • a Scrollbar rather than a pair of Buttons

    • a Label rather than a TextField?

  • Requires changing the "counter" logic

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Good interface design l.jpg

Good Interface Design

  • Separate interface from application:

    • Interface: should not affect application logic

    • Application: should not know about interface.

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Revising the counter applet l.jpg

Revising the Counter Applet

  • Have a Counter class

    • Encapsulate application logic of up/down counter

  • The CounterApplet class then uses the Counter class.

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The counter class l.jpg

The Counter Class

public class Counter {

public Counter(int max) {this.max = max;}

public void reset() {val = 0;}

public int getVal() {return val;}

public void setVal(int val) {

if (val >= 0 && val <= max)

this.val = val;

}

public void inc() {if (val < max) val++;}

public void dec() {if (val > 0) val--;}

private int max, val=0;// Instance variables

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The counterapplet class72 l.jpg

The CounterApplet Class

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class CounterApplet extends Applet implements ActionListener {

public void init() {…}

public void actionPerformed(ActionEvent e) {…}

Button incButton, decButton;// Instance variables

TextField valField;

Counter ctr;

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The init method73 l.jpg

The init Method

public void init() {

ctr = new Counter(10);

incButton = new Button("+");

decButton = new Button("-");

valField = new TextField();

valField.setText(Integer.toString(ctr.getVal()));

Panel p = new Panel();

p.setLayout(new BorderLayout());

p.add(incButton, "North");

p.add(decButton, "South");

add(p);

add(valField);

incButton.addActionListener(this);

decButton.addActionListener(this);

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The actionperformed method74 l.jpg

The actionPerformed Method

public void actionPerformed(ActionEvent e) {

if (e.getSource() == incButton)

ctr.inc();

else

ctr.dec();

valField.setText(Integer.toString(ctr.getVal));

}

  • The event handler for the Button invokes the appropriate counter method and updates the TextField.

  • We no longer use the TextField for the counter value.

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Better applet but l.jpg

Better Applet, but...

  • actionPerformed still responsible for updating the textField.

  • What if we decide to change the TextField to a

    • Label?

    • A Scrollbar

    • A gauge?

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


One possible approach l.jpg

One Possible Approach

  • We could isolate the display update logic into a helper method that can be called from anywhere.

  • However, the CounterApplet still has to know WHEN the Counter has changed.

  • We will try something a bit different.

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Model view controller mvc l.jpg

Model-View-Controller (MVC)

  • Separates application, user input, and display logics.

  • Makes for an exceptionally clean design

  • Minimal coupling between interface and application

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Model l.jpg

Model

  • Application

  • Interface-independent

  • Examples

    • Spreadsheet data

    • Counter class

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Slide79 l.jpg

View

  • Display

  • Responsible for maintaining an updated view of the model

  • Must be notified of changes to the model.

  • Examples

    • graph, matrix

    • TextField update

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Controller l.jpg

Controller

  • Input

  • Often initiates changes to the model.

  • Examples

    • keyboard, mouse

    • actionPerformed

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Document view l.jpg

Document-View

  • Often easier to combine view and controller.

  • Sometimes known as document-view.

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Model as observed l.jpg

Model as Observed

  • Must notify view when changes happen

  • Model must know:

    • Who is the view?

    • How to notify the view of the change?

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Symmetric with event handling l.jpg

Symmetric with Event Handling

View notification

  • Who is the view?

  • How to notify view?

Event Handling

  • Who is the listener?

  • How to notify listener?

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


View as observer l.jpg

View as Observer

  • Who is the view?

    • View registers with the model

  • How to notify view that change happened?

    • View implements an "observer" interface

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The symmetry continues l.jpg

The Symmetry Continues

View notification

  • View registers with model

  • View implements observer interface

Event Handling

  • Listener registers with event source

  • Listener implements listener interface

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The counter applet using mvc l.jpg

The Counter Applet Using MVC

  • class Counter— Model

  • class CounterApplet — View/Controller

  • interface CounterObserver — observer interface

    • developed for our applet— not predefined

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counterobserver interface l.jpg

CounterObserver Interface

  • Implemented by view to ‘listen’ for model changes

  • Single method with the Counter as a parameter.

  • When invoked allows view to be updated.

    interface CounterObserver {

    public void counterHasChanged(Counter ctr);

    }

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counter class overview l.jpg

Counter Class Overview

  • Same basic functionality, plus…

  • Maintains a CounterObserver as part of its state.

  • Provides observer registration method

    • registerAsObserver

  • Notifies observer of changes

    • Relies upon observer implementing CounterObserver

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counter class l.jpg

Counter Class

public class Counter {

public Counter(int max) {this.max = max;}

public void reset() {val = 0;}

public int getVal() {return val;}

// Manipulator methods-

// must notify observer the model has changed

public void setVal(int val) {…}

public void inc() {...}

public void dec() {...}

// Observer-related methods

public void registerAsObserver(CounterObserver observer){…}

private void notifyObserver() {...}

private int max, val=0;

CounterObserver observer;

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counter s manipulator methods l.jpg

Counter’s Manipulator Methods

public void setVal(int val) {

if (val >= 0 && val <= max) this.val = val;

notifyObserver();

}

public void inc() {

if (val < max) val++;

notifyObserver();

}

public void dec() {

if (val > 0) val--;

notifyObserver();

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counter s observer related methods l.jpg

Counter’s Observer-Related Methods

public void registerAsObserver(CounterObserver observer) {

this.observer = observer;

notifyObserver();// Allow initial display

}

private void notifyObserver() {

observer.counterHasChanged(this);

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counterapplet class overview l.jpg

CounterApplet Class Overview

  • Implements CounterObserver interface (view)

  • Registers with Counter during initialization (view)

  • Event-handlers invoke Counter methods but do not update view. (controller)

  • Updates TextField when counterHasChanged method is invoked. (view)

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counterapplet class l.jpg

CounterApplet Class

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class CounterApplet extends Applet

implements ActionListener,

CounterObserver {

public void init() {…}

public void actionPerformed(ActionEvent e) {…}

public void counterHasChanged(Counter ctr) {…}

Button incButton, decButton;

TextField valField;

Counter ctr;

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The init method94 l.jpg

The init Method

public void init() {

incButton = new Button("+");

decButton = new Button("-");

valField = new TextField();

Panel p = new Panel();

p.setLayout(new BorderLayout());

p.add(incButton, "North");

p.add(decButton, "South");

add(p);

add(valField);

incButton.addActionListener(this);

decButton.addActionListener(this);

ctr = new Counter(10);

ctr.registerAsObserver(this);

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The event handling methods l.jpg

The Event-Handling Methods

public void actionPerformed(ActionEvent e) {

if (e.getSource() == incButton)

ctr.inc();

else

ctr.dec();

}

  • The event handler simply initiates model changes

  • NOT responsible for the display!

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The counterhaschanged method l.jpg

The counterHasChanged Method

public void counterHasChanged(Counter ctr) {

valField.setText(Integer.toString(ctrVal));

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Now let s have some fun l.jpg

Now Let’s Have Some Fun!

  • We’ve shown you the basics of MVC

  • We’ve also claimed it results in a clean design

    • Model knows nothing of controller/view’s workings

  • All this leads to some very unexpected capabilities!

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counters l.jpg

Counters...

  • Two pairs of synchronized counters:

    • East/West

    • North/South

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Slide99 l.jpg

… Logs, ...

  • A logging facility in synch with the counters

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


And alarms l.jpg

… and Alarms

  • An alarm panel keeping track of the counter values

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Class overview l.jpg

Class Overview

  • Counter class: a model

    • same basic functionality, but ...

    • now allows multiple observers

  • CounterPanel class: a view and controller

    • creates our familiar counter GUI

    • observes the counter

    • similar structure to our previous CounterApplet class

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Class overview ii l.jpg

Class Overview (II)

  • CounterLogger: a view

    • prints out counter changes to System.out

    • observes the counter

    • maintains counter name

  • CounterAlarmPanel: a view

    • observes multiple counters

    • indicates movement past error threshold

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Class overview iii l.jpg

Class Overview (III)

  • CounterApplet

    • creates the various interface components

    • sits back and let’s them do all the work

  • CounterObserver interface

    • same as before

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counter class104 l.jpg

Counter Class

import java.util.*;

public class Counter {

public Counter(int max) {

this.max = max;

observers = new Vector();

}

public void reset() { /*Same as before*/ }

public int getVal() { /*Same as before*/ }

public void setVal(int val) { /*Same as before*/ }

public void inc() { /*Same as before*/ }

public void dec() { /*Same as before*/ }

public void registerAsObserver(CounterObserver observer){…}

private void notifyObservers() {…}

private int max, val=0;

Vector observers;// Allows multiple observers

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The registerasobserver method l.jpg

The registerAsObserver Method

  • observers are added to the Vector

    public void registerAsObserver(CounterObserver observer) {

    observers.addElement(observer);

    observer.counterHasChanged(this);

    }

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The notifyobservers method l.jpg

The notifyObservers Method

  • Notification involves enumerating through the Vector and notifying each observer

    private void notifyObservers() {

    Enumeration enum = observers.elements();

    while (enum.hasMoreElements()) {

    CounterObserver observer =

    (CounterObserver)enum.nextElement();

    observer.counterHasChanged(this);

    }

    }

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counterlogger class l.jpg

CounterLogger Class

class CounterLogger implements CounterObserver {

public CounterLogger(Counter ctr, String counterName) {

this.counterName = counterName;

ctr.registerAsObserver(this);// Observes counter

}

public void counterHasChanged(Counter ctr) {

System.out.println(counterName + " changed to " +

ctr.getVal());

}

private String counterName;// For id purposes

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counterpanel class l.jpg

CounterPanel Class

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class CounterPanel extends Panel

implements ActionListener,

CounterObserver {

public CounterPanel(Counter ctr) {…}

public void actionPerformed(ActionEvent e) {…}

public void counterHasChanged(Counter ctr) {…}

Button incButton, decButton;

TextField valField;

Counter ctr;

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counterpanel constructor l.jpg

CounterPanel Constructor

public CounterPanel(Counter ctr) {

incButton = new Button("+");

decButton = new Button("-");

valField = new TextField();

Panel p = new Panel();

p.setLayout(new BorderLayout());

p.add(incButton, "North");

p.add(decButton, "South");

add(p);

add(valField);

incButton.addActionListener(this);

decButton.addActionListener(this);

this.ctr = ctr;

ctr.registerAsObserver(this);

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The event handler method l.jpg

The Event-Handler Method

  • identical to before

    public void actionPerformed(ActionEvent e) {

    if (e.getSource() == incButton)

    ctr.inc();

    else

    ctr.dec();

    }

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The counterhaschanged method111 l.jpg

The counterHasChanged Method

  • Same as before

    public void counterHasChanged(Counter ctr) {

    valField.setText(Integer.toString(ctrVal));

    }

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counteralarmpanel class l.jpg

CounterAlarmPanel Class

import java.util.*;

import java.awt.*;

class CounterAlarmPanel extends Panel

implements CounterObserver {

public CounterAlarmPanel() {counters = new Vector();}

// add counter with error-threshold

void add(Counter ctr, int err) {…}

public void paint(Graphics g) {...}

public void counterHasChanged(Counter ctr) {…}

Vector counters;// counter/error-threshold pairs

}

  • Counter/error-threshold pairs maintained in helper class, CounterAlarm

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The add method113 l.jpg

The add Method

  • Creates a CounterAlarm object from the counter/error-threshold

  • Adds the CounterAlarm to the Vector

  • Registers as an observer of the Counter

    void add(Counter ctr, int err) {

    counters.addElement(new CounterAlarm(ctr, err));

    ctr.registerAsObserver(this);

    }

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The paint method l.jpg

The paint Method

  • Enumerates through the CounterAlarm Vector

    • Paints a green circle if below the threshold; a red one otherwise

      public void paint(Graphics g) {

      Enumeration e = counters.elements();

      int i = 0;

      while (e.hasMoreElements()) {

      CounterAlarm ctrAlarm =

      (CounterAlarm)e.nextElement();

      int ctrval = ctrAlarm.ctr.getVal();

      if (ctrval >= ctrAlarm.err)

      g.setColor(Color.red);

      else

      g.setColor(Color.green);

      g.fillOval(50+i*30, 30, 20, 20);

      g.setColor(Color.black);

      g.drawOval(50+i*30, 30, 20, 20);

      i++;

      }

      }

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


The counterhaschanged method115 l.jpg

The counterHasChanged Method

  • Merely causes a repaint

    public void counterHasChanged(Counter ctr) {

    repaint();

    }

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counterapplet class116 l.jpg

CounterApplet Class

import java.applet.*;

import java.awt.*;

public class CounterApplet extends Applet {

public void init() {

Counter ctr1 = new Counter(10);

CounterPanel cp1 = new CounterPanel(ctr1);

CounterPanel cp2 = new CounterPanel(ctr1);

Counter ctr2 = new Counter(5);

CounterPanel cp3 = new CounterPanel(ctr2);

CounterPanel cp4 = new CounterPanel(ctr2);

CounterAlarmPanel cpa = new CounterAlarmPanel();

cpa.add(ctr1, 8); cpa.add(ctr2, 4);

setLayout(new BorderLayout());

add(cp1, "North"); add(cp2, "South");

add(cp3, "East"); add(cp4, "West");

add(cpa, "Center");

CounterLogger cl = new CounterLogger(ctr1, "Counter1");

CounterLogger c2 = new CounterLogger(ctr2, "Counter2");

}

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Counteralarm class l.jpg

CounterAlarm Class

class CounterAlarm {

CounterAlarm(Counter ctr, int err) {

this.ctr = ctr;

this.err = err;

}

Counter ctr;

int err;

}

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Where do you go from here net resources l.jpg

Where Do You Go From Here?Net Resources

  • www.javasoft.com

    • Sun’s Java site

    • Join Java Developer’s Connection (JDC) - it’s free (actually it costs a cookie)

  • http://developer.netscape.com/

    • Netscape’s DevEdge Online

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Where do you go from here books l.jpg

Where Do You Go From Here?Books

  • core Java - Cornell & Horstmann, Prentice Hall

    • good technical Java material

  • Intro to OOP (Using Java) - Budd, Addison-Wesley

    • Has good handle on OOP

  • Practical OO Development in C++ and Java - Horstmann

    • Nice intro to both, good discussion of OO techniques (inheritance vs composition, class design, access control)

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


Where do you go from here development tools l.jpg

Where Do You Go From Here?Development Tools

  • Java Development Kit (JDK)

    • Sun’s product

    • Currently 1.2 beta, 1.1.7 product release

    • Free! www.javasoft.com (only 7M+ of download)

    • De Facto operational definition

  • Microsoft J++

  • CodeWarrior

  • Inprise (Borland) Jbuilder

Arnow and Weiss:

Objects At Their Best— Java's Abstract Window Toolkit


  • Login