47

This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Embed Size (px)

Citation preview

Page 1: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking
Page 2: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

This Lecture Course Outline Brief review

Design PatternsCollectionsGUI with Java Swing

Java Networking

Page 3: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Course Objective Algorithmic programming techniques

Academic purpose○ Minimal knowledge of implementing software

systems○ Academic basis for methods used in design,

testing and verification of real world software systems

Industry purpose○ Solid basis for software development positions in

the industry○ Enhance knowledge of common programming

toolsMake it easier for students to learn about such

tools by themselves

Page 4: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Additional Reading and Materials The course can only serve as a starting

pointStudents are expected to learn some of the

material by themselvesThe Java Tutorial:

http://java.sun.com/docs/books/tutorial/ Material covered so far…

○ Essential Java Classes — exceptions, IO, threads, …

○ Collections — ADTs, the Java Collections Framework

○ Swing — Introduction to the Swing GUI toolkit

Page 5: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Additional Reading and Materials Required additional reading

○ Custom Networking — networking features

Future reading○ Generics — Advanced generics support,

compile-time type safety○ JDBC Database Access —API for connectivity

to databases and a data sourcesBruce Eckel

○ Thinking in Java○ Thinking in Patterns

Page 6: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Introduction – Design Patterns Object Oriented Design is Hard Errors are expensive

Cost of error increases during the later development phases

Reuse experts’ designs

Pattern = Documented experience

Page 7: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Expected Benefits

Finding the right classes Finding them faster Common design jargon Consistent format Coded infrastructures

Page 8: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Abstract Data TypeAn abstract data type (ADT) is a

specification of the behavior (methods) of a type

An ADT shows no implementation What Java construct can be use to specifies

an ADT?

Page 9: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

The Java Interface

An interface describes a set of methods: ○ no constructors or instance variables

Almost always, two or more classes implement the same interface○ Type guaranteed to have the same methods○ Objects can be treated as the same type○ Can use different algorithms / instance variables

Page 10: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Old MacDonald had a farm

An interface, a reference type, can have ○ static variables and method headings with ;

public int size(); // no { }Methods are implemented by classesExample interface :

public interface BarnyardAnimal { public String sound(); }

Page 11: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Multiple classes implement the same interface

To implement an interface, classes must have all methods specified as given in the interface

public class Cow implements BarnyardAnimal { public String sound() { return "moo"; } }

public class Chicken implements BarnyardAnimal { public String sound() { return "cluck"; } }

Page 12: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

The Comparable interface

Can assign an instance of a class that implements and interface to a variable of the interface type

Comparable str = new String("abc"); Comparable acct = new BankAccount("B", 1); Comparable day = new Date();

Implementing classes for Comparable BigInteger Byte ByteBuffer Date Double …Comparable provides natural ordering for

collections

Page 13: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Implementing Comparable

You can have types implement Comparable○ Need to do this to be sorted by Collections.sort

public interface Comparable<T> { /** Return 0 if two objects are equal; less than * zero if this object is smaller; greater than * zero if this object is larger. */ public int compareTo(T other); }

Try to sort some BankAccounts without Comparable

Implement Comparable (next Slide)

Page 14: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

BankAccount can be a Comparable

