Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014

Similar documents
Jonathan Aldrich Charlie Garrod

Introduction to concurrency and GUIs

Chris9an Kästner Charlie Garrod

Charlie Garrod Michael Hilton

Graphical User Interfaces (GUIs)

Java: Graphical User Interfaces (GUI)

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Charlie Garrod Bogdan Vasilescu

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

Graphical User Interface (GUI)

Packages: Putting Classes Together

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

Systems Programming Graphical User Interfaces

Lecture 5: Java Graphics

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

Design Case Study: GUI with Swing (2)

Java Programming Lecture 6

GUI Event Handlers (Part I)

CSE 331 Software Design & Implementation

Introduction to the JAVA UI classes Advanced HCI IAT351

GUI Software Architecture

Lecture 9. Lecture

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

SELF-STUDY. Glossary

CS11 Java. Fall Lecture 4

Swing. By Iqtidar Ali

Sri Vidya College of Engineering & Technology

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo

Swing from A to Z Some Simple Components. Preface

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Lecture 3: Java Graphics & Events

Window Interfaces Using Swing Objects

Graphical interfaces & event-driven programming

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Lecture 19 GUI Events

Graphical User Interface (GUI)

Window Interfaces Using Swing Objects

CS 251 Intermediate Programming GUIs: Event Listeners

Graphical User Interfaces. Comp 152

CSE 331 Software Design & Implementation

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Class 16: The Swing Event Model

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

GUI Implementation Support

ITEC 120 4/14/11. Review. Need. Objectives. GUI basics JFrame JPanel JLabel, JButton, JTextField Layout managers. Lecture 38 GUI Interactivity

Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

Part I: Learn Common Graphics Components

SD Module-1 Advanced JAVA

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

Eclipsing Your IDE. Figure 1 The first Eclipse screen.

CS 251 Intermediate Programming GUIs: Components and Layout

SD Module-1 Advanced JAVA. Assignment No. 4

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068

Programming Languages and Techniques (CIS120)

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

EPITA Première Année Cycle Ingénieur. Atelier Java - J5

CS Exam 1 Review Suggestions

GUI Programming. Chapter. A Fresh Graduate s Guide to Software Development Tools and Technologies

Graphical User Interfaces. Swing. Jose Jesus García Rueda

(Incomplete) History of GUIs

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

PIC 20A GUI with swing

Part 3: Graphical User Interface (GUI) & Java Applets

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

CS 349 / SE 382 Design Patterns. Professor Michael Terry January 21, 2009

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

Graphic User Interfaces. - GUI concepts - Swing - AWT

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Chapter 8. Java continued. CS Hugh Anderson s notes. Page number: 264 ALERT. MCQ test next week. This time. This place.

Java continued. Chapter 8 ALERT ALERT. Last week. MCQ test next week. This time. This place. Closed book. Assignment #2 is for groups of 3

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Midterm assessment - MAKEUP Fall 2010

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Chapter 12 Advanced GUIs and Graphics

Lecture 18 Java Graphics and GUIs

Swing: Building GUIs in Java

CS415 Human Computer Interaction

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

Graphical User Interface (Part-1) Supplementary Material for CPSC 233

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Widgets. Widgets Widget Toolkits. 2.3 Widgets 1

CS108, Stanford Handout #22. Thread 3 GUI

Original GUIs. IntroGUI 1

2110: GUIS: Graphical User Interfaces

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

UI Software Organization

Swing: Building GUIs in Java

Transcription:

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 Kaestner, Jeffrey Eppinger, and William Scherlis. Used and adapted by permission

What makes GUIs different? How do they compare to command-line I/O? 2

What makes GUIs different? How do they compare to command-line I/O? Don t call us, we ll call you! GUI has to react to the user s actions Not just a response to a prompt Could involve entirely different functionality Requires structuring the GUI around reacting to events 3

(Blocking) Interactions with Users Game Dealer Player newgame addcards addcards getaction action blocking execution [action==hit] addcard

Interactions with Users through Events Do not wait for user response, react to event Here: Two interactions to separate events: Game Dealer Player newgame addcards addcards hit addcard

Event-based programming A style of programming where the control-flow of the program is driven by (usually-) external events public void performaction(actionevent e) { printslides() } public void performaction(actionevent e) { editfigure() } public void performaction(actionevent e) { }

Writing GUIs, Old-Style Operating System Application createwindow( ) windowhandle loop getnextevent() event element=findguielement(event) This complex code is the same for every application! a=findaction(event, element) update( ) a.execute() 7

