Frameworks: Swing Case Study David Talby. Frameworks A reusable, semi-complete application An object-oriented technique Reuse of both code & design Hollywood.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
Unit 091 Introduction to GUI Programming Introduction to User Interfaces Introduction to GUI Programming GUI Design Issues GUI Programming Issues Java.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
1 Chapter 7 Graphics and Event Handling. 2 Overview The java.awt and javax.swing packages and their subpackages support graphics and event handling. Many.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Java Swing Toolkit Graphics The key to effectively using graphics in Java is understanding: –the basic components of the graphics library –the patterns.
Frameworks David Talby. Frameworks “ A reusable, semi-complete application that can be specialized to produce a custom application ” “ A set of cooperating.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
A Guide to Oracle9i1 Creating an Integrated Database Application Chapter 8.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
Unit 111 Java GUI Components and Events  Learning Outcomes oDistinguish between GUI components and containers. oIdentify and distinguish top-level containers.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Graphical User Interface (GUI) Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
Introduction to Java Swing “We are the sultans of swing” – Mark Knopfler.
Frameworks David Talby. June 14, 2006 Object Oriented Design Course 2 Frameworks “ A reusable, semi-complete application that can be specialized to produce.
Java Programming Chapter 10 Graphical User Interfaces.
MVC pattern and implementation in java
Software Construction Lecture 10 Frameworks
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
Java Swing, Events and MVC Optional Readings: Eckel’s Thinking in Java: Chap 14 (
CS377A: A Programming Approach to HCI Jan Borchers Spring Swing Refresher David Merrill 5/14/2002
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.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
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.
GUI Chapter 10 Graphics context and objects Creating a window based application JFrame, JTextField, JButton Containers and Controls Graphics commands Layout.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
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.
GoF: Document Editor Example Rebecca Miller-Webster.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
SWING 101. IF YOU GET LOST - IMPORTANT LINKS  Swing articles:
1 Java Swing - Lecture 2 Components and Containment Boriana Koleva
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 35 MVC and Swing MVC.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Software Design 5.1 From Using to Programming GUIs l Extend model of "keep it simple" in code to GUI  Bells and whistles ok, but easy to use and hide.
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, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
Swinging in Your Java Playground. Background Swing is a part of the Java Foundation Classes (JFC). The JFC is made up of features intended to give a programmer.
Swing - 2 Session 13. Swing - 2 / 2 of 38 Objectives (1) Discuss trees and tables Discuss progress bars Discuss MVC architecture Describe menus.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Java Swing, Events Readings: Just Java 2: Chap 19 & 21, or Eckel’s Thinking in Java: Chap 14 Slide credits to CMPUT 301, Department of Computing Science.
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.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
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:
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Frameworks David Talby.
Java Look-and-Feel Design Guidelines
Review: Java GUI Programming
Lecture 27 Creating Custom GUIs
Java Programming: From Problem Analysis to Program Design,
A Quick Java Swing Tutorial
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
Steps to Creating a GUI Interface
A Quick Java Swing Tutorial
Presentation transcript:

Frameworks: Swing Case Study David Talby

Frameworks A reusable, semi-complete application An object-oriented technique Reuse of both code & design Hollywood Principle + Hooks Enables the creation of Components Origin of many design patterns Many application domains – Our focus: User interfaces

Swing Java ’ s User Interface FW since JDK 1.2

The Problem Hardware and operating system support primitive I/O operations Drawing pixels and lines on the screen – Class java.awt.Graphics has drawLine(), setColor(), fillRect(), setFont(), … methods Receiving user input – Reading file and device input streams – Platform-dependent

The Problem II Visual components are not reused – Should be in standard library – Look-and-feel should be consistent – Easy to create / buy new visual components Design of user interface is not reused – Separating visual design, data structures, user input handling and applicative code Code is not platform-independent A lot of code & design is required

Swing Features Wide variety of visual components – Button, Label, List, Panel, Table, Tree, … – Standard Dialog Boxes (Open, Save, Color, …) Pluggable look-and feel – Platform independence – Dynamically changeable MVC architecture – Facilitates writing components or look-and-feels Action objects – Shared commands in toolbars and menus – Generic Undo capability

Swing Features II Keystroke Handling – Global, form, container and component shortcuts – Conflict management Nested Containers – Windows, Dialogs, Frames, Panels, Tables, … – Virtually anything can be in anything, at any depth Text Manipulation – HTML and RTF editing (multi-font, colors, etc.) Accessibility – Alternative user interface support: Braille, sound…

A Simple Form We’ll use JButton and JTextField Inside a JPanel container Inside a JFrame (a window container) Whose main() method will run the show The application will show this dialog box:

Anonymous Classes Syntax We need a little extra Java syntax first Given an interface, it’s possible to construct an object that implements it by providing an implementation during the initialization For example, since the ActionListener interface only defines the actionPerformed() method: ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e) { textField.setText(""); } } ); The “new” class is an inner class of its scope This is the anonymous inner classes syntax

