Algorithmic Programming II

Slides:



Advertisements
Similar presentations
Chapter 16 GUI Programming Basics GUI Overview Event-Driven Programming Basics GUI Classes and Packages A Simple Window Program JFrame Class Java Components.
Advertisements

Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
Graphical User Interfaces
Graphical User Interfaces (Part IV)
Java Software Development Paradigm Lecture # 12. Basics of GUI.
CS18000: Problem Solving and Object-Oriented Programming.
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Things to mention public static void main(String [] args) –The starting point for a free-standing Java application (i.e. one not run from the DrJava interactions.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Event Driven Programming and GUIs Part 3 CS221 – 4/15/09.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
© The McGraw-Hill Companies, 2006 Chapter 10 Graphics and event- driven programs.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Java's Collection Framework
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
A.k.a. GUI’s.  If you want to discuss your Lab 2 grade come see me this week. ◦ Office: 436 ERB. One hour prior to class ◦ Open to Appointments MWF 
Java Programming Chapter 10 Graphical User Interfaces.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
1 Java's Collection Framework By Rick Mercer with help from The Java Tutorial, The Collections Trail, by Joshua BlockThe Collections Trail.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Chapter 18 Java Collections Framework
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 13 : Swing I King Fahd University of Petroleum & Minerals College of Computer Science.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Copyright © 2002, Systems and Computer Engineering, Carleton University c-Gui3.ppt * Object-Oriented Software Development Part 18-c Building.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 19.1 Test-Driving the Shipping Hub Application.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
1 Interfaces in Java’s Collection Framework Rick Mercer.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
1 Java's Collection Framework Map and Sets. 2 Collection Framework  A collections framework is a unified architecture for representing and manipulating.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Graphical User Interface (GUI)
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
GUIs and Events Rick Mercer.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
CSC 205 Programming II Lecture 5 AWT - I.
A First Look at GUI Applications
“Form Ever Follows Function” Louis Henri Sullivan
Graphical User Interface (pronounced "gooey")
Java Programming: From Problem Analysis to Program Design,
Ellen Walker Hiram College
Presentation transcript:

Algorithmic Programming II

This Lecture Course Outline Brief review Java Networking 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 tools Make it easier for students to learn about such tools by themselves

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

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

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

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

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?

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

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

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";

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

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)

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

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.

Collection interfaces in java.util (Java 5)

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>

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

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)

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

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

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

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

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)

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

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

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

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

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

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

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

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

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

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 …

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

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

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

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

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

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); } // ...

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)

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)

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

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

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

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

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