Writing GUIs with GUI Frameworks Operating System Framework createwindow( ) windowhandle w = new Window( ) w.setaction(action) Application loop getnextevent() event w.setvisible(true) update( ) element=findguielement(event) a=findaction(event, element) a.execute() update( ) 8

Pseudocodefor GUIs Application code Creates and sets up a window Asks framework to show the window main() exits Takes action in response to event May contact GUI E.g. consider if event was a redraw Call GUI to paint lines, text GUI framework code Starts the GUI thread This thread loops: Asks OS for event Finds application window that event relates to Asks application window to handle event Draws lines/text on behalf of application 9

Example: RabbitWorldGUI hw2.staff.worldui.main() Creates a top-level JFrame window Creates a WorldUIto go in it Sets some parameters Makes the window (and its contents) visible hw2.staff.worldpanel.paintcomponent() Called when the OS needs to show the WorldPanel(part of WorldUI) Right after the window becomes visible super.paintcomponent() draws a background ImageIcon.paintIcon( ) draws each item in the world Let s look at the code 10

GUI Frameworks in Java AWT Native widgets, only basic components, dated Swing Java rendering, rich components SWT + JFace Mixture of native widgets and Java rendering; created for Eclipse for faster performance Others Apache Pivot, SwingX, JavaFX,

Swing JFrame JPanel JButton JTextField

To create a simple Swing application Make a Window (a JFrame) Make a container (a JPanel) Put it in the window Add components (Buttons, Boxes, etc.) to the container Use layouts to control positioning Set up observers (a.k.a. listeners) to respond to events Optionally, write custom widgets with application-specific display logic Set up the window to display the container Then wait for events to arrive 13

Components Swing has lots of components: JLabel JButton JCheckBox JChoice JRadioButton JTextField JTextArea JList JScrollBar and more 14

JFrame & JPanel JFrame is the Swing Window JPanel (aka a pane) is the container to which you add your components (or other containers) 15

Swing Layout Managers The simplest, and default, layout. Wraps around when out of space. Like FlowLayout, but no wrapping More sophisticated layout managers see http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

Find the pattern contentpane.setlayout(new BorderLayout(0,0)); contentpane.setborder(new EmptyBorder(5, 5, 5, 5));

Behavioral: Strategy Applicability Many classes differ in only their behavior Client needs different variants of an algorithm Consequences Code is more extensible with new strategies Compare to conditionals Separates algorithm from context each can vary independently Adds objects and dynamism code harder to understand Common strategy interface may not be needed for all Strategy implementations may be extra overhead

Example: RabbitWorldGUI hw2.staff.worldui.worldui() Sets the layout to a BorderLayout Adds a WorldPanelin the CENTER of the UI Creates a JPanelfor the buttons at the bottom Adds 2buttons to the JPanel(WEST and CENTER) Puts the button JPanelat the SOUTH side of the WorldPanel Let s look at the code again 19

Question How do you make a button work? 20

Events in Swing An event is when something changes Button clicked, scrolling, mouse movement Swing (actually AWT) generates an event To do something you need to implement a Listener Interface and register interest 21

The Observer design pattern Applicability When an abstraction has two aspects, one dependent on the other, and you want to reuse each When change to one object requires changing others, and you don t know how many objects need to be changed When an object should be able to notify others without knowing who they are Consequences Loose coupling between subject and observer, enhancing reuse Support for broadcast communication Notification can lead to further updates, causing a cascade effect Subject + attach(o : Observer) + detach(o : Observer) # notify() ConcreteSubject + getstate() + setstate() subjectstate observers 0..* for all o in observers o.update(); Also called Listener <<interface>> Observer + update() ConcreteObserver + update() + observerstate

Event Listeners Swing has lots of event listener interfaces: ActionListener AdjustmentListener FocusListener ItemListener KeyListener MouseListener TreeExpansionListener TextListener WindowListener and on and on 23

ActionListener Events for JButtons, JTextFields, etc The things we are using Implement ActionListener Provide actionperformed method In actionperformed method Use event.getsource() to determine which button was clicked, etc. 24

Example: RabbitWorldGUI hw2.staff.worldui.worldui() Sets ActionListeners for the run and step buttons Anonymous inner classes used A single method actionperformed( ) is overridden step button: just calls step() on the WorldPanel Steps the world Requests that the window be refreshed (so the user can see the changes) run button Starts the world continuously stepping Disables the step button (no point!) Sets a toggle flag so that pressing the button again will stop the simulation 25