The Simple Form Code Step 1 is to subclass JPanel: class SimplePanel extends JPanel { JTextField textField; JButton button; public SimplePanel() { button = new JButton("Clear Text"); add(button); textField = new JTextField(10); add(textField); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textField.setText(""); } }); } }

The Simple Form Code II Step 2 is to subclass JFrame: public class SimplePanelTest extends JFrame { static final int WIDTH = 300; static final int HEIGHT = 100; SimplePanelTest(String title) { super(title); SimplePanel simplePanel = new SimplePanel(); Container c = getContentPane(); c.add(simplePanel, BorderLayout.CENTER); }

The Simple Form Code III The same class also contains main(): public static void main(String args[]) { JFrame frame = new SimplePanelTest("SimplePanel Example"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setSize(WIDTH, HEIGHT); frame.setVisible(true); } } The framework takes over after main()

The Framework in Action Inversion of Control – Event loop is handled by a Swing thread – Hardware- and OS-specific input formats are translated to standard interfaces Hooks – Building the visual controls is white-box style – Registering to events is black-box style Design Patterns – Composite: JPanel.add(Component c) – Observer: JButton.addActionListener(al)

Component Hierarchy Common ancestor is javax.swing.JComponent – Listener registration for keyboard & mouse events – Painting infrastructure: double buffering, borders – Keyboard mapping, custom properties, tool-tips, look and feel, accessibility, serialization, … Except for top-level heavyweight containers: – JFrame, JDialog, JApplet, JWindow Any subclass of JComponent is a component – Easy to write ComboBox, DatePicker, ImageList – Standard dialog boxes are implemented this way

Editor Actions All text editors share some commands – Cut, Copy, Paste, Clear, Insert Special Char, … These are encapsulated in Action objects Each text component supports getActions() Actions are added to menus, toolbars, etc: JMenu menu = new JMenu(“Edit”); menu.add(cutAction); Action objects are shared by default – Don ’ t modify them Follows the Command design pattern

Text Editor Kits Editor kits can do two things – Read & write documents in a particular format – Hold a list of actions supported by that format Predefined kits: Default, Styled, HTML, RTF Editor kits dynamically define text editors: – Each EditorKit registers with the JEditorPane – When a file is loaded into the pane, it checks its format against the registered editor kits – The matching kit reads, writes and edits the text Follows the State design pattern

Creating Kits To support a new format & actions – Extend DefaultEditorKit or StyledEditorKit – Kit may store date about its current EditorPane – Call JEditorPane.registerEditorKitForContentType – Kits are created by cloning the prototype – However, this is done by reflection on class name

Documents and Views Editor Kits follow the Builder design pattern Input: The Document interface – Content, Mutation, Notification, Properties – Structure: an Hierarchy of Element objects Output: The View interface – Participate in layout, paint its portion of document, translate coordinate systems, respond to events These interfaces are only used internally – To enable reuse of builder, data Structure, view hierarchy and data parser separately

The HTMLEditorKit An Abstract Factory for creating views – Interface ViewFactory has View create(Element e) – There are HTMLViewFactory and BasicTextUI Very customizable using Factory Methods – Replace document: override createDefaultDocument – Replace views: override getViewFactory – Replace parser: override getParser – EditorKit responsible only for read() and write() Multiple views per document, for printing

Keystroke Mapping A KeyMap is a map A text component has one or more Keymaps – By default, only JTextComponent.DEFAULT_KEYMAP – Can be modified, but the default Keymap is shared Custom Keymaps can be added and removed – Adding requires a name and a parent Keymap – Then, addActionForKeyStroke() can modify it Keymap matching is by most-specific-first Follows the Chain of Responsibility Pattern

Undo / Redo Package javax.swing.undo offers UndoableEdit – Has undo(), redo(), canUndo(), canRedo(), die(), isSignificant(), getPresentationName() methods – Package offers an AbstractUndoableEdit class – And a CompoundEdit class for composite commands Class UndoManager manages done commands – Extends CompoundEdit - has addEdit() method – undo(), redo(), setLimit(), trimEdits(), undoTo(), redoTo(), undoOrRedo(), discardAllEdits(), … Each text component supports: addUndoableEditListener(UndoableEditListener uel)

Model / View / Controller The Basic User Interface Design Pattern – Origin is SmallTalk-80, the first OOFW

MVC Participants Model – Data structure of displayed data – Notifies observers on state change View – Paints the data on the screen – Observer on its model Controller – Handles user input – Changes model, which causes views to update

MVC by Example ButtonModel class – Private color field, setColor() and getColor() – setColor() will also notify observers ButtonView class – Gets a ButtonModel in its constructor, stores is in a private field and registers to it – Has a public paint() method, called on notification MyController class – Initialized with both model and view objects – Handles user input events (mouse/keyboard/etc.) by changing the model and the view

MVC Benefits Three elements can be reused separately Synchronized user interface made easy – Multiple views observe one model Models know nothing about presentation – Easy to modify or create views – Easy to dynamically change views More efficient – Shared models & controllers save memory – Easy to maintain pools of views and models

Document / View View and Controller are often merged – MFC: “Document” and “View” – Swing (Text Editors): “Document” and “View” – Swing (Components): “Model” and “Delegate”

Swing and MVC There are several levels of using MVC “Manually”, to synchronize complex views – A file explorer, with a tree and current dir In forms or complex components – Custom form logic to synchronize its field – A table or tree and its sub-components – A variation of the Mediator design pattern A component is a façade to two objects: – Model: data structure of property values – Delegate: handles painting and user input

MVC Inside a Component Each component is a façade for two objects – Each components defines getModel() and getUI() – Usually only one component per model and delegate UIManager is a singleton – Holds current look & feel properties ComponentUI defines drawing interface – javax.swing.plaf.* includes ButtonUI, SliderUI, …

Changing Look & Feel The default is in a text configuration file homepath/lib/swing.properties At runtime before creating components: UIManager.setLookAndFeel( “com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); At runtime after initialization: UIManager.setLookAndFeel(lnfName); SwingUtilities.updateComponentTreeUI(frame); frame.pack(); // in case sizes have changed Replaces the ComponentUI object – Follows the Strategy pattern for paint()

The Façade Pattern A flexible framework becomes very complex It is important to provide simple façades JEditorPane class – No need to know EditorKit & its subclasses, Document, Element, View, ViewFactory, KeyMap, … JButton class – No need to know ComponentModel, ComponentUI, UIManager, LookAndFeel, … Provide users only with concepts they know Button, Window, Action, Menu X Document, ViewFactory, EditorKit

Other Features Swing supports several other features that we don’t have time to cover: – Drag & Drop – Printing – Internationalization – Trees and Tables – Menus & Popup menus – Layout Management Other standard Java graphic libraries: – 2D drawing, 3D drawing, Multimedia

Summary Swing is a classic OOD framework – Contains a lot of domain knowledge – Highly customizable through design patterns – Comes with a set of implemented components – Also intended for writing new ones – Inversion of control + hooks It’s a medium-sized framework – Several hundred classes and interfaces – Plus free & commercial 3 rd party components