Outline. Observer Pattern: Pitfalls. Observer Applications
|
|
- Aileen Short
- 5 years ago
- Views:
Transcription
1 Outline Observer Pattern: Pitfalls NotifyObservers Invocation Problem M:N Problem ConcurrentModificationException Problem Cyclic Dependency Problem Causality of State Changes Problem Memory Management Problem Multi Model Problem Observer Applications 23 March
2 Observer Pattern: Structure Structure diagram Subject and Concrete Subject may be combined in a single class Observer may be an interface 23 March
3 Observer Pattern: Collaborations :ConcreteSubject :ConcreteObserver :ConcreteObserver setstate notify update update 23 March
4 Observer Pattern: Sample Code (1/2) interface Observer { void update(); abstract class Observable { private final List<Observer> observers = new ArrayList<>(); public void addobserver(observer o) { observers.add(o); public void removeobserver(observer o) { observers.remove(o); protected void notifyobservers() { for(observer obs : observers) { obs.update(); 23 March
5 Observer Pattern: Sample Code (2/2) class Sensor extends Observable { private int temp; public int gettemperature() { return temp; public void settemperature(int val) { temp = val; notifyobservers(); class SensorObserver implements Observer { private Sensor s; SensorObserver (Sensor s) { this.s = s; s.addobserver(this); public void update() { System.out.println("Sensor has changed, new temperature is " + s.gettemperature()); 23 March
6 Invocation of notifyobservers When is notifyobservers called Automatically at every state change => many updates Explicitly after a set of change operations => client responsibility Approaches to reduce number of updates Asynchronous update at idle time AWT/Swing repaint registers an asynchronous request that this component needs to be repainted => multiple calls to repaint may be combined Here, "observer" is the actual "paint" method which reacts on changes java.util.observable: explicit, but change operations call setchanged notifyobservers becomes only active if ischanged() == true (notifyobservers calls clearchanged) notifyobservers could be invoked regularly (as a background task) Registration for specific message types only To be checked within observable class 23 March
7 java.util.observable public interface Observer { void update(observable o, Object arg); public class Observable { private boolean changed = false; // Marks this Observable as having been changed protected void setchanged() { changed = true; // Indicates that this object has no longer changed, // or that it has already notified all of its observers // of its most recent change. protected void clearchanged() { changed = false; // Tests if this object has changed. public boolean haschanged() { return changed; 23 March
8 java.util.observable // If this object has changed, as indicated by the // haschanged method, then notify all of its observers // and then call the clearchanged method to indicate // that this object has no longer changed. public void notifyobservers(object arg) { if (!changed) return; Object[] copy = obs.toarray(); clearchanged(); // before notification! for (int i = copy.length-1; i>=0; i--) ((Observer)copy[i]).update(this, arg); March
9 Missing Multiple Inheritance java.util.observable Provides implementation of an Observable Can only be used if extension is not defined in its own inheritance hierarchy Model Observable * Observer Consequence Code duplication java.util.observable is not used in the Java library (and will be removed) Solution Composition (twin classes) ObservableModel 23 March
10 Observable Twin Classes Twin Classes Model Observable * Observer Observable- Model Observer- Registry getsource Concrete- Observer ObservableModel can be used where Models are expected ObserverRegistry can be used where Observables are expected public class Model { private int value; public int getvalue() { return value; public void setvalue(int value) { this.value = value; 23 March
11 Observable Twin Classes Twin Classes public class ObservableModel extends Model { private final ObserverRegistry<Model> reg = new ObserverRegistry<>(this); public Observable getobservable() { return reg; public void addobserver(observer obs) { public void setvalue(int value) { super.setvalue(value); reg.setchanged(); reg.notifyobservers(); 23 March
12 Observable Twin Classes Twin Classes public class ObserverRegistry<T> extends Observable { private final T owner; public ObserverRegistry(T trueobservable) { this.owner = trueobservable; public T gettrueobservable() { return owner; // lift visibility into this package protected void setchanged() { super.setchanged(); protected void clearchanged() { super.clearchanged(); Lifting necessary. setchanged is declared protected, but in another package! 23 March
13 Observable Twin Classes Twin Classes public class PrintObserver implements Observer { public void update(observable obs, Object arg) { Model m = ((ObserverRegistry<Model>) obs).gettrueobservable(); System.out.println("new value: " + m.getvalue()); public class Test { public static void main(string[] args) { ObservableModel model = new ObservableModel(); Observer obs = new PrintObserver(); model.addobserver(obs); model.setvalue(5); model.setvalue(10); 23 March
14 Many Observables / Observers Observable Observable Observable Observable Observable Observer Observer Observer Observer Observer 23 March
15 Many Observables / Observers Observable Observable Observable Observable Observable Observer Observer Observer Observer Observer 23 March
16 Many Observables / Observers Observable Observer Mediator public class Mediator extends Observable implements Observer { public void update(object source, Object arg){ notifyobservers(source, arg); 23 March
17 Problem: Concurrent Modification in notify public void addobserver(observer o) { observers.add(o); public void removeobserver(observer o) { observers.remove(o); protected void notifyobservers(object arg) { for(observer obs : observers) { obs.update(this, arg); Problem: ConcurrentModificationException Collection over which one iterates must not be changed public class OnceObserver implements Observer { public void update(observable source, Object arg) { System.out.println("received update from "+source); source.removeobserver(this); 23 March
18 Problem: Concurrent Modification in notify Solution 1: Perform notification on a copy of the observer list protected void notifyobservers() { Observer[] copy; copy = observers.toarray(new Observer[observers.size()]); for (Observer obs : copy) { obs.update(this); protected void notifyobservers() { for(observer o : new ArrayList<>(observables)) { o.update(this); 23 March
19 Problem: Concurrent Modification in notify Solution 2: Delay add/removeobserver calls private static class Mutation { private final Observer observer; private final boolean add; public Mutation(Observer observer, boolean add) { this.observer = observer; this.add = add; private List<Mutation> pendingmutations = new LinkedList<>(); private int level = 0; public void addobserver(observer o) { if(level > 0) { pendingmutations.add(new Mutation(o, true)); else { observers.add(o); public void removeobserver(observer o) { if(level > 0) { pendingmutations.add(new Mutation(o, false)); else { observers.remove(o); 23 March
20 Problem: Concurrent Modification in notify... protected void notifyobservers() { level++; for (Observer obs : observers) obs.update(this); level--; if(level == 0) { for(mutation m : pendingmuts) { if(m.add) observers.add(m.observer); else observers.remove(m.observer); pendingmutations.clear(); 23 March
21 Problem: Concurrent Modification in notify Solution 3: Copy the observer list upon modification private List<Observer> observers = new CopyOnWriteArrayList<>(); public void addobserver(observer o) { observers.add(o); public void removeobserver(observer o) { observers.remove(o); protected void notifyobservers(object arg) { for(observer obs : observers) { obs.update(this, arg); CopyOnWriteArrayList is a (thread-safe) variant of ArrayList in which all mutative operations are implemented by making a fresh copy of the underlying array. 23 March
22 Problem: Cyclic Dependencies ItemListener JCheckBox- MenuItem ColorModel ColorListener 23 March
23 Problem: Cyclic Dependencies Notification Sequence 23 March
24 Problem: Cyclic Dependencies Solution 1: Break recursion in the color listener implementation public void colorvaluechanged(color c) { if (isselected()!= c.equals(this.color)) setselected(c.equals(this.color)); Solution 2: Break recursion in (subclass of) JCheckBoxMenuItem public void setselected(boolean b) { if (b!= isselected()) super.setselected(b); 23 March
25 Problem: Cyclic Dependencies Solution 3: Break recursion in ItemListener implementation private boolean updating = false; public void itemstatechanged(itemevent e) { if(!updating) { updating = true; if (e.getstatechange() == ItemEvent.SELECTED) { model.setcolor(color); updating = false; instead of comparing the value to be set on the model with the existing value, this solution checks for recursive invocations using a flag => changes performed during a notification would not be handled 23 March
26 Problem: Cyclic Dependencies Solution 4: Break recursion in the color model public class ColorModel { private Color color; public void setcolor(color color) { if (!color.equals(this.color)) { this.color = color; notify(color);... General rule: Propagate changes only if the model really changed 23 March
27 Problem: Cyclic Dependencies Solution 5: Use ActionListener instead of an ItemListener Actions are only fired if an event is initiated over the keyboard or over the mouse Whenever the color is changed over the ColorModel, then the JCheckBoxMenuItem is changed and an ItemEvent is fired, but no listener is registered for that and thus the recursion is broken General Rule: Avoid recursion! Always break the recursion in a model 23 March
28 Problem: Causality of Changes Causality How can we assert that notifications appear at the Observers in the same order as they were applied to the model 23 March
29 Example Observable Document Observers CorrectionListener TextFieldListener Operation (c) is added in front of FHNW 23 March
30 Problem: Causality of Changes Solutions Queuing of notifications: Notifications triggered by recursive state changes are delayed until all pending changes have been notified Model and notifications are out of sync, i.e. when an insert character is notified, this character may already have been removed from the model Queuing of state changes Model becomes asynchronous, i.e. state change operations are not executed immediately => difficult to program Prohibit state changes during notification 23 March
31 Problem: Memory Management Example ActionListener * 1 Multicast- Panel newbutton new: JButton {Creates closeallbutton closeall: JButton SimpleFrame buf 23 March
32 Problem: Memory Management MulticastPanel: ActionListener (new button) SimpleFrame f = new SimpleFrame(); f.settitle("window " + counter++); f.setsize(250, 150); f.setvisible(true); closeallbutton.addactionlistener(f); SimpleFrame: ActionListener (close all button) public void actionperformed(actionevent evt) { this.dispose(); // Releases all of the native screen // resources used by this window 23 March
33 Problem: Memory Management Memory Leaks Despite the existence of a GC, memory leaks can occur Remember to remove registered observers before you release an object public void actionperformed(actionevent evt) { JButton closeallbutton = (JButton)evt.getSource(); closeallbutton.removeactionlistener(this); this.dispose(); Alternative solution: use weak references means that the listener is only registered in the observable as long as there exists a strong reference to it 23 March
34 Problem: What is the model Multi-Models Assume that we represent each channel of our color as a separate model Simplifies implementations of the scrollbars / textfields red green blue Consequences Rules Each change of the color implies three updates Modelling is too fine granular, actually implementation details are published (like the representation of the color as RGB or HSV) Only changes from valid to valid state should be visible 23 March
35 Outline Observer Pattern: Pitfalls Observer Applications Model-View Separation in Swing Other applications 23 March
36 Model-View Separation in Swing All Swing controls refer to a model Model contains the data Model informs registered views when state changes View visualizes data View getmodel() setmodel(model m) * 1 Model Examples: JButton (ButtonModel) JScrollBar (BoundedRangeModel) JList (ListModel) JTree (TreeModel) JMenu (ButtonModel) 23 March
37 Model-View Separation in Swing View: setmodel If the model is set on a view, then the view registers itself (or an explicit listener implementation) as an observer of the model class View { private Model model; public Model getmodel(){ return model; public void setmodel(model model){ Model m = getmodel(); if(m!= null){ m.removemodellistener(ml); this.model = model; model.addmodellistener(ml); March
38 Model-View Separation in Swing Applications Several Controls may refer (display) the same model JTextField field = new JTextField(10); JPasswordField pwfld = new JPasswordField(10); JTextArea area = new JTextArea(5, 20); pwfld.setdocument(field.getdocument()); area.setdocument(field.getdocument()); 23 March
39 Model-View Separation in Swing Applications Model may be implemented by user Example: ListModel interface ListModel { getsize(); getelementat(int i); adddatalistener(datalistener dl); removedatalistener(datalistener dl); List entries can be computed on demand List entries can be fetched from data base ListModel may dynamically change its content 23 March
40 Model-View Separation in Swing Example: Fibonacci-Model N-th fibonacci number is computed on demand JList list = new JList( new AbstractListModel() { public int getsize() { return 10000; public Object getelementat(int n) { if(n == 0) return BigInteger.ZERO; BigInteger f0 = BigInteger.ZERO; BigInteger f1 = BigInteger.ONE; List entries can be computed on demand for(int i=1; i<n; i++) { List BigInteger entries can f2 be fetched = f0.add(f1); from data f0 base = f1; f1 = f2; ListModel may dynamically change its content return f1; ); 23 March
41 Observer Pattern: Other Applications AWT Event handling ActionListener, MouseListener, MouseMotionListener, Swing: Model-View separation JTable, JList Java Beans Event Notifications public void addpropertychangelistener(propertychangelistener) public void removepropertychangelistener(propertychangelistener) public void addvetoablechangelistener(vetoablechangelistener) public void removevetoablechangelistener(vetoablechangelistener) JavaFX data binding 23 March
42 JavaFX Data Binding 23 March
43 JavaFX Data Binding ChangeListener Can be added to every ObservableValue void addlistener(changelistener<? super T> listener); Change listener is invoked as soon as the value changes If the value is not changed => no invocation => no cycles Both the old and the new value is passed to the listener textfield.textproperty().addlistener( (observable, oldvalue, newvalue) -> { //... ); 23 March
44 JavaFX Data Binding Data Binding Properties can be bound unidirectionallly or bidirectionally StringProperty p1 = new SimpleStringProperty("p1"); IntegerProperty p2 = new SimpleIntegerProperty(); p2.bind(p1.length()); The value of p2 can no longer be set, but it depends on p1 StringProperty prop1 = new SimpleStringProperty(""); StringProperty prop2 = new SimpleStringProperty(""); prop2.bindbidirectional(prop1); If one value changes, the other is adjusted automatically 23 March
45 JavaFX Data Binding Bidirectional Binding public static <T> BidirectionalBinding bind( Property<T> property1, Property<T> property2) { BidirectionalBinding binding = new TypedGenericBidirectionalBinding<T>(property1, property2); property1.setvalue(property2.getvalue()); property1.addlistener(binding); property2.addlistener(binding); return binding; 23 March
46 JavaFX Data Binding Bidirectional Binding private static class TypedGenericBidirectionalBinding<T> { private final WeakReference<Property<T>> propertyref1; private final WeakReference<Property<T>> propertyref2; private boolean updating = false; public void changed(observablevalue<? extends T> sourceproperty, T oldvalue, T newvalue) { if (!updating) { final Property<T> p1 = propertyref1.get(); final Property<T> p2 = propertyref2.get(); if ((p1 == null) (p2 == null)) { if (p1!= null) { p1.removelistener(this); if (p2!= null) { p2.removelistener(this); else { updating = true; if (p1 == sourceproperty) { p2.setvalue(newvalue); else { p1.setvalue(newvalue); updating = false; 23 March
Outline. Design Patterns. Observer Pattern. Definitions & Classifications
Outline Design Patterns Definitions & Classifications Observer Pattern Intent Motivation Structure Participants Collaborations Consequences Implementation 1 What is a Design Pattern describes a problem
More informationare most specifically concerned with
Observer Behavioral Patterns Behavioral patterns are those patterns that are most specifically concerned with communication between objects Introduction Name Observer Also Known As Dependents, Publish-Subscribe
More informationIntroduction to Software Engineering (2+1 SWS) Winter Term 2009 / 2010 Dr. Michael Eichberg Vertretungsprofessur Software Engineering Department of
Introduction to Software Engineering (2+1 SWS) Winter Term 2009 / 2010 Dr. Michael Eichberg Vertretungsprofessur Software Engineering Department of Computer Science Technische Universität Darmstadt Dr.
More information6 The MVC model. Main concepts to be covered. Pattern structure. Using design patterns. Design pattern: Observer. Observers
Main concepts to be covered 6 The MVC model Design patterns The design pattern The architecture Using design patterns Inter-class relationships are important, and can be complex. Some relationship recur
More informationIntroduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014
Introduction to GUIs Principles of Software Construction: Objects, Design, and Concurrency Jonathan Aldrich and Charlie Garrod Fall 2014 Slides copyright 2014 by Jonathan Aldrich, Charlie Garrod, Christian
More informationEvent-driven Programming, Separation of Concerns, the Observer pattern and the JavaFX Event Infrastructure
Java GUIs in JavaFX Event-driven Programming, Separation of Concerns, the Observer pattern and the JavaFX Event Infrastructure 1 GUIs process inputs and deliver outputs for a computing system Inputs Click
More informationGUI Event Handlers (Part I)
GUI Event Handlers (Part I) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1 Agenda General event
More informationIT 313 Advanced Application Development
Page 1 of 10 IT 313 Advanced Application Development Final Exam -- March 13, 2016 Part A. Multiple Choice Questions. Answer all questions. You may supply a reason or show work for partial credit. 5 points
More informationHandout 14 Graphical User Interface (GUI) with Swing, Event Handling
Handout 12 CS603 Object-Oriented Programming Fall 15 Page 1 of 12 Handout 14 Graphical User Interface (GUI) with Swing, Event Handling The Swing library (javax.swing.*) Contains classes that implement
More informationObserver Pattern. CS580 Advanced Software Engineering October 31, Yu Sun, Ph.D.
Observer Pattern CS580 Advanced Software Engineering http://cs356.yusun.io October 31, 2014 Yu Sun, Ph.D. http://yusun.io yusun@csupomona.edu Announcements Quiz 5 Singleton Pattern Abstract Factory Pattern
More informationUppsala University. Assignment 3. Separation into Model-View TableModel ListModel ( multiple inheritance or adapter) Renderer (delegation)
ToDo-list Assignment 3 Separation into Model-View TableModel ListModel ( multiple inheritance or adapter) Renderer (delegation) A new component Extend Swing with your own design Theme Modify look&feel
More informationPackages: Putting Classes Together
Packages: Putting Classes Together 1 Introduction 2 The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance) Extending interfaces The features in basic
More informationContents Introduction 1
SELF-STUDY iii Introduction 1 Course Purpose... 1 Course Goals...1 Exercises... 2 Scenario-Based Learning... 3 Multimedia Overview... 3 Assessment... 3 Hardware and Software Requirements... 4 Chapter 1
More informationSolution register itself
Observer Pattern Context: One object (the Subject) is the source of events. Other objects (Observers) want to know when an event occurs. Or: several objects should be immediately updated when the state
More informationSD Module-1 Advanced JAVA
Assignment No. 4 SD Module-1 Advanced JAVA R C (4) V T Total (10) Dated Sign Title: Transform the above system from command line system to GUI based application Problem Definition: Write a Java program
More informationSD Module-1 Advanced JAVA. Assignment No. 4
SD Module-1 Advanced JAVA Assignment No. 4 Title :- Transform the above system from command line system to GUI based application Problem Definition: Write a Java program with the help of GUI based Application
More informationLab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in
Lab 4 D0010E Object-Oriented Programming and Design Lecture 9 Lab 4: You will implement a game that can be played over the Internet. The networking part has already been written. Among other things, the
More informationEVENTS, EVENT SOURCES AND LISTENERS
Java Programming EVENT HANDLING Arash Habibi Lashkari Ph.D. Candidate of UTM University Kuala Lumpur, Malaysia All Rights Reserved 2010, www.ahlashkari.com EVENTS, EVENT SOURCES AND LISTENERS Important
More informationJava Event Handling -- 1
Java Event Handling -- 1 Event Handling Happens every time a user interacts with a user interface. For example, when a user pushes a button, or types a character. 2 A Typical Situation: Scrollbar AWTEvent
More informationCONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13
CONTENTS Chapter 1 Getting Started with Java SE 6 1 Introduction of Java SE 6... 3 Desktop Improvements... 3 Core Improvements... 4 Getting and Installing Java... 5 A Simple Java Program... 10 Compiling
More informationJonathan Aldrich Charlie Garrod
Principles of Software Construction: Objects, Design, and Concurrency (Part 3: Design Case Studies) Introduction to GUIs Jonathan Aldrich Charlie Garrod School of Computer Science 1 Administrivia Homework
More informationM257 Past Paper Oct 2007 Attempted Solution
M257 Past Paper Oct 2007 Attempted Solution Part 1 Question 1 The compilation process translates the source code of a Java program into bytecode, which is an intermediate language. The Java interpreter
More informationGraphical User Interface (GUI)
Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware
More informationOutline. Composite Pattern. Model-View-Controller Pattern Callback Pattern
Outline Composite Pattern Motivation Structure Transparent vs Safe composite Applications: AWT & Swing Composite Problems: Alias references Model-View-Controller Pattern Callback Pattern 1 Composite Pattern
More informationGUI DYNAMICS Lecture July 26 CS2110 Summer 2011
GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI Statics and GUI Dynamics 2 Statics: what s drawn on the screen Components buttons, labels, lists, sliders, menus,... Containers: components that contain
More informationObserver pattern. Somebody s watching me...
Observer pattern Somebody s watching me... Purpose of the Observer pattern You have an object, Subject whose state many other objects are interested in. In particular, the many other objects are interested
More informationGUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline
Sequential vs. Event-driven Programming Reacting to the user GUI Program Organization Let s digress briefly to examine the organization of our GUI programs We ll do this in stages, by examining three example
More informationCS 180 Final Exam Review 12/(11, 12)/08
CS 180 Final Exam Review 12/(11, 12)/08 Announcements Final Exam Thursday, 18 th December, 10:20 am 12:20 pm in PHYS 112 Format 30 multiple choice questions 5 programming questions More stress on topics
More informationMarcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science
Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science mluckner@mini.pw.edu.pl http://www.mini.pw.edu.pl/~lucknerm } Abstract Window Toolkit Delegates creation and
More informationSoftware Design: Figures
Software Design: Figures Your assistant for this week Stefan Stevsic E-mail: stefan.stevsic@inf.ethz.ch Office: CNB H 100.9 You can simply stop by. You can also drop me a short e-mail to check if I m there.
More informationJava: Graphical User Interfaces (GUI)
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, and Bertrand Meyer Java: Graphical User Interfaces (GUI) With material from Christoph Angerer The essence of the Java Graphics API Application
More informationMultiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)
M257 MTA Spring2010 Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks) 1. If we need various objects that are similar in structure, but
More informationDesign Patterns. it s about the Observer pattern, the Command pattern, MVC, and some GUI. some more
Lecture: Software Engineering, Winter Semester 2011/2012 some more Design Patterns it s about the Observer pattern, the Command pattern, MVC, and some GUI Design Pattern *...+ describes a problem which
More informationLecture 3: Java Graphics & Events
Lecture 3: Java Graphics & Events CS 62 Fall 2017 Kim Bruce & Alexandra Papoutsaki Text Input Scanner class Constructor: myscanner = new Scanner(System.in); can use file instead of System.in new Scanner(new
More informationBasics of programming 3. Java GUI and SWING
Basics of programming 3 Java GUI and SWING Complex widgets Basics of programming 3 BME IIT, Goldschmidt Balázs 2 Complex widgets JList elements can be selected from a list JComboBox drop down list with
More informationCS410G: GUI Programming. The Model/View/Controller Pattern. Model. Controller. View. MVC is a popular architecture for building GUIs
CS410G: GUI Programming The Model/View/Controller design pattern provides a clean distinction between the your application s data (model), your GUI (view), and the how they interact (controller). Many
More informationExample Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.
COSC User Interfaces Module 3 Sequential vs. Event-driven Programming Example Programs DemoLargestConsole.java DemoLargestGUI.java Demo programs will be available on the course web page. GUI Program Organization
More informationGUI in Java TalentHome Solutions
GUI in Java TalentHome Solutions AWT Stands for Abstract Window Toolkit API to develop GUI in java Has some predefined components Platform Dependent Heavy weight To use AWT, import java.awt.* Calculator
More informationApplet which displays a simulated trackball in the upper half of its window.
Example: Applet which displays a simulated trackball in the upper half of its window. By dragging the trackball using the mouse, you change its state, given by its x-y position relative to the window boundaries,
More informationIntroduction to concurrency and GUIs
Principles of Software Construction: Objects, Design, and Concurrency Part 2: Designing (Sub)systems Introduction to concurrency and GUIs Charlie Garrod Bogdan Vasilescu School of Computer Science 1 Administrivia
More informationENGLISH Page 1 of 6. EXAM IN COURSE TDT4100 Object-Oriented Programming / IT1104 Programming, Advanced Course. Tuesday 29. Mai
ENGLISH Page 1 of 6 NTNU Norges teknisk-naturvitenskapelige universitet Fakultet for informasjonsteknologi, matematikk og elektroteknikk Institutt for datateknikk og informasjonsvitenskap EXAM IN COURSE
More informationContents Chapter 1 Introduction to Programming and the Java Language
Chapter 1 Introduction to Programming and the Java Language 1.1 Basic Computer Concepts 5 1.1.1 Hardware 5 1.1.2 Operating Systems 8 1.1.3 Application Software 9 1.1.4 Computer Networks and the Internet
More informationCOMP 401 Recitation 8. Observer Pattern
COMP 401 Recitation 8 Observer Pattern Agenda Quick review of the Observer pattern Worked example Exam review (~30 minutes) Quiz (on your own time) 2 Observer Pattern Problem Statement I have some object
More informationLecture 5: Java Graphics
Lecture 5: Java Graphics CS 62 Spring 2019 William Devanny & Alexandra Papoutsaki 1 New Unit Overview Graphical User Interfaces (GUI) Components, e.g., JButton, JTextField, JSlider, JChooser, Containers,
More informationCharlie Garrod Bogdan Vasilescu
Principles of So3ware Construc9on: Objects, Design, and Concurrency Part 2: Designing (sub-) systems A GUI design case study Charlie Garrod Bogdan Vasilescu School of Computer Science 1 Administrivia Homework
More informationIntroduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1
Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introducing Object Oriented Programming... 2 Explaining OOP concepts... 2 Objects...3
More informationWhat Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }
CBOP3203 What Is an Event? Events Objects that describe what happened Event Sources The generator of an event Event Handlers A method that receives an event object, deciphers it, and processes the user
More informationCS111: PROGRAMMING LANGUAGE II
CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 10(b): Working with Controls Agenda 2 Case study: TextFields and Labels Combo Boxes buttons List manipulation Radio buttons and checkboxes
More informationChapter 8. Java continued. CS Hugh Anderson s notes. Page number: 264 ALERT. MCQ test next week. This time. This place.
Chapter 8 Java continued CS3283 - Hugh Anderson s notes. Page number: 263 ALERT MCQ test next week This time This place Closed book CS3283 - Hugh Anderson s notes. Page number: 264 ALERT Assignment #2
More informationClass, Variable, Constructor, Object, Method Questions
Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx
More informationOutline. More on the Swing API Graphics: double buffering and timers Model - View - Controller paradigm Applets
Advanced Swing Outline More on the Swing API Graphics: double buffering and timers Model - View - Controller paradigm Applets Using menus Frame menus add a menu bar to the frame (JMenuBar) add menus to
More informationJava continued. Chapter 8 ALERT ALERT. Last week. MCQ test next week. This time. This place. Closed book. Assignment #2 is for groups of 3
Chapter 8 Java continued MCQ test next week This time This place Closed book ALERT CS3283 - Hugh Anderson s notes. Page number: 263 CS3283 - Hugh Anderson s notes. Page number: 264 ALERT Last week Assignment
More informationGraphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java
More informationOverview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008
Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object
More informationJava Fundamentals (II)
Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class
More informationDesign Patterns Design patterns advantages:
Design Patterns Designing object-oriented software is hard, and designing reusable object oriented software is even harder. You must find pertinent objects factor them into classes at the right granularity
More informationControl Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User
CSE3461 Control Flow Paradigms: Reacting to the User Control Flow: Overview Definition of control flow: The sequence of execution of instructions in a program. Control flow is determined at run time by
More informationGUI Event Handlers (Part II)
GUI Event Handlers (Part II) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1 Agenda Listener
More informationName: CSC143 Exam 1 1 CSC 143. Exam 1. Write also your name in the appropriate box of the scantron
Name: CSC143 Exam 1 1 CSC 143 Exam 1 Write also your name in the appropriate box of the scantron Name: CSC143 Exam 1 2 Multiple Choice Questions (30 points) Answer all of the following questions. READ
More informationVirtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.
1 - What if the main method is declared as private? 1. The program does not compile 2. The program compiles but does not run 3. The program compiles and runs properly ( From Lectuer # 2) 4. The program
More informationStatic Detection of Brittle Parameter Typing
Static Detection of Brittle Parameter Typing Michael Pradel, Severin Heiniger, and Thomas R. Gross Department of Computer Science ETH Zurich 1 Motivation void m(a a) {... } Object A.. B C D E F 2 Motivation
More information15CS45 : OBJECT ORIENTED CONCEPTS
15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?
More informationSwing. By Iqtidar Ali
Swing By Iqtidar Ali Background of Swing We have been looking at AWT (Abstract Window ToolKit) components up till now. Programmers were not comfortable when doing programming with AWT. Bcoz AWT is limited
More informationCourse Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski
CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University March 10, 2008 / Lecture 8 Outline Course Status Course Information & Schedule
More informationFrames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling
Frames, GUI and events Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Introduction to Swing The Java AWT (Abstract Window Toolkit)
More informationThe DSL created in Scala was accomplished using the Implicit conversion (Views) feature of Scala.
5. Rich Graphical User Interface DSL To evaluate the ability of Scala and Groovy to be DSL hosts, we created a small JavaFX like DSL for Rich Graphical User Interface (GUI) creation. The DSL provides features
More informationGraphical User Interfaces. Comp 152
Graphical User Interfaces Comp 152 Procedural programming Execute line of code at a time Allowing for selection and repetition Call one function and then another. Can trace program execution on paper from
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationThe AWT Event Model 9
The AWT Event Model 9 Course Map This module covers the event-based GUI user input mechanism. Getting Started The Java Programming Language Basics Identifiers, Keywords, and Types Expressions and Flow
More informationDesign patterns for graphical user interface applications
Design patterns for graphical user interface applications Prof.Asoc. Alda Kika Department of Informatics Faculty of Natural Sciences University of Tirana Outline Pattern Concept Design pattern in computer
More informationGraphical User Interface (GUI)
Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware
More informationThe JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class
CHAPTER GRAPHICAL USER INTERFACES 10 Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/11 10.1 Frame Windows Java provides classes to create graphical applications that can run on any major graphical
More informationSystems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid
Systems Programming Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid Leganés, 21st of March, 2014. Duration: 75 min. Full
More informationLab. Lecture 26: Concurrency & Responsiveness. Assignment. Maze Program
Lab Lecture 26: Concurrency & Responsiveness CS 62 Fall 2016 Kim Bruce & Peter Mawhorter Using parallelism to speed up sorting using Threads and ForkJoinFramework Review relevant material. Some slides
More informationCaesar. Ben Rister work by Mira Mezini and Klaus Ostermann
Caesar Ben Rister work by Mira Mezini and Klaus Ostermann 1 Outline Ideal Properties of Aspect Systems Cast of Characters Motivating Example Analysis 2 Ideal Properties Powerful extensibility Easy to write
More informationEPITA Première Année Cycle Ingénieur. Atelier Java - J5
EPITA Première Année Cycle Ingénieur marwan.burelle@lse.epita.fr http://www.lse.epita.fr Overview 1 2 Different toolkits AWT: the good-old one, lakes some features and has a plateform specific look n
More informationBean Communication. COMP434B Software Design. Bean Communication. Bean Communication. Bean Communication. Bean Communication
COMP434B Software Design JavaBeans: Events and Reflection Events are the primary mechanism by which Java components interact with each other One Bean generates an event and one or more other Beans receive
More informationBased on slides by Prof. Burton Ma
Based on slides by Prof. Burton Ma 1 TV - on : boolean - channel : int - volume : int + power(boolean) : void + channel(int) : void + volume(int) : void Model View Controller RemoteControl + togglepower()
More informationCIS 120 Final Exam May 7, Name (printed): Pennkey (login id):
CIS 120 Final Exam May 7, 2014 Name (printed): Pennkey (login id): My signature below certifies that I have complied with the University of Pennsylvania s Code of Academic Integrity in completing this
More informationLaboratorio di Tecnologie dell'informazione
Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Design pattern Observer Some motivations In many programs, when a object changes
More informationPROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7
PROGRAMMING DESIGN USING JAVA (ITT 303) Graphical User Interface Unit 7 Learning Objectives At the end of this unit students should be able to: Build graphical user interfaces Create and manipulate buttons,
More informationModule 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani
Module 5 The Applet Class, Swings OOC 4 th Sem, B Div 2016-17 Prof. Mouna M. Naravani The layout manager helps lay out the components held by this container. When you set a layout to null, you tell the
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 32 April 9, 2018 Swing I: Drawing and Event Handling Chapter 29 HW8: Spellchecker Available on the web site Due: Tuesday! Announcements Parsing, working
More informationSwing from A to Z Some Simple Components. Preface
By Richard G. Baldwin baldwin.richard@iname.com Java Programming, Lecture Notes # 1005 July 31, 2000 Swing from A to Z Some Simple Components Preface Introduction Sample Program Interesting Code Fragments
More informationIntroduction to the JAVA UI classes Advanced HCI IAT351
Introduction to the JAVA UI classes Advanced HCI IAT351 Week 3 Lecture 1 17.09.2012 Lyn Bartram lyn@sfu.ca About JFC and Swing JFC Java TM Foundation Classes Encompass a group of features for constructing
More informationSYSC Come to the PASS workshop with your mock exam complete. During the workshop you can work with other students to review your work.
It is most beneficial to you to write this mock midterm UNDER EXAM CONDITIONS. This means: Complete the Exam in 3 hour(s). Work on your own. Keep your notes and textbook closed. Attempt every question.
More informationLecture 9. Lecture
Layout Components MVC Design PaCern GUI Programming Observer Design PaCern D0010E Lecture 8 - Håkan Jonsson 1 Lecture 8 - Håkan Jonsson 2 Lecture 8 - Håkan Jonsson 3 1 1. GUI programming In the beginning,
More informationSwing UI. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff
Swing UI by Vlad Costel Ungureanu for Learn Stuff User Interface Command Line Graphical User Interface (GUI) Tactile User Interface (TUI) Multimedia (voice) Intelligent (gesture recognition) 2 Making the
More informationCSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation Hal Perkins Spring 2017 GUI Event-Driven Programming 1 The plan User events and callbacks Event objects Event listeners Registering listeners to handle events Anonymous
More informationGraphics. Lecture 18 COP 3252 Summer June 6, 2017
Graphics Lecture 18 COP 3252 Summer 2017 June 6, 2017 Graphics classes In the original version of Java, graphics components were in the AWT library (Abstract Windows Toolkit) Was okay for developing simple
More informationTable of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...
Table of Contents Chapter 1 Getting Started with Java SE 7 1 Introduction of Java SE 7... 2 Exploring the Features of Java... 3 Exploring Features of Java SE 7... 4 Introducing Java Environment... 5 Explaining
More informationBlock I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1
Block I Unit 2 Basic Constructs in Java M301 Block I, unit 2 1 Developing a Simple Java Program Objectives: Create a simple object using a constructor. Create and display a window frame. Paint a message
More informationDOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS
Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully
More informationProblems with Concurrency. February 19, 2014
with Concurrency February 19, 2014 s with concurrency interleavings race conditions dead GUI source of s non-determinism deterministic execution model 2 / 30 General ideas Shared variable Access interleavings
More informationGraphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI
CBOP3203 Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI components like button, text input, scroll bar and others.
More informationEXAMPLE ANSWERS. EXAM IN COURSE TDT4100 Object-Oriented Programming / IT1104 Programming, Advanced Course. Tuesday 29. Mai
ENGLISH Page 1 of 15 NTNU Norges teknisk-naturvitenskapelige universitet Fakultet for informasjonsteknologi, matematikk og elektroteknikk Institutt for datateknikk og informasjonsvitenskap EXAMPLE ANSWERS
More informationComposite Pattern Diagram. Explanation. JavaFX Subclass Hierarchy, cont. JavaFX: Node. JavaFX Layout Classes. Top-Level Containers 10/12/2018
Explanation Component has Operation( ), which is a method that applies to all components, whether composite or leaf. There are generally many operations. Component also has composite methods: Add( ), Remove(
More informationGraphical interfaces & event-driven programming
Graphical interfaces & event-driven programming Lecture 12 of TDA 540 (Objektorienterad Programmering) Carlo A. Furia Alex Gerdes Chalmers University of Technology Gothenburg University Fall 2017 Pop quiz!
More informationSri Vidya College of Engineering & Technology
UNIT-V TWO MARKS QUESTION & ANSWER 1. What is the difference between the Font and FontMetrics class? Font class is used to set or retrieve the screen fonts.the Font class maps the characters of the language
More informationhttps://www.lri.fr/~linaye/gl.html
Software Engineering https://www.lri.fr/~linaye/gl.html lina.ye@centralesupelec.fr Sequence 3, 2017-2018 1/50 Software Engineering Plan 1 2 3 4 5 2/50 Software Engineering ground Evolution of Program 3/50
More information