abstract data types: stepping back from specifics

71
Abstract Data Types: stepping back from specifics

Post on 19-Dec-2015

225 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Abstract Data Types: stepping back from specifics

Abstract Data Types:stepping back from

specifics

Page 2: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Abstract Data Types (ADTs)

An ADT consists of: a set of values, and a set of operations on those values.

Example: rational numbers some values: 15/7, -3/4, 123/1, 0/1 (but NOT 1/0 !) some operations: addition, multiplication,

negation An ADT therefore specifies:

what the members are, and what operations are supported.

Page 3: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

What an ADT isn’t:

An ADT does not specify: how the data is stored/represented, or how the operations are implemented.

These details are abstracted away.An ADT is implementation independentAn ADT is language independent.In Java, an ADT is typically specified in an

interface.

Page 4: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Data Structures (DS)

A data structure is an implementation of an ADT.

In Java, data structures are classes. In the Java Collections framework, the List

interface specifies an ADT that is implemented by several data structures: ArrayList (an array-based structure) LinkedList (a linked structure)

Page 5: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Analogy #1: an ADT is like a vending machine

You can perform only the specific tasks that the machine's interface presents to you.

You must understand these tasks. E.g. you must know what to do to buy a beverage.

You cannot see or access the inside of the machine, because a steel shell encapsulates it.

You can use the machine even though you don't know what happens inside.

If someone replaced the machine's inner mechanism with an improved version, leaving the interface unchanged, you could still use the machine the same way.

Page 6: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Analogy #2: an ADT is like a car

Basic interface is the same: steering wheel to determine path gearshift (on an automatic) to determine direction

(drive/reverse) pedals to determine speed (accelerator/brake)

Underlying implementation is irrelevant steering: recirculating ball, rack & pinion transmission: 3, 4 or 5 speed, CVT engine: 4, 5, 6 or 8 cylinder, gas, diesel, CNG or hybrid

Client treats them all the same!

Page 7: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

What if the interface changes?

How easy is it for people to switch from driving an automatic to a manual transmission car?

Automatic: gear selector: drive/reverse pedals: accelerator, brake

Manual: gear selector: 1, 2, 3, 4, 5, R pedals: accelerator, brake, clutch

Client needs to adjust to the new interface!

Page 8: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

With an ADT The client can only perform the operations

specific to the ADT. The client must adhere to the

specifications of the operations that the ADT provides.

Thus, client must understand how to use the operations.

Page 9: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Interacting with a List (ADT) The client cannot access the data within the list

without using an ADT operation. The principle of encapsulation hides the data within the ADT.

The client can use the ADT, even though it can't access the data directly, and does not know how it is stored.

If you vary the implementation, but maintain the interface, the client isn’t affected and doesn’t have to care.

Page 10: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Examples of ADTs

Bag – unordered collection, allowing duplicates Set – unordered collection, no duplicates List – ordered collection – client determines order Sorted list – comparator determines ordering Stack – Last-In First-Out (insert/remove from front) Queue – First-In First-Out (insert back, remove front) Tree – hierarchical organization Binary Search Tree – comparator determines ordering

a simple BST makes no performance guarantees more advanced BSTs can make performance guarantees

Dictionary – collection of key-value pairs Graph – collection of vertices and arcs

Page 11: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Creating an ADTTo define an ADT, we Describe its data Specify the operations on that data Focus on “what”, not “how”.

Page 12: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Bag ADT (revisiting details) Values: object references (unordered). We use the new Java 5 generics to define a

parameterized type. The type of the members of the ADT is

specified by a type parameter in the definition of the interface.

Page 13: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Bag Operations (revisiting details)

Basic operations: add (client has no control over placement;

returns a boolean) remove (based on object identity; returns a

boolean) contains (membership test; returns a boolean) size (how many values are in a given bag)

Page 14: Abstract Data Types: stepping back from specifics

Java Foundation Classes

(JFC/Swing)

Carl Alphoncerevised Spring 2007

(with contributions from Alan Hunt)

Page 15: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Java Swing Toolkit Graphics The key to effectively using graphics in

Java is understanding: the basic components of the graphics library the patterns that are used to combine

components Must also understand how multiple

threads of execution are used to run graphical applications.

Page 16: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Overview Patterns Containers and Components Threads

Page 17: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Some patterns used OBSERVER STRATEGY COMPOSITE DECORATOR

Page 18: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Some patterns used - examples OBSERVER – event handling STRATEGY – layout management COMPOSITE – containers are also components DECORATOR – scrollbars, streams

Page 19: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

java.awt.Component

All displayable objects in the graphics hierarchy extend this base class. You will never create an instance of this class directly (since it is abstract), but instead use the pre-defined GUI elements that Java provides.

