CSE 219 Patterns in Programming More Design Patterns.

Slides:



Advertisements
Similar presentations
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
Advertisements

Graphical User Interfaces (Part IV)
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
OOP Design Patterns Chapters Design Patterns The main idea behind design patterns is to extract the high level interactions between objects and.
 What are the basic GUI components we’ve learned so far? › JFrame › JPanel › JButton › JLabel › JTextArea › JTextField › JCheckBox › JRadioButton › Paint.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Java Swing Toolkit Graphics The key to effectively using graphics in Java is understanding: –the basic components of the graphics library –the patterns.
Object-Oriented Software Engineering PersonGui (Mark 2) Case Study.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Object-Oriented Analysis and Design
GUI and Event-Driven Programming Part 2. Event Handling An action involving a GUI object, such as clicking a button, is called an event. The mechanism.
Model View Controller (MVC) Architecture. Terminology and History MVC evolved from Smalltalk-80 Has become a key pattern in web based applications – If.
Advanced Java Class GUI, part 2. JComponent methods addXXXListener(XXXListener) repaint() – [optional arguments: delay and coordinates of sub-area to.
CPSC150 Week 12 Graphical User Interfaces Chapter 11.
Graphic User Interfaces Part 1. Typical GUI Screen from Microsoft Word What GUI “components” can you see? –Menus? Buttons? Labels? What else? –Anything.
Design Patterns and Graphical User Interfaces Horstmann ,
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Object Oriented Programming Ders 11: Interfaces Mustafa Emre İlal
עקרונות תכנות מונחה עצמים תרגול 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,
Introduction to Swing Components Chapter 14.  Part of the Java Foundation Classes (JFC)  Provides a rich set of GUI components  Used to create a Java.
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
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.
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.
Java Programming: Advanced Topics 1 Components and Facilities for Rich Graphical User Interfaces Chapter 7.
Chapter 12 1 TOPIC 13B l Buttons and Action Listeners Window Interfaces Using Swing Objects.
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.
Concurrent Programming and Threads Threads Blocking a User Interface.
EE2E1. JAVA Programming Lecture 6 Event handling and building user interfaces with Swing.
Graphical User Interfaces (Part 2) 1. View  view  presents the user with a sensory (visual, audio, haptic) representation of the model state  a user.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 35 MVC and Swing MVC.
Creating Windows. How can we use Java to create programs that use windows (GUI applications)? How can we use Java to create programs that use windows.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Object Oriented Programming.  Interface  Event Handling.
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.
(1) Introduction to Java GUIs Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu.
5-Jan-16 R Ramesh Swing. 5-Jan-16 R Ramesh An Introduction to Java Foundation Classes (JFC) A suite of libraries to assist programmers create enterprise.
Review_6 AWT, Swing, ActionListener, and Graphics.
Computer Science 209 GUIs Model/View/Controller Layouts.
1 CSE 331 Model/View Separation and Observer Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia.
Advanced Java Class Events. change in state initiated by system or user java.util.EventObject java.awt.event java.swing.event.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 15 : Swing III King Fahd University of Petroleum & Minerals College of Computer.
GUI Tutorial 2. What did we do last time?  Basic flow  instance variables, set up in ctor, close operation, size, visible  JFrame  Event-driven programming.
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.
View  view  presents the user with a sensory (visual, audio, haptic) representation of the model state  a user interface element (the user interface.
Introduction to GUI in 1 Graphical User Interface 3 Nouf Almunyif.
Menus Pull-downs and popups. Tooltips –a ToolTip is a context-sensitive text string that is displayed in a popup window when the mouse rests over a particular.
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.
Clicker quiz 11/5/13 CSE 1102 Fall A. a FlowLayout B. a BorderLayout C. a GridGrouping D. a JSplitPane E. a GridLayout Suppose we want to to lay.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Chapter 6 Building Java GUIs. MVC Model View Controller The model passes its data to the view for rendering The view determines which events are passed.
A Quick Java Swing Tutorial
A First Look at GUI Applications
Advanced User Interfaces
GUIs Model/View/Controller Layouts
Graphical User Interface (pronounced "gooey")
Event-driven programming for GUI
Common Design Patterns
Design Patterns in Swing and AWT
Design Patterns in Swing and AWT
Graphical User Interface
Presentation transcript:

CSE 219 Patterns in Programming More Design Patterns

Reading Assignment Why Software Fails from IEEE Spectrum: – Software Hall of Shame –

GUIs & Patterns Patterns are commonly used throughout GUI packages –wide use of interfaces –Command Pattern - Event Programming for simple GUI controls –Observer Pattern - Event Handling for complex GUI controls (MVC) –Strategy Pattern for Layout Management

Command Abstraction For many GUIs, a single function may be triggered by many means (e.g., keystroke, menu, button, etc…) Try to link all similar events to the same listener The information concerning the command can be abstracted to a separate command object Two Common Java Approaches: 1.Specify a String for each command –have listener respond to each command differently 2.Make an Action object for each command make each command a listener for the events that trigger it Both techniques: –ensure commands are handled in a uniform way –require access to the necessary GUI controls to effect change

Example Suppose I wanted to create a simple GUI: –1 colored panel –2 buttons, yellow & red –2 menu items, yellow & red –clicking on the buttons or menu items changes the color of the panel Since the buttons & the menu items both perform the same function, they should be tied to the same commands –I could even add popup menu items

First Approach – Command Strings public class ColorCommandFrame1 extends JFrame implements ActionListener { private Toolkit tk = Toolkit.getDefaultToolkit(); private ImageIcon yellowIcon = new ImageIcon(tk.getImage("yellow_bullet.bmp")); private ImageIcon redIcon = new ImageIcon(tk.getImage("red_bullet.bmp")); private JPanel coloredPanel = new JPanel(); private JButton yellowButton = new JButton(yellowIcon); private JButton redButton = new JButton(redIcon); private JMenuBar menuBar = new JMenuBar(); private JMenu colorMenu = new JMenu("Color"); private JMenuItem yellowMenuItem = new JMenuItem(yellowIcon); private JMenuItem redMenuItem = new JMenuItem(redIcon); private JPopupMenu popupMenu = new JPopupMenu(); private JMenuItem yellowPopupItem = new JMenuItem(yellowIcon); private JMenuItem redPopupItem = new JMenuItem(redIcon); private static final String YELLOW_COMMAND = "YELLOW_COMMAND"; private static final String RED_COMMAND = "RED_COMMAND";

public ColorCommandFrame1() { super("ColorCommandFrame1"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setExtendedState(JFrame.MAXIMIZED_BOTH); initButtons(); initPopupMenu(); initMenu(); } private void initButtons() { yellowButton.setActionCommand(YELLOW_COMMAND); redButton.setActionCommand(RED_COMMAND); yellowButton.addActionListener(this); redButton.addActionListener(this); coloredPanel.add(yellowButton); coloredPanel.add(redButton); Container contentPane = getContentPane(); contentPane.add(coloredPanel); }

private void initPopupMenu() { yellowPopupItem.setActionCommand(YELLOW_COMMAND); redPopupItem.setActionCommand(RED_COMMAND); yellowPopupItem.addActionListener(this); redPopupItem.addActionListener(this); popupMenu.add(yellowPopupItem); popupMenu.add(redPopupItem); coloredPanel.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); }

private void initMenu() { yellowMenuItem.setActionCommand(YELLOW_COMMAND); redMenuItem.setActionCommand(RED_COMMAND); yellowMenuItem.addActionListener(this); redMenuItem.addActionListener(this); colorMenu.add(yellowMenuItem); colorMenu.add(redMenuItem); menuBar.add(colorMenu); setJMenuBar(menuBar); } public void actionPerformed(ActionEvent ae) { String command = ae.getActionCommand(); if (command.equals(YELLOW_COMMAND)) coloredPanel.setBackground(Color.YELLOW); else if (command.equals(RED_COMMAND)) coloredPanel.setBackground(Color.RED); } }

Second Approach – Action Object public class ColorCommandFrame2 extends JFrame { private Toolkit tk = Toolkit.getDefaultToolkit(); private ImageIcon yellowIcon = new ImageIcon(tk.getImage("yellow_bullet.png")); private ImageIcon redIcon = new ImageIcon(tk.getImage("red_bullet.png")); private JPanel coloredPanel = new JPanel(); private Action yellowAction = new YellowAction("Yellow", yellowIcon); private Action redAction = new RedAction ("Red", redIcon); private JButton redActionButton = new JButton(redAction); private JButton yellowActionButton = new JButton(yellowAction); private JMenuBar menuBar = new JMenuBar(); private JMenu colorMenu = new JMenu("Color"); private JMenuItem yellowMenuItem = new JMenuItem(yellowAction); private JMenuItem redMenuItem = new JMenuItem(redAction); private JPopupMenu popupMenu = new JPopupMenu(); private JMenuItem yellowPopupItem = new JMenuItem(yellowAction); private JMenuItem redPopupItem = new JMenuItem(redAction);

public ColorCommandFrame2() { super("ColorCommandFrame2 - Action Object"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setExtendedState(JFrame.MAXIMIZED_BOTH); initButtons(); initPopupMenu(); initMenu(); } private void initButtons() { coloredPanel.add(yellowActionButton); coloredPanel.add(redActionButton); Container contentPane = getContentPane(); contentPane.add(coloredPanel); }

private void initPopupMenu() { popupMenu.add(yellowPopupItem); popupMenu.add(redPopupItem); coloredPanel.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); }

private void initMenu() { colorMenu.add(yellowMenuItem); colorMenu.add(redMenuItem); menuBar.add(colorMenu); setJMenuBar(menuBar); } public class YellowAction extends AbstractAction { public YellowAction(String text, ImageIcon icon) { super(text, icon); } public void actionPerformed(ActionEvent e) { coloredPanel.setBackground(Color.YELLOW); } } public class RedAction extends AbstractAction { public RedAction(String text, ImageIcon icon){ super(text, icon); } public void actionPerformed(ActionEvent e) { coloredPanel.setBackground(Color.RED); } }

More Complex Controls Controls like tables, trees, lists, combo boxes may contain much data as well as functionality For controls like these, data is managed separate from the view What type of design pattern could we use? –many similar types of software problems –solution: Observer pattern – MVC Must be used for GUI controls when contents change Ex: combo box for browser address bar –ability to add more addresses

Observer Pattern (MVC) Model –data structure, no visual representation –notifies views when something interesting happens Views –visual representations –views attach themselves to model in order to be notified Controllers –handling of events –listeners that are attached to view in order to be notified of user interaction (or otherwise) MVC Interaction –controller updates model –model tells view that data has changed –view redrawn

ControllerModelView updateData notify return repaint

MVC Architecture ModelView Controller The model passes its data to the view for rendering The view determines which events are passed to the controller The controller updates the model based on events received

Example of a Temperature Model public class TemperatureModel extends Observable { private double temperatureF = 32.0; public double getF(){return temperatureF;} public double getC(){return (temperatureF ) * 5.0 / 9.0;} public void setF(double tempF) {temperatureF = tempF; setChanged(); notifyObservers(); } public void setC(double tempC) {temperatureF = tempC*9.0/ ; setChanged(); notifyObservers(); } }

Common Model Interfaces BoundedRangeModel for JSlider, JProgressBar, JScrollBar ComboBoxModel for JComboBox ListModel for JList TableModel for JTable TreeModel for JTree

Trees Used to display a hierarchical structure –File structure, browsing history, etc…

Editing To edit the tree, you must go through the model: JTree tree = new JTree(… TreeModel model = tree.getModel(); // Insert Node model.insertNodeInto(… // Remove Node model.removeNodeFromParent(… // Change Node model.nodeChanged(… // UPDATING THE MODEL WILL NOW AUTOMATICALLY UPDATE THE // VIEW (JTree) THANKS TO MVC!

Layout Managers A layout manager uses an algorithm to position and size GUI components for a given container –When the user resizes the container, the layout manager automatically reflows the components to fill the available space LayoutManager –An interface in the Java class library –Describes how a Container and a layout manager communicate. –It describes several methods which: Handle resizing Handle components added to or removed from the container. Size and position the components it manages.

Strategy Pattern Place essential steps for an algorithm in a strategy interface –different methods represent different parts of the algorithm –classes implementing this interface customize methods LayoutManager s use this pattern –you may use a pre-existing LayoutManager –you may create your own LayoutManager define a class that implements LayoutManager Define abstract methods from LayoutManager interface however you want your manager to behave –addLayoutComponent –layoutContainer –minimumLayoutSize –preferredLayoutSize –removeLayoutComponent you may use to setLayout for Java Components to use your layout Java Components use LayoutManager methods to draw themselves