Abstract Data Types: stepping back from specifics.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
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.
Java Foundation Classes (JFC/Swing) Carl Alphonce revised Spring 2007 (with contributions from Alan Hunt)
OOP Design Patterns Chapters Design Patterns The main idea behind design patterns is to extract the high level interactions between objects and.
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,
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Agenda –interfaces and realization –type hierarchy –introduction to graphics and event handling.
Things to mention public static void main(String [] args) imports comments –block comments /* … */ –single-line comments // –javadoc comments and tags.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
JFC/Swing lectures O BSERVER PATTERN – general form Idea: decouple event from event handling Concrete Observable Abstract Observable Concrete Observer.
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
Java Swing Toolkit Graphics The key to effectively using graphics in Java is understanding: –the basic components of the graphics library –the patterns.
Swing CS-328 Dick Steflik John Margulies. Swing vs AWT AWT is Java’s original set of classes for building GUIs Uses peer components of the OS; heavyweight.
Object-Oriented Software Engineering Java with added Swing.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
Lecture 19 Graphics User Interfaces (GUIs)
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Abstract Data Types (ADTs) An ADT consists of: –a set of values –a set of operations on those values Rational numbers –15/7, -3/4, 123/1, 0/1 (but NOT.
1 Object Oriented Design & Patterns Part 1. 2 Design Patterns Derived from architectural patterns: –rules for design of buildings –describe common problems,
Graphics without NGP The key to effectively using graphics in Java is understanding: –the basic components of the graphics library –the patterns that are.
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 
Design Patterns and Graphical User Interfaces Horstmann ,
Welcome to CIS 083 ! Events CIS 068.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Object Oriented Programming Ders 11: Interfaces Mustafa Emre İlal
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
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,
3461A Readings from the Swing Tutorial. 3461A Overview  The follow is the Table of Contents from the trail “Creating a GUI with JFC/Swing” in the “The.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Field Trip #19 Animations with Java By Keith Lynn.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
SWING IF YOU GET LOST - IMPORTANT LINKS  Swing articles:
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Concurrent Programming and Threads Threads Blocking a User Interface.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Ajmer Singh PGT(IP) JAVA IDE Programming - I. Ajmer Singh PGT(IP) GUI (Graphical User Interface) It is an interface that uses a graphic entities along.
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 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)
Developing GUIs With the Eclipse Visual Editor, Swing/AWT Edition David Gallardo.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
A Quick Java Swing Tutorial
CSC 205 Programming II Lecture 5 AWT - I.
A Quick Java Swing Tutorial
Ellen Walker Hiram College
Chap 7. Building Java Graphical User Interfaces
Graphical User Interfaces -- Introduction
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
A Quick Java Swing Tutorial
Graphical User Interface
Presentation transcript:

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.

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 independent  An ADT is language independent.  In Java, an ADT is typically specified in an interface.

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)

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.

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!

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!

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.

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.

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

JFC/Swing lectures Creating an ADT To define an ADT, we  Describe its data  Specify the operations on that data  Focus on “what”, not “how”.

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.

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)

Java Foundation Classes (JFC/Swing) Carl Alphonce revised Spring 2007 (with contributions from Alan Hunt)

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.

JFC/Swing lectures Overview  Patterns  Containers and Components  Threads

JFC/Swing lectures Some patterns used  O BSERVER  S TRATEGY  C OMPOSITE  D ECORATOR

JFC/Swing lectures Some patterns used - examples  O BSERVER – event handling  S TRATEGY – layout management  C OMPOSITE – containers are also components  D ECORATOR – scrollbars, streams

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.

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

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.

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

JFC/Swing lectures Composite Pattern

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

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.

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

JFC/Swing lectures O BSERVER PATTERN – general form Idea: decouple event from event handling Concrete Observable Abstract Observable Concrete Observer 0..* Abstract Observable attach(Observer) detach(Observer) notifyObservers() Abstract Observable Abstract Observer update()

JFC/Swing lectures JFC use of O BSERVER  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.

JFC/Swing lectures O BSERVER 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 Observable ActionListener actionPerformed(ActionEvent ) attach  addActionListener detach  removeActionListener notifyObservers  fireActionPerformed update  actionPerformed

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

JFC/Swing lectures D ECORATOR  A decorator adds functionality while maintaining an interface.  One example: InputStreamReader wraps InputStream BufferedReader wraps InputStreamReader  Another example: JScrollPane wraps Jlist

JFC/Swing lectures S TRATEGY  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.

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.

JFC/Swing lectures BorderLayout  The BorderLayout manager creates an object that resembles a picture with a four sided frame, or border.

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.

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.

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.

JFC/Swing lectures Topic overview  Processes & Threads  Containers (graphical)  Components  Layout managers  Event handling  Inner classes

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

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

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

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.

JFC/Swing lectures Runnable interface  The Runnable interface specifies one method: public interface Runnable { /** * When an object implementing interface Runnable is used * to create a thread, starting the thread causes the object's * run method to be called in that separately executing * thread. * * The general contract of the method run is that it may * take any action whatsoever. * java.lang.Thread#run() */ public abstract void run(); }

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.

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.

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

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

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

JFC/Swing lectures A simple component  A JLabel is a component that can display text or an image.  Go look at example_set_2

JFC/Swing lectures Layout managers  What happens if we add another JLabel?  Go look at example_set_3

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.

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:

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

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.

JFC/Swing lectures Event handling - 3  Go look at example_set_4

JFC/Swing lectures Putting it all together  Go look at example_set_5

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

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.

JFC/Swing lectures Controls  Swing provides many controls  “Separable model architecture”  We’ll touch on: check box list menu spinner your choice, time permitting

JFC/Swing lectures Views  Views are information displays that cannot be edited. labels, progress bars, tooltips

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.

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.

JFC/Swing lectures JScrollPane  (see session5.scrollpane)

JFC/Swing lectures JSplitPane  (see session5.splitpane)

JFC/Swing lectures JTabbedPane  (see session5.tabbedpane)  Show tooltips.  Show mnemonics.

JFC/Swing lectures Combining containers!  (see session5.combined)

JFC/Swing lectures JCheckBox  (see session5.checkbox)

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

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.

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.