Find the comp in each of these texts
This presentation is the property of its rightful owner.
Sponsored Links
1 / 107

FIND THE “ comp ” IN EACH OF THESE TEXTS PowerPoint PPT Presentation


  • 35 Views
  • Uploaded on
  • Presentation posted in: General

FIND THE “ comp ” IN EACH OF THESE TEXTS. alkdfjasdkasldkfjasdlkfjasdkfajsldfkajsldkfjalsdkfjadlfjkdffddfdfasldkfajsdlkfjasldkfjalsdkfjasldfjasldkfjasldkfjaldskjfalsdkjfalskdjfalskdjfalskdjfalksdjfwioer comp uqkeflaksdjfasldkfjasldkfjaslkdjfaiowejrwqeijrqwoejrqoiejfalskdfjaslkdfja.

Download Presentation

FIND THE “ comp ” IN EACH OF THESE TEXTS

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


Find the comp in each of these texts

FIND THE “comp” IN EACH OF THESE TEXTS

alkdfjasdkasldkfjasdlkfjasdkfajsldfkajsldkfjalsdkfjadlfjkdffddfdfasldkfajsdlkfjasldkfjalsdkfjasldfjasldkfjasldkfjaldskjfalsdkjfalskdjfalskdjfalskdjfalksdjfwioercompuqkeflaksdjfasldkfjasldkfjaslkdjfaiowejrwqeijrqwoejrqoiejfalskdfjaslkdfja

asdfasldkjfalsdfasdlkfjasdlfksdlfkjcompflsadf

HARD

EASY