Page 20: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Containers

A container is the basic enclosing element of a graphical application. You cannot have a graphical application without a container to hold the rest of your graphical components.

The top level container for an application is usually a javax.swing.JFrame

Page 21: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

javax.swing.JFrame

A JFrame is a top-level container (meaning it does not need to be contained within any other container).

A JFrame is a window with a title and a border.

JFrames also support menu bars.

Page 22: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

An example using a JFrame(this is not "thread-safe")

public class JFrameExample {

public JFrameExample() {JFrame f = new JFrame();f.pack();f.setVisible(true);

}

public static void main(String[] args) {new JFrameExample();

}

}

Page 23: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Composite Pattern

Page 24: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Page 25: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Composite Pattern The whole graphical framework is a

hierarchy of components. This is an almost textbook example of the composite pattern: a frame contains many children, which all

comply to the same interface (Component) a call to, for example, repaint() on the frame

will also call repaint() on all its children

Page 26: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Input Elements The whole point of a Graphical User

Interface (GUI) is to accept user input and do something with it. To this end, there are a large number of input components in Swing.

Let’s first examine the JButton.

Page 27: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Button Example

JButton button = new JButton("Push Me");

f.getContentPane().add(button);

button.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {

label.setText("Clicked");}

});

Page 28: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

OBSERVER PATTERN – general form

Idea: decouple event from event handling

Concrete Observable

Abstract Observable

Concrete Observer

0..*

Abstract Observable

attach(Observer)

detach(Observer)

notifyObservers()

Abstract ObservableAbstract Observer

update()

Page 29: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

JFC use of OBSERVER The observer pattern is used for event

notification. Observables (classes like JButton)

generate events. An observable can have many observers. The pattern is applied several times in

design of class library. Pattern is tailored to application: method

names are suitable for each application.

Page 30: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

OBSERVER PATTERN - applied

In JFC/Swing, Observer is realized for different event types, with methods named accordingly.

Abstract Observable

0..*

JButton

addActionListener(ActionListener)

removeActionListener(ActionListener)

fireActionPerformed(ActionEvent)

Abstract ObservableActionListener

actionPerformed(ActionEvent)

attach addActionListenerdetach removeActionListenernotifyObservers fireActionPerformed

update actionPerformed

Page 31: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Multiple Observers

We can add more than one observer to our button. All observers are notified when a button event occurs. Let us add an observer that will also change the color of the label.

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

label.setForeground(Color.RED);

}

});

Page 32: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

DECORATOR A decorator adds functionality while

maintaining an interface. One example:

InputStreamReader wraps InputStream BufferedReader wraps InputStreamReader

Another example: JScrollPane wraps Jlist

Page 33: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

STRATEGY A layout manager has responsibility for

laying out components within a container. Unlike in NGP, JFC containers do not have

fixed layout managers. Layout managers are treated as

strategies. Strategies can be swapped.

Page 34: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Layout Managers Swing has several different layout

managers. Some of the most common are FlowLayout, BorderLayout, GridLayout, and GridBag Layout. Each has advantages and disadvantages.

Page 35: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

BorderLayout

The BorderLayout manager creates an object that resembles a picture with a four sided frame, or border.

Page 36: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

FlowLayout FlowLayout is arguably the simplest layout

manager. It just stacks up components in a row, right to left. If it runs out of space, it wraps to a new line. This is the default layout manager for JPanel. You can see the behavior in how the button, text area, and combo box are laid out.

Page 37: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

GridLayout GridLayout arranges its components in an

equally spaced grid of cells. Will take as much space as is available to it.

Page 38: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

GridBag Layout GridBag is both the most flexible of the

layout managers, and the most difficult to use. It allows you customize the size and growth of all the components separately, but setting it up is a pain.

Page 39: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Topic overview Processes & Threads Containers (graphical) Components Layout managers Event handling Inner classes

Page 40: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Processes and Threads What is a process? What is a thread? two special Java threads

main thread event-dispatching thread

the Runnable interface

Page 41: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Processes A program that is running on a computer is

called a process. most consumer OSes allow many processes to run

simultaneously a single program can give rise to many processes

bob runs Netscape – one process sally runs Netscape – another process

multitasking at the operating system level

Page 42: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Threads Each process has its own (main) thread of

execution A process can spawn several threads

multitasking is happening at the level of the process, not at the level of the operating system

a process with multiple threads is called a multithreaded application

Page 43: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Two Java threads Every Java program has a main thread of

execution. starts with “public static void main(String [] args)”

Graphical applications have an event-dispatching thread too.

It is important for the proper functioning of graphical, event-driven programs that graphics be run on the event-dispatching thread.

Page 44: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Runnable interface The Runnable interface specifies one method:

public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run();}

Page 45: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

How is Runnable used? An object which is Runnable has a run

method. An object which is Runnable can be run in

a specific thread. The javax.swing.SwingUtilities class

provides a method, invokeLater, which takes a Runnable, and calls its run method once other events queued on the event-dispatching thread have been handled.

Page 46: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

What does this have to do with graphics? To be “thread safe” graphical applications

should run their GUI code on the event-dispatching thread.

They do this by starting their GUI on the event-dispatching thread write the GUI creation code in a Runnable pass this object to the invokeLater method.

Page 47: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Graphical containers All graphical elements are contained inside

some graphical container, except the so-called “top-level” containers.

Containers can contain other containers Top-level containers:

JFrame JDialog JApplet

Page 48: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Example Creating just a frame

new javax.swing.JFrame()

Creating a frame with a title new javax.swing.JFrame(“My title”)

Making the frame visible: call setVisible(true) on the frame

Making application close when window is closed: call setDevaultCloseOperation(JFrame.EXIT_ON_CLOSE) on

the frame Go look at example_set_1

Page 49: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Adding components Top-level containers have multiple panes Content pane is the one which holds

components call getContentPane() on frame to get frame’s

content pane call add(…) on content pane to add a

component

Page 50: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

A simple component A JLabel is a component that can display

text or an image. Go look at example_set_2

Page 51: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Layout managers What happens if we add another JLabel?

Go look at example_set_3

Page 52: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Another component A JButton is a component which is typically

set up to react to clicks. Clicks on buttons, mouse movements, etc.

are all considered events. A program can react to events by setting

up event handlers. Like an exception handler, an event

handler defines what should happen when a particular event occurs.

Page 53: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Event handling – 1 The component which gives rise to an event

is decoupled from the part of the code that handles the event.

This is called the observer pattern. General form:

www.research.ibm.com/designpatterns/example.htm

Page 54: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Event handling – 2 Observer pattern in Java

An observer is called a listener in Java Button clicks are “ActionEvents”. Handlers for ActionEvents are ActionListeners. An event-generator can have many listeners Use “addActionListener” method to register a

listener with a component

Page 55: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Inner Classes An inner class is a class defined inside another

class. An inner class is within the scope of the

surrounding class (and therefore has access to private variables and methods defined in class).

An anonymous inner class is an inner class defined without a name (a one-off class) saw this earlier with Runnable interface implementation

Inner classes are often used to define event handlers, especially anonymous inner classes.

Page 56: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Event handling - 3 Go look at example_set_4

Page 57: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Putting it all together Go look at example_set_5

Page 58: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Topic overview Swing components in (more) detail

Containers top-level containers general containers special-purpose containers

Controls Views (uneditable displays) Editors

Layout managers in (more) detail

Page 59: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Containers Top-level containers

JApplet, JFrame, JDialog (and subclasses) They can serve as the top of a (graphical) containment

hierarchy (i.e. they don’t need to be contained within another container).

General containers panels, scroll panes, split panes and tabbed panes They provide fairly general ways of organizing

information visually. Special-purpose containers

Won’t go into these here.

Page 60: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Controls Swing provides many controls “Separable model architecture” We’ll touch on:

check box list menu spinner your choice, time permitting

Page 61: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Views Views are information displays that cannot

be edited. labels, progress bars, tooltips

Page 62: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Editors Editors are information displays which

allow editing. editor pane, text pane, color chooser, file

chooser, table, etc. Can be very complex.

Page 63: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Containers JPanel is a very generic container. JScrollPane is a container that can provide

scrollbars to shift a “viewport” to show different parts of an underlying view.

JSplitPane provides a movable partition between two parts of a pane.

JTabbedPane provides a “tabbed” environment for displaying different views.

Page 64: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

JScrollPane (see session5.scrollpane)

Page 65: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

JSplitPane (see session5.splitpane)

Page 66: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

JTabbedPane (see session5.tabbedpane) Show tooltips. Show mnemonics.

Page 67: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Combining containers! (see session5.combined)

Page 68: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

JCheckBox (see session5.checkbox)

Page 69: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Model-View-Controller The Model-View-Controller pattern is often

used to help architect GUI applications: the model holds data a view displays data from the model to user a controller handles user input and

communicates with the model

V

C

M

V

M

C

Page 70: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

Models and Views Use lists as an example. The model (the data provider) of a list is

separate from its View/Controller. A JList is the view-controller, which

communicates with an underlying ListModel.

Page 71: Abstract Data Types: stepping back from specifics

JFC/Swing lectures

How do you create a model? You can implement the ListModel interface

to create a custom data model. The JList constructor allows you to pass in

an array or a vector of data elements, which it then uses to build a default ListModel automagically.