Presentation is loading. Please wait.

Presentation is loading. Please wait.

Algorithmic Programming II

Similar presentations


Presentation on theme: "Algorithmic Programming II"— Presentation transcript:

1 Algorithmic Programming II

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

3 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 tools Make it easier for students to learn about such tools by themselves

4 Additional Reading and Materials
The course can only serve as a starting point Students are expected to learn some of the material by themselves The Java Tutorial: Material covered so far… Essential Java Classes — exceptions, IO, threads, … Collections — ADTs, the Java Collections Framework Swing — Introduction to the Swing GUI toolkit

5 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 sources Bruce Eckel Thinking in Java Thinking in Patterns

6 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

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

8 Abstract Data Type An 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?

9 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

10 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 classes Example interface : public interface BarnyardAnimal { public String sound(); }

11 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 { return "cluck";

12 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

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

14 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 promise that this class has int compareTo(T) Add compareTo method

15 Java's 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.

16 Collection interfaces in java.util (Java 5)

17 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>

18 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

19 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 allowed Set: A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2)

20 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

21 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

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

23 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

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

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

26 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

27 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

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

29 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

30 Building components So far we have an empty window
Let us add a button, a label, and an editable line First 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

31 Adding to the Content Pane
In 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

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

33 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

34 So what happens next? You can layout a real pretty GUI
You 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 …

35 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 movements clicks on hyperlinks, buttons, menu items Users pressing any key, selecting a list item

36 Example: Action Events
The 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

37 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 screen Examples FlowLayout GridLayout SpringLayout Events Signal that a user interacted with the GUI Examples: mouse clicks, keys pressed, hyperlinks selected

38 Java's Event Model JFrame JButton JTextField JMenuItem Listener
1 Layout Graphical Components JFrame JButton 4 Users interact with these graphical components JButton JTextField JMenuItem 3 You register objects that waits for messages from graphical components addActionListener 2 You write classes that implement the correct interface ActionListener Listener Listener Listener

39 A Java GUI Preview for writing a GUI
1. 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 it 4. 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

40 The first 5 steps import java.awt.*; import javax.swing.*;
public class SingleButtonFrame extends JFrame { public static void main(String[] args) { // Construct an instance of this class and show it SingleButtonFrame aWindow = new SingleButtonFrame(); aWindow.setVisible(true); } // To be "listened" to private JButton aButton; public SingleButtonFrame() { // Lay out the GUI, initialize instance variables // Have this object send some messages to itself setSize(200, 100); setTitle("Listen to button"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); aButton = new JButton("Click Me"); Container contentPane = getContentPane(); contentPane.add(aButton, BorderLayout.NORTH); } // ...

41 No one is "Listening" Okay, now we have a GUI
but when run, nothing happens Wanted: 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 method addActionListener(ActionListener al)

42 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 method events 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)

43 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) You need an ActionListener object Make your class implement ActionListener

44 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

45 Have a class that implements ActionListener
// 6. inner class to listen to events private class ButtonListener implements ActionListener { // No constructor needed here // Must have this method to implement ActionListener public void actionPerformed(ActionEvent anActionEvent) { System.out.println("Button was clicked."); } // 7. In the constructor of the class that extends JFrame, // register the instance of the listener so the component // can later send messages to that object ButtonListener aListener = new ButtonListener(); aButton.addActionListener(aListener); Caution: this is easy to forget. It is an error no one will tell you about

46 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 GUI But they all can be treated as ActionListener objects They 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

47 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


Download ppt "Algorithmic Programming II"

Similar presentations


Ads by Google