`

This parallels debugging.


Importance of incremental coding

Importance of Incremental Coding

Incremental coding is the practice of testing small portions of your code as you are writing them.

Much easierto find bugs with less code to work with at any one time.

  • You will know exactly when your code stops working as intended.

  • The TAs will be much happier at hours.

    • The TAs will not help students track down extremely convoluted bugs that are a result of coding large portions without testing.


Importance of incremental coding1

Importance of Incremental Coding

For more information, see Lab2 (UMLet and Debugging part 1)

LiteBrite example:

Get Palette and Grid to show up. Test.

Try to add colors to the Palette. Test.

Get a Lite to show up when you click in the right spot. Test.

Finally, get a Lite to show up in the right spot with the right color. TEST.

The bulk of time “coding” is actually spent debugging Code and debug incrementally


Debugging printlns vs debugger

Debugging! Printlns vs. Debugger

Printlines:

  • When you want to quickly review a history of state changes, e.g., track one or two variables, or flow-of-control

    • useful when no exception is thrown

Eclipse Debugger:

  • Already have a bunch of printlines cluttering console

  • You're getting exceptions / infinite loops and don't want to have to force-exit the program with the stop button

  • You have multiple conditionals, event handlers/listeners, etc., and want to quickly and conveniently check which ones are getting hit

  • You want to track multiple variables but only note their values once or twice


Continuation from last time

Continuation from last time


Generics 1 3

Generics! (1/3)

  • Generics allow us to write a collection class A to hold instances of another class B, without regard for what that class B is

    public ArrayList<ElementType> ()


Generics 2 3

Generics! (2/3)

  • Programmers use “generics” to implement a collection class without knowing what specific type of object the user (another programmer) of that collection will want to store

    • example: Java’s ArrayList’s class file defines an array list of ElementTypes left unspecified, but when users of the ArrayList actually declare and instantiate one, the type must be fully specified (e.g., an ArrayList of Plastics to serve Regina), much the way arrays need types

    • Java replaces ElementType with Plastics in return types and parameters of any ArrayList method you want to use

    • but you must keep the literal < > brackets wherever they are used to indicate use of generics!


Generics 3 3

Generics! (3/3)

  • Generics allow for generality of using any type while still having compiler do type checking

  • Think of the “generic” as a specialization of the type ArrayList


Java util arraylist methods 1 5

java.util.ArrayListMethods (1/5)

//Note: only most important methods are shown; see JavaDocs for //full class

//Note: literal use of < and >

//one of the many constructors for ArrayList class - specialize //it by providing ElementType, just as Array has the type it //stores. Note: < and > are literal - think of them as “of type”

public ArrayList<ElementType>()

  • //returns the object of type ElementType

  • public ElementType get(int index)


Java util arraylist methods 2 5

java.util.ArrayListMethods (2/5)

//inserts the specified element at the specified position in //this ArrayList

public void add(int index, ElementType element)

//inserts specified element at end of ArrayList

public boolean add(ElementType element)

//removes the ElementType at given index

public ElementType remove(int index)

//returns number of elements stored in ArrayList

public int size()

//returns true if the ArrayList contains zero elements; false //otherwise

public boolean is Empty()


Java util arraylist methods 3 5

java.util.ArrayListMethods (3/5)

  • ArrayLists also have methods which access elements by searching (as opposed to using an index)

    • these methods take a parameter of type Object (superclass from which all Java classes inherit)

    • But you should never pass in (or get back) anything except an ElementType - using polymorphism here not for generality but to get compile-time type checking


Java util arraylist methods 4 5

java.util.ArrayListMethods (4/5)

//finds first occurrence of specified element

public int indexOf(Object elem)

//return true if ArrayList contains specified element

public boolean contains(Object elem)

//remove first occurrence of specified element

//if the element isn’t in the ArrayList, returns false and ArrayList remains unmodified

public boolean remove(Object elem)


Java util arraylist methods 5 5

java.util.ArrayListMethods (5/5)

  • Some other ArrayList notes…

    • can add object at particular slot or at end

    • can retrieve an object stored at a particular index and perform operations on it

    • can use for loop to access all objects in ArrayList

    • shifting elements in memory for adding/deleting from an ArrayList is done automagically by Java!


Summary of arraylists 1 2

Summary of ArrayLists (1/2)

  • More flexible than arrays for insertion/deletion

    • dynamically shifting elements and adjusting size in response to insert/delete done automagically

  • full class with useful methods, eg.,

    • get(int index), add(ElementType element)

    • add(int index, ElementType element)

    • indexOf(ElementType elem) //search

    • remove (int index), size(), isEmpty()


Summary of arraylists 2 2

Summary of ArrayLists (2/2)

  • Can hold a heterogeneous collection of any kind of Object; want homogeneous collections…

  • So specialize the ArrayList type by adding a “generic” specification to a declaration or instantiation, thereby specifying two classes in one statement: the collection and the type of object it is to hold and return

    • implementer of ArrayList collection declares constructor with <ElementType> as placeholder

      public ArrayList<ElementType> ();

    • user of ArrayList “fills in” ElementType

      private ArrayList<Plastic> _plastics;

      _plastics = new ArrayList<Plastic>();

  • Be sure to use literal < > for specialized type!


Example 1 5

Example (1/5)

public class PlasticsCollection{

/* To declare ArrayList, must specify type of object ArrayList stores.

Replace all occurrences of ElementType with Plastic, including where

ElementType occurs in literal <> brackets. Could extend ArrayList, but

it goes against good design. */

private ArrayList<Plastic> _plastics;

public PlasticsCollection(){

// ArrayList initialization - note literal <>

_plastics = new ArrayList<Plastic>();

for (int i=0; i<3; i++){

//Add a Plastic at each pass

_plastics.add(new Plastic());

}

}

// class definition continued on next slide


Example 2 5

Example(2/5)

//Adds a new Plastic at the end

public void addPlastic(Plastic plastic){

_plastics.add(plastic);

}

// If the specified Plastic is in the collection, remove and banish her

public void banishPlastic(Plastic plastic){

if (_plastics.contains(plastic)){

_plastics.remove(plastic);

}

}

} //End of Class


Example 3 5

Example(3/5)

  • <Plastic> indicates use of Java generics

    • now, only Plastic instances can be stored and retrieved from this ArrayList

  • In PlasticCollection’s constructor, adding a new Plastic works:

    • _plastics.add(new Plastic());

  • However, adding another type to the ArrayList of Plastics won’t work:

    • _plastics.add(new String(“Yeah!”));

    • // Won’t work… parameters needs to be of type Plastic

  • Exception thrown!

    • “The method add(Plastic) in the type ArrayList<Plastic> is not applicable for the arguments (String)”


Example 4 5

Example(4/5)

public class Regina{

private PlasticCollection _plastics;

private Plastic _betrayer;

public Regina(PlasticCollection plastics, Plastic betrayer){

_plastics = plastics;

_betrayer = betrayer;

}

// Method to act like a queen bee

public void ruinLives(Plastic plastic){

this.wearPink(); // method def elided

plastic.obey(this) // method def elided

this.spreadRumors(); // method def elided

}

// Method to destroy anyone who betrays her

public void banishBetrayer(){

this.distributeBurnBook();

_plastics.banishPlastic(_betrayer);

}

}


Example 5 5

Example(5/5)

public class MeanGirls{

private PlasticCollection _plastics;

private Regina _regina;

public MeanGirls(){

_plastics = new PlasticCollection();

Plastic cady = new Plastic("Cady");

_plastics.add(cady);

_regina = new Regina(_plastics, cady);

  • } // End of constructor

    public void haveBoringDay(){

    regina.doCarCommercial();

    regina.goShopping();

    }

public void haveExcitingDay(){

Plastic karen = new Plastic("Karen");

regina.ruinLives(karen);

regina.banishBetrayer();

}

} // End of class


Enhanced for loop 1 2

Enhanced forLoop (1/2)

  • Remember for loops from last lecture?

  • Basic for loop was extended in Java 5 to make iteration over arrays and other collections easier

    • commonly called for-each or for-in loop

    • <> here NOT literal, i.e., not for generics

  • for (<type> <var>: <structure>){

  • <loop body>

  • }

  • <type>: class of objects stores in the <structure>

  • <var>: name of the loop counter

  • <structure>: data structure (array or collection) you’d like to iterate over


Enhanced for loop 2 2

Enhanced forLoop (2/2)

  • Intended to simplify most common form of iteration, when, as name suggests, loop body is applied to each and every member of the collection

  • But, how do for-each loop and for loop differ?

    • in a for loop, have access to index at which an item is stored in an array or collection (and hence item itself)

    • in a for-each loop, we don’t have direct access to the index, but can easily access item (see next example)


For each vs for loop 1 2

for-each vs. forloop (1/2)

  • Consider this for loop:

  • //Somewhere in the StudentCollection class

  • //note: _northShoreStudents is an ArrayList<NorthShoreStudent>

  • for (int i=0; i<_northShoreStudents.size(); i++){

  • if (i % 2 == 0){ //if index ‘i’ is even

  • //apologize() is defined in NorthShoreStudent

  • _northShoreStudents.get(i).apologize();

  • }

  • }

  • In the loop above, we only want to call apologize() on elements at even indices. A for-each loop would not be appropriate in this case. Why? Because we don’t execute apologize() on every element in the ArrayList; we only care about elements at specific indices.


For each vs for loop 2 2

for-each vs. forloop (2/2)

  • However, if we want to operate on every element in the ArrayList and the loop body does not require element indices, we may use a for-each loop:

  • //Instead of only even-numbered students, now everyone must apologize!

  • for (NorthShoreStudent student : _northShoreStudents){

  • //notice how don't need to use index to get student from ArrayList

  • student.apologize();

  • }

  • A great advantage of for-each loops is that they don’t give you ArrayIndexOutOfBoundsExceptions! Why?

    • Java does the indexing for you. And Java is never wrong!


Understanding mainline and optional params

package Demos.Mainline;

//Dummy class to understand Mainline

public class App{

public App(){

//constructor elided

}

//Standard mainline function

public static void main(String[] argv){

System.out.println(argv[0]);

System.out.println(argv[1]);

new App();

}

}

Understanding Mainline (and optional params)

  • If we type this in a shell:

    java Demos.Mainline.App Hello CS15

  • We get the output:

    Hello

    CS15

  • In this example, if we did not pass two or more parameters to the mainline, we’d get an ArrayIndexOutOfBoundsException!

  • Why? Because array argv’s size is exactly equal to the number of parameters passed to the mainline

  • You won’t need to use mainline parameters in CS15, but we wanted you to know they exist. You will probably use them in CS32!


Lecture 1 3

Lecture 13

Design Patterns


Overview

Overview

  • Design as trade-offs

  • Holder Pattern

  • Proxy Pattern

  • Delegation


Design in a nutshell 1 3

Design in a Nutshell 1/3

  • Up to now, focused on how to program

    • be appropriately lazy: re-use code and ideas

  • Design Patterns are proven solutions to common problems

    • used successfully before by others, refined by experience

    • generally language-independent - learn once, apply everywhere


Design in a nutshell 2 3

Design in a Nutshell 2/3

  • Increasingly we learn about good design

    • some designs are better than others

    • “better” means, for example:

      • more efficient in space or time required (traditional criteria)

      • more robust, maintainable/extensible

      • more reusable, understandable

    • these are central concerns of Software Engineering

      • discussed in detail in CSCI0320


Design in a nutshell 3 3

Design in a Nutshell 3/3

  • There are trade-offs to make everywhere

    • architect balances aesthetics, functionality, cost

    • mechanical engineer balances manufacturability, strength, maintainability, cost

  • Need to defend your trade-offs

    • no perfect solution, no exact rules

    • up to now, designs have been rather straight-forward


Designing takes experience 1 3

Designing Takes Experience 1/3

  • Experiences is gained by:

    • doing, using, seeing examples (good and bad)

  • Rarely find the final design on first try

    • like writing: you always find a “better” way

    • we changed some design styles for this year’s CS15

    • no one ever stops learning

      • you never stop practicing music, sports, ...

      • Malcolm Gladwell’s pop-psych 10,000 hour “rule”in “Outliers” (but a Princeton study disagrees…)


Designing takes experience 2 3

Designing Takes Experience 2/3

  • CS15 provides you with supervised practice

    • typically, TAs have more experience designing than you

    • but they are still learning from CS15 and other classes

    • guide you towards “best” design, but there are many others - the larger/more complex the problem, the more choices


Designing takes experience 3 3

Designing Takes Experience 3/3

  • But why is experience useful?

    • know what to do in certain circumstances

    • recognize problems you’ve solved before

    • can remember previous solutions and reuse them

      • i.e., recognizing programming patterns

  • As a jump-start, why not make a catalogue of good designs you could read and learn from?


Designing pattern bibles

Designing Pattern Bibles

The two “bibles” of Design Patterns:

  • The Timeless Way of Building by Christopher Alexander (1979)

  • design patterns in architecture

  • Alexander’s patterns in architecture initiated the study of design patterns in software

  • Design Pattern by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994) (“gang of four”)


Reuse designs rather than redesign

Reuse Designs Rather Than Redesign

  • Libraries are predefined classes you can reuse

    • components, like architect’s windows

    • examples: cs015.prj, java.awt, Demos.Cars

    • like components, no indication on how to use them in a program


Reuse design rather than redesign

Reuse Design Rather Than Redesign

  • Patterns are more general than libraries

    • specify some relationships between classes

    • one pattern may represent many interacting classes

    • general, so they must be applied to specific problem

    • no actual code re-use

  • Progression in abstraction/generality vs. code re-use, from concrete classes to abstract classes, to interfaces (no code-reuse, just contract for methods) to patterns (idea re-use)

  • Pattern name, abstract, and identify key aspects of a design’s structure


Reuse rather than reinvent redesign

Reuse Rather Than Reinvent/Redesign

Example Pattern

  • Name: Colonial Revival

  • Abstract: example of 18t-century architecture

  • Key Aspects: typically white or gray wood, facade shows symmetrically balanced windows centered on door, windows have double-hung sashes and panes


You ve already seen simple patterns 1 4

You’ve Already Seen Simple Patterns 1/4

  • Constructors

    • Pattern Name: initialization

    • Abstract: way to ensure objects have proper internal state before use

    • Key Aspects: method that first calls super() (parent’s constructor) and then sets up instance’s own instance variables


You ve already seen simple patterns 2 4

You’ve Already Seen Simple Patterns 2/4

  • Accessor/Mutator methods

    • Pattern Name: encapsulation

    • Abstract: keeps other objects from changing an object’s internal state improperly

    • Key Aspects: use public accessor and mutator methods as appropriate to interact with private or instance variables


You ve already seen simple patterns 3 4

You’ve Already Seen Simple Patterns 3/4

  • Composite Objects

    • PatternName: containment

    • Abstract: models objects that are composed of other objects

    • Key Aspect: store components as instance variables, initialize them in the constructor through instantiation or association (via parameter passing) and provide access protection through encapsulation

      ** Note: Containment pattern uses initialization and encapsulation patterns


You ve already seen simple patterns 4 4

You’ve Already Seen Simple Patterns 4/4

  • Painting

    • PatternName: delegation

    • Abstract: have a complex object perform an action by telling each other its components what to do (e.g., painting or moving themselves)

    • Key Aspect: writing all of the detailed code for each component would clutter the paint or move, etc. method of a complex object. Instead, delegate particulars of painting (or moving, etc.) to individual components


Example colorized app

Example: Colorized App

Specification:

Create a frame with one pentagon, a row of three buttons, and a quit button. One button should be labeled “Red”, the second “Green”, and the third “Blue”. Clicking on a button should set the corresponding color to be the current color for drawing the pentagon: any time the user clicks on the pentagon after clicking a color button, the color of the pentagon should be set to the specified current color. The pentagon should be white by default.


Analyzing the new specification

Analyzing the New Specification

  • Some of this we already know how to do:

    • creating frames, colors, polygons, buttons

    • labelling buttons

  • What don’t we know?

    • how to model, or hold onto, the “current color”

    • what objects we must create ourselves vs. what we can take directlyfrom Swing

  • Let’s define a panel called MainPanel that will hold the shape and the buttons


More graphical containment

More Graphical Containment

  • Let’s create a new graphical containment tree!

  • Use BorderLayoutfor MainPanel

  • Note that graphical and logical containment are usually similar, but slightly different (e.g., classes such as listeners and the holder [see slide 51] do not exist graphically) - See next slide for comparison


Graphical vs logical containment

Graphical vs. Logical Containment

Logical

Graphical

Note: The Colors we use in code technically are never instantiated (we use predefined static constants). So, for containment purposes, we consider them created the first time the Color appears in the code.


What type of buttons 1 2

What Type of Buttons? 1/2

  • We’ll start with buttons - this time for Red, Green and Blue colors

  • Show we use JButton or JRadioButton?

    • JButtons are used to perform one-time action

    • JRadioButtons are used to set semi-permanent choice (choice stays same until explicitly changed by pressing different JRadioButton); also enforce only one choice selected at a time via a ButtonGroup


What type of buttons 2 2

What Type of Buttons? 2/2

  • JRadioButtons are more appropriate for this situation (only want one color at a time for our pentagon)

  • Want to make a single generic class instead of multiple separate subclasses

    • each button has same behavior, but differs only in the actual color it sets


Modeling specified color

Modeling “Specified” Color

  • How do we model the concept of “specified” color?

    • i.e., how do we keep track of the last color clicked?

  • Challenge: Colors are immutable. Once created, a Colorinstance (not instance variable!) models the same color forever

  • JRadioButtons need to refer to an object instance which is mutable


Modeling specified color1

Modeling “Specified” Color

  • Colorableis an interface for objects which have mutable color (cars, bouncing balls,...)

    • two methods: getColor() and setColor()

  • Remember when you had to think about a very similar problem for LiteBrite?


Modeling specified color2

Modeling “Specified” Color

  • Solution: Define a mutable object (called ColorHolder) which implements Colorable and models concept of current color

    • more generic than in LiteBrite, where Palette had its own instance variable for the current color

    • allows us to “set” and “get” color in one place (our ColorHolder), instead of everywhere that has a color reference


Colorholder

ColorHolder

  • ColorListeners for each JRadioButtonwill record instances of their own immutable Color, and call setColor(...) on the associated ColorHolder when clicked

  • ColorChangingPentagon will set its current color by calling getColor() on instance of ColorHolder every time that shape is clicked on


Syntax the colorholder class

Syntax: The ColorHolder Class

  • Each ColorListener tells ColorHolder to change its color reference when activated

  • The pentagon gets current color from ColorHolder

  • So, whenever the pentagon is redrawn, it has current color

  • Think of ColorHolder as a standalone instance variable with set/get

public class ColorHolderimplements Colorable{

private java.awt.Color _color;

public ColorHolder(java.awt.Color color) {

_color = color;

}

//Colorable interface requires set and get

public void setColor(java.awt.Color color){

_color = color;

}

public java.awt.Color getColor() {

return _color;

}

}// end of class ColorHolder – super simple!


Colorholder and colorlistener 1 2

ColorHolder and ColorListener 1/2

  • Notice: ColorHolder implements Colorableand stores a reference to a specific java.awt.Color

  • Each JRadioButtonwill have an instance of the same ColorListener that will set ColorHolder with a specific color

    • ColorListenerhas reference to its unique Color, as well as to the shared ColorHolder

  • Something to think about when designing the ColorListener (which implements java.awt.event.ActionListener - described in the next two slides)

    • what will actionPerformed() do?

      • set color of ColorHolder to color stored in ColorListener’scolor, e.g., Red button’s Listener will set Colorholder’s color to red


Colorholder and colorlistener 2 2

ColorHolder and ColorListener 2/2

  • ColorHolder will be contained (logically, not graphically – it has no graphical representation, just like listeners) as an instance variable by MainPanelsince that is where both the ControlPanel and ShapePanel(which will also need access to ColorHolder) are created

  • Note: javax.swing, java.awt, and cs015.prj.Shape package names are elided throughout remainder of lecture


Syntax the color listener class

Syntax: The ColorListenerClass

  • The ColorListener’sactionPerformedmethod just sets the ColorHolder’s color to the ColorListener’s color value.

publicclass ColorListener implements ActionListener{

private ColorHolder _colorHolder;

private Color _color;

public ColorListener(ColorHolder holder, Color color){_colorHolder=holder;

_color=color;

}

public void actionPerformed(ActionEvent e) {

// set holder’s color (not shape’s!)

_colorHolder.setColor(_color);

}

}


Designing the colorbuttonrow 1 2

Designing the ColorButtonRow 1/2

  • Should logically and graphically contain JRadioButtons

  • What type of LayoutManager should we use?

    • GridLayout (or FlowLayout) can be used to make a row

    • want only one JRadioButtonto be selected at any time


Designing the colorbuttonrow 2 2

Designing the ColorButtonRow 2/2

  • Again, use ButtonGroup

    • make JRadioButtons mutually exclusive

    • still have to add individual buttons to panel!

  • When creating ColorListeners, we need reference to ColorHolder


Syntax colorbuttonrow class

Syntax: ColorButtonRow Class

  • If GridLayout, is passed a 0 value for determining how many rows or columns the layout should have, the grid will have as many rows or columns as necessary to fit the components on the JPanel. Here we want one row of as many columns as needed

  • A ButtonGroup is never added to a JPanel. It just needs to be created and have JRadioButtons added to it to enforce mutual exclusion

public class ColorButtonRow extends JPanel {

public ColorButtonRow(ColorHolder colorHolder) {

super();

this.setLayout(new GridLayout(1,0));

// Buttons differentiated by different colors and different labels

JRadioButton redButton = new JRadioButton("Red");

redButton.addActionListener(new ColorListener(colorHolder, Color.RED));

JRadioButton greenButton = new JRadioButton("Green");

greenButton.addActionListener(new ColorListener(colorHolder, Color.GREEN));

JRadioButton blueButton = new JRadioButton("Blue");

blueButton.addActionListener(new ColorListener(colorHolder, Color.BLUE));

// First add buttons to ButtonGroupfor mutual exclusion

ButtonGroup buttonGroup = new ButtonGroup();

buttonGroup.add(redButton);

buttonGroup.add(greenButton);

buttonGroup.add(blueButton);

// Then add buttons to ColorButtonRow

this.add(redButton);

this.add(greenButton);

this.add(blueButton);

// Size setting, etc. elided

}

}


Colorchangingpentagon 1 3

ColorChangingPentagon 1/3

  • When clicked, it should:

    • query ColorHolder for new color

    • and set itself to that color.

  • So, how can we set up a Shape to react to clicks?


Colorchangingpentagon 2 3

ColorChangingPentagon 2/3

  • Our Shape support code has a react() method

  • This method is empty, but in subclasses of Shape, you can override it to provide functionality

    • The method is empty instead of abstract because all Shape subclasses are not required to implement it; a null method will “execute” but do nothing (called a “no-op”). In our previous examples, we didn’t need a react()…

  • Allows shape to dictate its own response to a click

    • different from timer-based animation which is typically controlled by shape’s containing panel so it can effect interactions between shapes

    • If clicking a shape should involve interactions between shapes, that has to be handled by the containing panel as well, using same methods as the react()s use for the individual shapes in the container


Colorchangingpentagon 3 3

ColorChangingPentagon 3/3

  • Stores reference to ColorHolder

  • Overrides react() method to set the color of the Shape to the color held in the ColorHolder

  • But, how does react() get called? In a few slides, we will show the listener calling the react() method when a click actually occurs

public class ColorChangingPentagon extends PolygonShape{

//Association to holder storing current color

private ColorHolder _colorHolder;

public ColorChangingPentagon(ColorHolder colorHolder) {

super(5); // 5 to be a pentagon

_colorHolder = colorHolder;

this.setColor(_colorHolder.getColor());

}

@Override

public void react() {

this.setColor(_colorHolder.getColor());

}

}// End of class ColorChangingPolygon


Making shapes respond to clicks 1 6

Making Shapes Respond to Clicks 1/6

  • For JButtons, JRadioButtons, etc. we simply call addActionListener(...) and pass in something which implements the ActionListener interface

  • But our Shape does not inherit from java.awt.Component and thus does not have any methods to add a listener


Find the comp in each of these texts

Making Shapes Respond to Clicks 2/6

  • Solution: call addMouseListener(...) on the panel which graphically contains the shape and pass in a reference to an instance of a class that implements the MouseListener interface!

    • use MouseListener instead of ActionListener because for the first time, weneed details about the event (i.e., (x, y) coordinates where click occurred on panel)


Find the comp in each of these texts

Making Shapes Respond to Clicks 3/6

  • When user clicks inside ShapePanel, the panel’s MouseListener checks shape to see whether user clicked inside that shape using shape’s contains(...)predicate

  • In the more general case with many shapes, you need to check each shape

  • If contains()is true for a shape, call shape’s react()

  • But how do we know where on panel user clicked?


Making shapes respond to clicks 4 6

Making Shapes Respond to Clicks 4/6

  • Note MouseListener’s method:

    void mouseClicked (MouseEvent e){...}

  • The MouseEvent parameter contains data about mouse click, including location on panel where click occurred

    • in particular, MouseEvents have a getPoint() method which returns a java.awt.Point

    • so to access point, simply call: e.getPoint();


Making shapes respond to clicks 5 6

Making Shapes Respond to Clicks 5/6

  • See JavaDocs for more information about MouseEvents or Points

  • Now you can find out whether any of shapes in ShapePanelwere clicked!

    • how? By checking if any of ShapePanel’s shapes contain point generated from click!

    • if yes, call react() on shape(s), which can be defined to do whatever you’d like!


Making shapes respond to clicks 6 6

Making Shapes Respond to Clicks 6/6

  • So division of labor between panel’s mouse listener and shape’s react() - it has the actual semantics of the response


Inner classes again

Inner Classes (again)

How will the ClickListenerknow about the shapes stored in the ShapePanel?

One option is to create an association between the ClickListener and the shapes

The simpler option is to add a private inner class to ShapePanel, as inner classes can directly access the outer class’s instance variables. Look ahead for the syntax…


Syntax shapepanel 1 5

Syntax: ShapePanel 1/5

  • ShapePanel is contained in and constructed by MainPanel

    • graphically and logically contains and sets location and dimensions of ColorChangingPentagon

    • passes the ColorHolder to ColorChangingPentagon

    • has ClickListener inner class

    • overrides paintComponent to draw shape (elided – we’ve shown that before)


Syntax shapepanel 2 5

Syntax: ShapePanel 2/5

public class ShapePanel extends JPanel {

private Shape _shape;

public ShapePanel(ColorHolder colorHolder) {

super();

_shape = new ColorChangingPentagon(colorHolder);

Dimension size = new Dimension(200,200);

this.setSize(size);

this.setPreferredSize(size);

_shape.setLocation(0,0);

_shape.setSize(200,200);

this.addMouseListener(new ClickListener(this));

}

// ClickListener code goes here, as inner class to ShapePanel; see slide 71

}


Syntax shapepanel 3 5

Syntax: ShapePanel 3/5

  • The MouseListener interface has five methods that need to be implemented

  • In order for a MouseListener to respond to mouse input, simply provide code for the mouseClicked method and have empty bodies for the other methods


Syntax shapepanel 4 5

Syntax: ShapePanel 4/5

  • Note that private is used for the inner class instead of public. When looking at just the inner class, it looks just like a normal class. On the next slide, we will show the inner class inside of the ShapePanel

  • The mouseClicked method is called by Swing when a click occurs. If click was inside a shape, call its react method, and call repaint to update the color of the shape on the JPanel

  • For multiple shapes you’d loop thru all of them

privateclass ClickListener implementsMouseListener {

private ShapePanel _panel;

public ClickListener(ShapePanel panel) {

_panel = panel;

}

/* This method is called by Swing when a click occurs, passing click’s location in the (event record) parameter e.

Note that _shape is defined in outer class ShapePanel, and this inner class can access it without needing sets/gets, for efficiency */

public void mouseClicked(MouseEvent e){

if(_shape.contains(e.getPoint())){

_shape.react();

_panel.repaint();

}

}

/* Leave these empty. These methods offer

finer control over mouse input, but are optional.*/

public void mousePressed(MouseEvent e){}

public void mouseReleased(MouseEvent e){}

public void mouseEntered(MouseEvent e){}

public void mouseExited(MouseEvent e){}

}// End of ClickListener inner class


Syntax shapepanel 5 5

Syntax: ShapePanel 5/5

public class ShapePanel extends JPanel {

private Shape _shape;

public ShapePanel(ColorHolder colorHolder) {

super();

_shape = newColorChangingPentagon(colorHolder);

Dimension size = new Dimension(200,200);

this.setSize(size);

this.setPreferredSize(size);

_shape.setLocation(0,0);

_shape.setSize(200,200);

this.addMouseListener(new ClickListener(this));

}

  • private class ClickListener implementsMouseListener {

  • private ShapePanel _panel;

  • public ClickListener(ShapePanel panel) {

  • _panel = panel;

  • }

  • public void mouseClicked(MouseEvent e){

  • if(_shape.contains(e.getPoint())){

  • _shape.react();

  • _panel.repaint();

  • }

  • }

  • public void mousePressed(MouseEvent e){}

  • public void mouseReleased(MouseEvent e){}

  • public void mouseEntered(MouseEvent e){}

  • public void mouseExited(MouseEvent e){}

  • }// End of ClickListener inner class

  • }//End of ShapePanel outer class

Note: Even though ClickListener is an inner class, it still must be added to the JPanel via addMouseListener.


When to use inner classes

When to Use Inner Classes

  • You should use an inner class if:

    • logically, the inner class should be encapsulated in the outer class. (The only place where the inner class is needed is in the outer class)

    • Using an inner class allows you to reduce the number of associations you need to make by allowing access to the outer class’s instance variables.


Quitlistener

QuitListener

  • We also need to make a listener for the JButton that quits our program

  • As usual, quit a program by using the System.exit(0) method

public class QuitListener implements ActionListener{

public void actionPerformed(ActionEvent e) {

System.exit(0);

}

}


Syntax controlpanel

Syntax: ControlPanel

public class ControlPanel extends JPanel {

public ControlPanel(ColorHolder holder) {

this.setLayout(new BorderLayout());

this.add(new ColorButtonRow(holder), BorderLayout.NORTH);

JPanelquitPanel= new JPanel();

JButtonquitButton=new JButton(“Quit”);

quitButton.addActionListener(new QuitListener());

quitPanel.add(quitButton);

this.add(quitPanel, BorderLayout.SOUTH);

}

}

Add ColorButtonRow to BorderLayout.NORTH

Create a JPanel to hold quitButton, and add it with BorderLayout.SOUTH.

Need to hold quitButton in its own JPanel because otherwise, the JButton will become wide enough to fill in the width of its container


Syntax mainpanel

Syntax: MainPanel

  • MainPanel is straightforward

    • construct ColorHolder

    • construct ShapePanel and ControlPanel, passing reference of ColorHolder to both

    • Note: Two different styles of passing a panel in add – both are fine

package Holder;

public class MainPanelextends JPanel {

Public MainPanel() {

super();

this.setLayout(new BorderLayout());

// Make white default color of ColorHolder

ColorHolder holder = new ColorHolder(java.awt.Color.WHITE);

ShapePanel shapePanel = new ShapePanel(holder);

this.add(shapePanel, BorderLayout.NORTH);

this.add(new ControlPanel(holder), BorderLayout.CENTER);

}

}


Syntax app

Syntax: App

  • Must create JFrame and MainPanel, and set them up

public class App {

public App() {

JFrame frame= new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// pass new instance directly to add(…)

frame.add(new MainPanel());

// size setting method calls elided

frame.setVisible(true);

frame.pack();

}

public static void main(String[] argv) {

new App();

}

} // end of class App


Holder pattern 1 3

Holder Pattern 1/3

  • Provide object that acts as holder for another object, called the subject (current color in our case)

    • acts as placeholder for a subject that many other objects might reference

    • holder object is “stable,” the instance referenced by other objects does not change

    • holder can change what subject it is referencing, including potentially instances of a different subclass, without affecting those objects that reference the holder itself


Holder pattern 2 3

Holder Pattern 2/3

  • holder object:

    • contains object for which it manages changes (can also be associated with it, like our ColorHolder is with initial color).

    • provides one level of indirection to subject instance

    • provides only accessor/mutator methods


Holder pattern 3 3

Holder Pattern 3/3

  • Advantages:

    • easily change the object that many clients reference because those objects only refer to holder

    • provide different interface to subject

      • e.g., subject may be immutable, but holder provides mutable interface

  • Disadvantages:

    • requires extra class, and thus, extra delegation (more on this later)


Generic structure of holder 1 3

Generic Structure of Holder 1/3

Note: Holder doesn’t have to logically contain/construct the subject – our ColorHolderis an example of the holder receiving an association to its subject during construction


Generic structure of holder 2 3

Generic Structure of Holder 2/3

  • Holderrepresentsour ColorHolder

    • provides mutable interface for immutable Color by maintaining reference to correct Color instance

    • other objects that must reference Color can only do so using ColorHolder

  • Subject represent what the holder holds, i.e., a reference to a java.awt.Color which can change (if we click on a new color). Changed via mutator (set method).


Generic structure of holder 3 3

Generic Structure of Holder 3/3

  • Clients represent ColorListenersand Shapes

    • modify Color

    • delegate the changing Color to ColorHolder

      • ColorHolder keeps track of current Color


Delegation

Delegation

  • Delegation occurs when one class “hands off” responsibility to another class

    • allow run-time flexibility not possible using static class relationships like inheritance or containment

    • message can be sent to many objects, or augmented, each time it is forwarded

    • thus, provides extra flexibility and extensibility

      • e.g., button class delegates responses to its listener class

  • Used in every design pattern we will see


Delegation1

Delegation

  • General structure of Delegation on right

  • Here, Client can be delegated in two ways:

  • to ObjectA or ObjectB directly

  • to ObjectC via Intermediate


Another example shapemover

Another Example: ShapeMover

  • Now we want to model movable hexagons! Here’s the spec:

    • Design a frame with two hexagons and a grid of buttons. The two hexagons should be colored and placed differently to distinguish them. The buttons should be labeled “Move Up”, Move Down”, “Move Left”, and “Move Right”. Clicking on a button moves the current hexagon in the direction denoted by the button. Clicking on a hexagon makes the hexagon the current hexagon.


Specification analysis

Specification Analysis

  • Some things should be simple:

    • frame

    • grid

    • buttons

    • hexagon

  • More difficult things:

    • concept of a current hexagon

    • making a moving hexagon


Current hexagon simple idea

MovingHexagon

MoveLeftListener

MoveRightListener

MoveUpListener

MoveDownListener

Current Hexagon: Simple Idea

  • First idea: Give all button listeners a reference to the hexagon they control

  • Problems:

    • when current hexagonchanges, all buttons need to reset their references

    • no nice way of knowing if a hexagon clicked on is new or not, so with every mouse click, all references to hexagon must be updated


The proxy pattern 1 2

The Proxy Pattern 1/2

  • Current hexagon sounds like current color from the holder pattern example!

    • could use a HexagonHolder…

    • hexagons would put reference to themselves in holder when clicked on

    • buttons would get current hexagon from holder and call messages on it

  • From a design perspective, gives a lot of work to the buttons

    • would like to avoid having buttons get current hexagon from the holder in order to call methods on it


The proxy pattern 2 2

The Proxy Pattern 2/2

  • Alternative: Use a Proxy! (Which you’ll be doing in Tetris!)

  • Proxy acts on behalf of another subject

    • proxy has a reference to the actual instance of subject

    • that reference can change

    • all clients know only proxy; proxy only knows subject

    • proxy has methods that match those of subject (but not necessarily all of the subject’s methods)

    • clients call methods on proxy which forwards them to subject

    • let’s us control what methods can be called on the underlying object that the proxy models


Current hexagon using proxy 1 2

MovingHexagon

MovingHexagonProxy

MoveLeftListener

MoveRightListener

MoveUpListener

MoveDownListener

Current Hexagon: Using Proxy 1/2


Current hexagon using proxy 2 2

Current Hexagon: Using Proxy 2/2

  • MovingHexagonProxy acts on behalf of MovingHexagon; another example of delegation

  • When the JButton associated with the MoveUpListener is clicked, it calls moveUp() on proxy, which in turn calls moveUp() on hexagon (hooray for delegation!).

  • When hexagon is clicked, it sets proxy’s reference to itself

    • listeners don’t need to change their references


Design movinghexagonproxy

Design:MovingHexagonProxy

  • analyze program and come up with a class diagram

  • Note this time we don’t use a separate ControlPanel class since BorderLayout suffices – design choice

  • All instances of MovingHexagonknow about MovingHexagonProxy, but MovingHexagonProxyonly knows about one MovingHexagonat a time

  • Note: Only showing BorderLayout; other LayoutManagers elided


Design of the movinghexagonproxy

Design of the MovingHexagonProxy

  • MovingHexagonProxy class needs a method to set its MovingHexagon

  • Needs moveUp(), moveDown(), moveLeft(), and moveRight() methods to call on its MovingHexagon

    • e.g., moveUp() will call MovingHexagon’smoveUp() method


Syntax movinghexagonproxy

Syntax:MovingHexagonProxy

public void moveUp() {

_movingHexagon.moveUp();

}

public void moveDown() {

_movingHexagon.moveDown();

}

public void moveLeft() {

_movingHexagon.moveLeft();

}

public void moveRight() {

_movingHexagon.moveRight();

}

} // end of class MovingHexagonProxy

package Proxy;

public class MovingHexagonProxy {

private MovingHexagon _movingHexagon;

/* constructor doesn’t need to do anything because the containing class will call setHexagon(...) in its constructor to set the default hexagon in _movingHexagon */

public MovingHexagonProxy() {}

// Let us change the current hexagon

public void setHexagon(MovingHexagon hexagon) {

_movingHexagon = hexagon;

}


The move buttons

TheMoveButtons

public class MoveLeftListener implements ActionListener{

private ShapePanel _panel;

private MovingHexagonProxy _proxy;

public MoveLeftListener(ShapePanel panel, MovingHexagonProxyproxy) {

_panel=panel;

_proxy=proxy;

}

public void actionPerformed(ActionEvent e) {

_proxy.moveLeft();

_panel.repaint();

}

}

  • Listeners are simple!

    • make an ActionListenerfor each direction

  • You get the idea…


Designing movinghexagon

DesigningMovingHexagon

  • MovingHexagon will be subclass of PolygonShape, adding extra capabilities

  • It will store reference to MovingHexagonProxyand tell proxy to update the reference to itself as current hexagon when clicked

  • moveDown() method

    • method should move hexagon down by, say, 25 pixels

    • first get the old location and translate down by 25 pixelsdouble newY = this.getY() + 25;

    • then actually move the point this.setLocation(this.getX(), newY);

  • And other move methods are similar.


Syntax movinghexagon

Syntax: MovingHexagon

package Proxy;

public class MovingHexagon extends PolygonShape {

private MovingHexagonProxy _proxy;

public MovingHexagon(MovingHexagonProxy proxy) {

super(6); //6 to be a hexagon

_proxy = proxy;

this.setSize(50,50);

}

public void react() {

_proxy.setHexagon(this);

}

public void moveDown() {

double newY = this.getY() + 25;

this.setLocation(this.getX(), newY);

}

public void moveUp(){

//remember, origin is in top-left corner of panel!

double newY = this.getY() – 25;

this.setLocation(this.getX(), newY);

}

public void moveLeft() {

double newX = this.getX() – 25;

this.setLocation(newX, this.getY());

}

public void moveRight() {

double newX = this.getX() + 25;

this.setLocation(newX, this.getY());

}

}


Movebuttongrid

MoveButtonGrid

  • Just instantiates buttons and adds them to the layout.

  • Again, buttons are added to their own JPanels so that they do not fill the whole space of the container and are reasonably sized

package Proxy;

public class MoveButtonGrid extends JPanel {

public MoveButtonGrid(MovingHexagonProxy proxy,ShapePanel panel) {

super();

this.setLayout(new GridLayout(0,3));

//Create empty space between buttons done foraesthetic reasonsthis.add(Box.createHorizontalGlue());

//Add button

JPanelmoveUpPanel = new JPanel();

JButtonmoveUp = new JButton("Move Up");

moveUp.addActionListener(new MoveUpListener(panel, proxy));

moveUpPanel.add(moveUp);

this.add(moveUpPanel);

//And so on…

this.add(Box.createHorizontalGlue());

JPanelmoveLeftPanel= new JPanel();

JButtonmoveLeft = new JButton("Move Left");

moveLeft.addActionListener(new MoveLeftListener(panel, proxy));

moveLeftPanel.add(moveLeft);

this.add(moveLeftPanel);

//etc.

}

}


Shapepanel

ShapePanel

  • Instantiates the MovingHexagons and colors and positions them

  • Sets the proxy to one of the hexagons.

package Proxy;

public class ShapePanel extends JPanel {

private MovingHexagon _hex1, _hex2;

public ShapePanel(MovingHexagonProxy proxy) {

super();

this.setBackground(java.awt.Color.darkGray);

_hex1 = new MovingHexagon(proxy);

_hex1.setColor(java.awt.Color.RED);

_hex1.setLocation(50, 250);

_hex2 = new MovingHexagon(proxy);

_hex2.setColor(java.awt.Color.GREEN);

_hex2.setLocation(400, 251);

//put a default shape in the proxy

proxy.setHexagon(_hex1);

//set size, other initializations elided

}

//MouseListener, same pattern of testing containment of

//containment of point in shapes as in previous

//holding example, then calls repaint.

//paintComponent elided...

}


Mainpanel

MainPanel

package Proxy;

public class MainPanel extends JPanel {

public MainPanel() {

super(new BorderLayout());

MovingHexagonProxy proxy = new MovingHexagonProxy();

ShapePanel shapePanel = new ShapePanel(proxy);

MoveButtonGrid moveButtonGrid = new MoveButtonGrid(proxy, shapePanel);

this.add(shapePanel, BorderLayout.NORTH);

this.add(moveButtonGrid, BorderLayout.CENTER);

JPanel quitPanel = new JPanel();

JButton quitButton = new JButton(“Quit”);

quitButton.addActionListener(new QuitListener());

quitPanel.add(quitButton);

this.add(quitPanel, BorderLayout.SOUTH);

//size setting, ect. Elided

}

}

  • Just instantiates theShapePanel,MoveButtonGrid,MovingHexagonProxy,andJButtonto quit the App.


Find the comp in each of these texts

App

  • Same as usual…

    package Proxy;

    public class App{

    public App() {

    JFrame frame = new JFrame(“Super Mover!”);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //add new instance of top-level to Frame

    frame.add(new MainPanel());

    frame.pack();

    frame.setVisible(true);

    //size setting, main line etc. elided

    }

    }


Holder vs proxy

Holder vs. Proxy

  • Notice the similarity between Proxy pattern and simpler Holder pattern

    • difference is in modeling.

  • Holder will usually contain subject that clients can access (get) and send messages to directly

    • Clients access/set the subject directly via simple accessor/mutator methods

    • This lets clients call any public method defined by subject on instance of that subject

  • Proxy knows about subject that clients can call methods on indirectly by way of proxy

    • Lets proxy limit the methods that can be indirectly called on the subject it models


Generic structure of proxy

ClientA

ClientB

Proxy

ClientC

Subject

Generic Structure of Proxy

  • Proxy represents our MovingHexagonProxy

    • provides indirect access to the Subject for the clients

    • acts on behalf of MovingHexagon—an example of delegation

  • Subject represents the Proxy’s reference to the current MovingHexagon. When a MovingHexagon is clicked on, it sets the proxy’s reference to itself.

  • Clients represent Jbuttons

    • indirectly moves the current MovingHexagon through the MovingHexagonProxy

    • buttons don’t need to change their references when the current MovingHexagon is changed.


Design patterns

Design Patterns…

  • Serve as examples of good design

    • there are no “hard and fast” rules

    • there are concrete trade-offs to think about

    • they are tools to help you build your own designs

  • Provide common vocabulary to discuss design at a more abstract level

    • give us a concise way to describe complex object interaction

    • discuss design at a higher level because we do not need to describe every object in the program

  • Must be adapted to your program specification

    • may need to add extra relationships to your structure to augment a design pattern.

    • may need to create a new pattern because none exists that exactly fits your needs.

  • Should be used in moderation

    • consider trade-offs carefully before using a pattern.

    • consider added complexity—is it needed in your model?


Announcements

Announcements

Cartoon Early handin tonight at 11:59PM

On Time handin is Saturday at 10:00PM

Late handin is Monday at 11:59PM


  • Login