Aside: Anonymous inner classes in Java You can implement an interface without naming the implementing class E.g., public interface Runnable { public void run(); } public static void main(string[] args) { Runnable greeter = new Runnable() { public void run() { System.out.println("Hi mom!"); } }; } greeter.run();

Scope within an anonymous inner class An anonymous inner class cannot access non-final variables in the scope where it is defined public interface Runnable { public void run(); } public static void main(string[] args) { String name = "Charlie"; Runnable greeter = new Runnable() { public void run() { System.out.println("Hi " + name); } }; } greeter.run(); compile-time error

Scope within an anonymous inner class An anonymous inner class cannot access non-final variables in the scope where it is defined public interface Runnable { public void run(); } public static void main(string[] args) { final String name = "Charlie"; Runnable greeter = new Runnable() { public void run() { System.out.println("Hi " + name); } }; } greeter.run(); OK

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 Kaestner, Jeffrey Eppinger, and William Scherlis. Used and adapted by permission

Homework Hint! UI Class (imaginary) All user interaction goes here and nothing else! Only make calls this way! Other Classes (real) No user interaction here all game and player state here 30

GUIDemoExample Shows how to construct a basic UI Illustrates an interesting UI responsiveness issue 31

The GUI Threading Architecture main() thread Create window Set up callbacks Show window (thread ends) GUI Thread Loop forever: Get system event Invoke callback Callback code: Compute fibonacci (UI is unresponsive) Show result 32

GUIDemoExample A fix: SwingWorker 33

The GUI Threading Architecture main() thread Create window Set up callbacks Show window (thread ends) GUI thread Loop forever: Get system event Invoke callback Callback code: create SwingWorker start it executing Worker thread Worker thread execution: invoke doinbackground() compute fibonacci store result in SwingWorker signal to UI that we are done SwingWorker result : Long 34

The GUI Threading Architecture main() thread Create window Set up callbacks Show window (thread ends) GUI thread Loop forever: Get system event Invoke callback Worker thread Invoke SwingWorker.done() get() result from SwingWorker show result in the UI Worker thread execution: invoke doinbackground() compute fibonacci store result in SwingWorker signal to UI that we are done SwingWorker result : Long 35

Organizational Tips Declare references to components you ll be manipulating as instance variables Put the code that performs the actions in private helper methods. (Keeps things neat) 36

GUI design issues Interfaces vs. inheritance Inherit from JPanel with custom drawing functionality Implement the ActionListener interface, register with button Why this difference? Models and views 37

GUI design issues Interfaces vs. inheritance Inherit from JPanel with custom drawing functionality Subclass is a special kind of Panel The subclass interacts closely with the JPanel e.g. the subclass calls back with super() The way you draw the subclass doesn t change as the program executes Implement the ActionListener interface, register with button The action to perform isn t really a special kind of button; it s just a way of reacting to the button. So it makes sense to be a separate object. The ActionListeneris decoupled from the button. Once the listener is invoked, it doesn t call anything on the Button anymore. We may want to change the action performed on a button press so once again it makes sense for it to be a separate object Models and views 38

Model-View-Controller (MVC) Manage inputs from user: mouse, keyboard, menu, etc. Manage display of information on the screen Manage data related to the application domain http://msdn.microsoft.com/en-us/library/ff649643.aspx

Passive model Model-View-Controller (MVC) Active model http://msdn.microsoft.com/en-us/library/ff649643.aspx

Example: RabbitWorldGUI hw2.lib.ui.worldimpl The Model class Model is passive: does not have a reference to the view hw2.lib.ui.worldui The Controller class Listener callbacks in constructor react to events Delegating to the view (is this design ideal?) hw2.lib.ui.worldpanel The View class Gets data from Model to find out where to draw rabbits, foxes, etc. Implements stepping (in step()) Invokes model to update world Invokes repaint() on self to update UI 41

Find That Pattern! What pattern is BorderLayout a part of? What pattern is JPanela part of? What pattern are the ActionListeners part of? There are classes representing the AI s decision to Eat, Breed, or Move. What pattern are these representing? Look at the documentation for JComponent.paint(). What pattern is used? 42

For More Information Oracle s Swing tutorials http://download.oracle.com/javase/tutorial/uiswing/ Introduction to Programming Using Java, Ch. 6 http://math.hws.edu/javanotes/c6/index.html 43