public class BankAccount implements Comparable<BankAccount> {

private String id; private double balance;

public BankAccount(String ID, double initialBalance) { id = ID; balance = initialBalance; }

public int compareTo(BankAccount other) { // Must have this method to avoid compiletime error // No cast needed in Java 5 return id.compareTo(other.id); } }

Code demo: make a class and test compareTo works

Add compareTo method

promise that this class has int compareTo(T)

Page 15: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Java's Collection Framework

Collection framework○ Unified architecture for representing and

manipulating collections Java's collection framework contains

○ Interfaces (ADTs): specification not implementation○ Concrete implementations as classes○ Algorithms to search, sort, find, shuffle, ...

The algorithms are polymorphic: ○ the same method can be used on many different

implementations of the appropriate collection interface.

In essence, algorithms are reusable functionality.

Page 16: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Collection interfaces in java.util (Java 5)

Page 17: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Collection Classes

A collection class that can be instantiated○ implements an interface as a Java class○ implements all methods of the interface○ selects appropriate instance variables

Java 5 has these concrete collection classes LinkedList<E>, HashMap<K,V>, HashSet<E>, Stack<E>, TreeMap<K,V>

Page 18: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Common Functionality

Collection classes often have methods for○ Adding objects○ Removing an object○ Finding a reference to a particular object find

can then send messages to the object still in the collection

Page 19: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

2 Useful ADTs written

List: a collection with a first element, a last element, distinct predecessors and successors

○ The user of this interface has precise control over where in the list each element is inserted

○ duplicates that "equals" each other are allowedSet: A collection that contains no duplicate

elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2)

Page 20: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

List

A list is○ a collection of elements (numbers, strings, accounts,

pictures,…) ○ ordered (a sequence): there is a first, and a last

element lists can be empty – no elements

○ elements with a unique predecessor and successor○ also known as a sequence

Page 21: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

ArrayList

ArrayList<E> ○ stores a collection of one type of object ○ similar functionality to an array, uses get and set, not[]○ The syntax tells you that the interface is generic. ○ When you <E> declare a Collection instance you can

and should specify the type of object contained Allows the compiler to verify (at compile-time) that the

type of object you put into the collection is correct

- Reduces errors at runtime. ○ Generic collection with <E> are not available before Java

5.0

Page 22: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

public class ThreeClassesImplementList {

public void showThreeImplementationsOfList() { // Interface name: List // Three classes that implement the List interface: List<String> bigList = new ArrayList<String>(); List<String> littleList = new LinkedList<String>(); List<String> sharedList = new Vector<String>();

// All three have an add method bigList.add("in array list"); littleList.add("in linked list"); sharedList.add("in vector");

// All three have a get method assertEquals("in array list", bigList.get(0)); assertEquals("in linked list", littleList.get(0)); assertEquals("in vector", sharedList.get(0)); } }

Page 23: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Can't add wrong type

Java 5 generics checks the type at compile time○ See errors early--a good thing○ "type safe" because you can't add different types

ArrayList<GregorianCalendar> dates = new ArrayList<GregorianCalendar>(); dates.add(new GregorianCalendar()); // Okay dates.add(new String("No go in dates")); // Error

ArrayList<Integer> ints = new ArrayList<Integer>(); ints.add(1); // Okay. Same as add(new Integer(1)) ints.add(new String("Pat")); // Error

Page 24: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

TreeSet<E>implements Set<E>

Set A collection that contains no duplicate elements. ○ Formally, contain no pair of elements e1 and

e2 such that e1.equals(e2) TreeSet implements the Set interface

○ Backed by a TreeMap instance○ Guarantees the sorted set will be in ascending

element order sorted according to the natural order of the elements

(see Comparable)

Page 25: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Extended for TreeSet<String> names = new

TreeSet<String>(); names.add("Sandeep"); names.add("Chris"); names.add("Kim"); names.add("Chris"); // not added names.add("Devon");

// name is the type between <> // names is the collection to iterate over

for (String name : names) System.out.println(name);

Page 26: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Java Graphical User Interface (GUI) Presents a graphical view of an application

To build a GUI application, you must:○ Have a well-tested model that will be used○ Make graphical components visible to the user○ ensure the correct things happen for each event

user clicks button, moves mouse, presses enter key, ...

Useful tool to show several design patterns

Let's first consider some of Java's components: windows, buttons, and text fields

Page 27: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Classes in the swing package

The javax.swing package has components that show in a graphical manner JFrame: window with title, border, menu, buttons JButton: A component that can "clicked" JLabel: A display area for a small amount of text JTextField: Allows editing of a single line of text

Page 28: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Get a window to show itself

Import all four as follows or javax.swing.* import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextField;

Code to tell a window to show itself: // Construct window with a title JFrame aWindow = new JFrame("Graffiti"); // Make sure the program terminates when window closes aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); aWindow.setVisible(true);

Page 29: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Some JFrame messages

Set the size of the window with aWindow.setSize(220, 100);

○ The first int is the width of the window in pixels○ the second int is the height of the window in pixels

Page 30: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Building components

So far we have an empty windowLet us add a button, a label, and an editable lineFirst construct three graphical components

JButton clickMeButton = new JButton("Nobody is listening to me") ; JLabel aLabel = new JLabel("Button above, text field below"); JTextField textEditor = new JTextField("You can edit this text ");

Next, add these objects to a window object

Page 31: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Adding to the Content PaneIn early versions of Java, you add components to

the window (an instance of Frame, not JFrame).Now you add components to the content pane

○ JFrame objects store several objects including a Container object known as the content pane

Page 32: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Add components to a window

Get a reference to the Container Container contentPane = aWindow.getContentPane();

Use layout from abstract windowing toolkit (awt) import java.awt.Container import java.awt.BorderLayout

Then add the previously constructed components to one of the five areas of a JFrame

contentPane.add(clickMeButton, BorderLayout.NORTH); contentPane.add(aLabel, BorderLayout.CENTER); contentPane.add(textEditor, BorderLayout.SOUTH); aWindow.setVisible(true);

Page 33: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

The 5 areas of BorderLayout

By default, JFrame objects have only five places where you can add components a 2nd add wipes out the 1st

○ This can be modified to other layouts ○ Or add other containers that contain other containers○ These five areas will do for now

Page 34: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

So what happens next?You can layout a real pretty GUIYou can click on buttons, enter text into a

text field, move the mouse, press a key○ And NOTHING happens

So let’s make something happen …

Page 35: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Java's Event Model

Java lets the OS to notify graphical components of user interaction○ Button objects are notified when the user clicks it○ A text field object with focus knows when the user

enters text and your program can respond○ A menu item can know that a user selected it○ An event driven program can respond to many things

mouse clicks, mouse movementsclicks on hyperlinks, buttons, menu itemsUsers pressing any key, selecting a list item

Page 36: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Example: Action EventsThe buttons, text fields, and menu items do

not perform the actions○ Instead JButton, JTextField, JMenuItem

objects send actionPerformed messages to other objects

We write code to respond to the above events in actionPerformed methods○ This requires a class that implements the ActionListener interface

Page 37: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Event Driven Program with GUIs

Key elements of an event-driven GUI○ Graphical components

The screen elements that a user manipulates with the mouse and keyboard JFrame JLabel JButton JScrollbar JMenuItem JTextField JTextArea Jlist ...

○ Layout managers Govern how the components appear on the screenExamples FlowLayout GridLayout SpringLayout

○ Events Signal that a user interacted with the GUIExamples: mouse clicks, keys pressed, hyperlinks selected

Page 38: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Java's Event Model

JFrame

JButton

1 Layout Graphical ComponentsJFrame JButton

JTextField JMenuItem

Listener

3 You register objects that waits for messages from graphical components addActionListener

ListenerListener

4 Users interact with these graphical components

2 You write classes that implement the correct interfaceActionListener

Page 39: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

A Java GUI

Preview for writing a GUI1. Add imports such as import java.awt.*; 2. Have a class that extends JFrame (your class is a

JFrame)3. Add main to construct the instance of itself and

show it4. Add instance variables – include graphical

components that will be needed by other methods in the class

5. Lay out a GUI and initialize instance variables in the constructor

Page 40: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

The first 5 steps

import java.awt.*;import java.awt.*; import javax.swing.*;import javax.swing.*; public class SingleButtonFrame extends JFramepublic class SingleButtonFrame extends JFrame {{ public static void main(String[] args)public static void main(String[] args) { { // Construct an instance of this class and show it// Construct an instance of this class and show it SingleButtonFrame aWindow = new SingleButtonFrame();SingleButtonFrame aWindow = new SingleButtonFrame(); aWindow.setVisible(true);aWindow.setVisible(true); }} // To be "listened" to// To be "listened" to private JButton aButton; private JButton aButton;

public SingleButtonFrame()public SingleButtonFrame() { { // Lay out the GUI, initialize instance variables// Lay out the GUI, initialize instance variables // Have this object send some messages to itself// Have this object send some messages to itself setSize(200, 100);setSize(200, 100); setTitle("Listen to button");setTitle("Listen to button"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); aButton = new JButton("Click Me");aButton = new JButton("Click Me"); Container contentPane = getContentPane();Container contentPane = getContentPane(); contentPane.add(aButton, BorderLayout.NORTH);contentPane.add(aButton, BorderLayout.NORTH); } } // ...// ...

Page 41: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

No one is "Listening"Okay, now we have a GUI

○ but when run, nothing happensWanted: An object to listen to the button

that understands a specific message such as○ actionPerformed

Also need to tell the button who it can send the actionPerfomed message to○ Register the listener with this methodaddActionListener(ActionListener al)

Page 42: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Handling Events

6. Add a private inner class that can listen to the event that the graphical component will generate Your class must implement a listener interface to

guarantee that it has the expected methods: First up: ActionListener

7. In the constructor of the class that is a JFrame, register the instance of the listener so the component can later send messages to the listener’s actionPerformed methodevents occur anytime in the future--the listener is listening

(waiting for user generated events such as clicking a button or entering text into a text field)

Page 43: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

ActionEvent / ActionListener

When a JButton object is clicked, it constructs an ActionEvent object and sends it to the actionPerformed method of its listeners

To register a listener to a JButton, you need to send an addActionListener message to button

public void addActionListener(ActionListener al)public void addActionListener(ActionListener al)

○You need an ActionListener objectMake your class implement ActionListener

Page 44: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Inner class

Add an inner class ○ inner classes have access to the enclosing

classes' instance variables○ make it private since no one else needs to know

about it○ otherwise you need a separate class that gets the

graphical components passed as an argument

Page 45: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Have a class that implements ActionListener

// 6. inner class to listen to events private class ButtonListener implements ActionListenerprivate class ButtonListener implements ActionListener { { // No constructor needed here// No constructor needed here // Must have this method to implement ActionListener// Must have this method to implement ActionListener public void actionPerformed(ActionEvent anActionEvent) public void actionPerformed(ActionEvent anActionEvent) {{ System.out.println("Button was clicked.");System.out.println("Button was clicked."); }} }}

// 7. In the constructor of the class that extends JFrame,// 7. In the constructor of the class that extends JFrame,// register the instance of the listener so the component // register the instance of the listener so the component // can later send messages to that object// can later send messages to that objectButtonListener aListener = new ButtonListener();ButtonListener aListener = new ButtonListener();aButton.addActionListener(aListener);aButton.addActionListener(aListener);

Caution: this is easy to forget. It is an error no one will tell you about

Page 46: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Polymorphism through interfaces

Can have many ActionListener objects○ Any class that implements ActionListener○ may need a different class for every button and text

field in the GUIBut they all can be treated as ActionListener objectsThey can be passed as arguments to this method

public void addActionListener(ActionListener ae) Adds the specified action listener to receive action events from JButtons,

JTextFields, …Parameters: aListener - an instance of a class that implements the ActionListener

interface

Page 47: This Lecture Course Outline Brief review Design Patterns Collections GUI with Java Swing Java Networking

Assignment Compatible

Can pass instances of classes implementing an interface to the interface type parameter

addActionListener(ActionListener anyListener)

addActionListener(new ButtonListener());

addActionListener(new TextFieldListener());

ButtonListener and TextFieldListener must implement interface ActionListener