GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012



Similar documents
Principles of Software Construction: Objects, Design and Concurrency. GUIs with Swing. toad Spring 2013

Swing. A Quick Tutorial on Programming Swing Applications

GUI Event-Driven Programming

CS 335 Lecture 06 Java Programming GUI and Swing

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

Programming with Java GUI components

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

@ - Internal # - Online TH PR OR TW TOTAL HOURS # @ 175

Using A Frame for Output

GUI Components: Part 2

Assignment # 2: Design Patterns and GUIs

Extending Desktop Applications to the Web

Event processing in Java: what happens when you click?


Developing GUI Applications: Architectural Patterns Revisited

Mouse Event Handling (cont.)

Model-View-Controller (MVC) Design Pattern

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Essentials of the Java(TM) Programming Language, Part 1

Implementação. Interfaces Pessoa Máquina 2010/ Salvador Abreu baseado em material Alan Dix. Thursday, June 2, 2011

The Basic Java Applet and JApplet

Course/Year W080/807 Expected Solution Subject: Software Development to Question No: 1

11. Applets, normal window applications, packaging and sharing your work

How To Write A Program For The Web In Java (Java)

How To Build A Swing Program In Java.Java.Netbeans.Netcode.Com (For Windows) (For Linux) (Java) (Javax) (Windows) (Powerpoint) (Netbeans) (Sun) (

method is never called because it is automatically called by the window manager. An example of overriding the paint() method in an Applet follows:

Advanced Network Programming Lab using Java. Angelos Stavrou

Eclipse with Mac OSX Getting Started Selecting Your Workspace. Creating a Project.

Essentials of the Java Programming Language

Artificial Intelligence. Class: 3 rd

Homework/Program #5 Solutions

How to Convert an Application into an Applet.

JiST Graphical User Interface Event Viewer. Mark Fong

Syllabus for CS 134 Java Programming

Graphical User Interfaces

Java is commonly used for deploying applications across a network. Compiled Java code

public class Craps extends JFrame implements ActionListener { final int WON = 0,LOST =1, CONTINUE = 2;

Tutorial: Time Of Day Part 2 GUI Design in NetBeans

Skills and Topics for TeenCoder: Java Programming

How Scala Improved Our Java

LAYOUT MANAGERS. Layout Managers Page 1. java.lang.object. java.awt.component. java.awt.container. java.awt.window. java.awt.panel

core 2 Handling Mouse and Keyboard Events

Nexawebホワイトペーパー. Developing with Nexaweb ~ Nexaweb to Improve Development Productivity and Maintainability

Sample copy. Introduction To WebLogic Server Property of Web 10.3 Age Solutions Inc.

Mapping to the Windows Presentation Framework

1 Hour, Closed Notes, Browser open to Java API docs is OK

Demo: Embedding Windows Presentation Foundation elements inside a Java GUI application. Version 7.3

Karsten Lentzsch JGoodies SWING WITH STYLE

Fundamentals of Java Programming

Cours de Java. Sciences-U Lyon. Java - Introduction Java - Fondamentaux Java Avancé.

For Introduction to Java Programming, 5E By Y. Daniel Liang

Object Oriented Programming with Java. School of Computer Science University of KwaZulu-Natal

Java (12 Weeks) Introduction to Java Programming Language

Java GUI Programming. Building the GUI for the Microsoft Windows Calculator Lecture 2. Des Traynor 2005

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Here's the code for our first Applet which will display 'I love Java' as a message in a Web page

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

JIDE Action Framework Developer Guide

Introduction to Google SketchUp (Mac Version)

Lab 1A. Create a simple Java application using JBuilder. Part 1: make the simplest Java application Hello World 1. Start Jbuilder. 2.

MEAP Edition Manning Early Access Program Hello! ios Development version 14

Week 2 Practical Objects and Turtles

Building a Python Plugin

Working With Your FTP Site

Konzepte objektorientierter Programmierung

Word basics. Before you begin. What you'll learn. Requirements. Estimated time to complete:

How To Use The Command Pattern In Java.Com (Programming) To Create A Program That Is Atomic And Is Not A Command Pattern (Programmer)

Introduction to SketchUp

Objectives. Chapter 2: Operating-System Structures. Operating System Services (Cont.) Operating System Services. Operating System Services (Cont.

Fondamenti di Java. Introduzione alla costruzione di GUI (graphic user interface)

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Software Design: Figures

The Google Web Toolkit (GWT): Declarative Layout with UiBinder Basics

Blackboard s Collaboration Tool

Tutorial Reference Manual. Java WireFusion 4.1

file://c:\dokumente und Einstellungen\Marco Favorito\Desktop\ScanCmds.html

Developing NFC Applications on the Android Platform. The Definitive Resource

Demo: Controlling.NET Windows Forms from a Java Application. Version 7.3

Specialized Android APP Development Program with Java (SAADPJ) Duration 2 months

Using the IPMI interface

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Computing Concepts with Java Essentials

Hypercosm. Studio.

How to extend WindowBuilder to support new components. 1. Add component to palette Palette contribution in project

Creating a Guest Book Using WebObjects Builder

Lab 9. Spam, Spam, Spam. Handout 11 CSCI 134: Spring, To gain experience with Strings. Objective

State of Illinois Web Content Management (WCM) Guide For SharePoint 2010 Content Editors. 11/6/2014 State of Illinois Bill Seagle

BCA 421- Java. Tilak Maharashtra University. Bachelor of Computer Applications (BCA) 1. The Genesis of Java

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Triggers & Actions 10

View Controller Programming Guide for ios

Creating trouble-free numbering in Microsoft Word

Design. in NetBeans 6.0

Example. Represent this as XML

COMMUNITY COLLEGE OF CITY UNIVERSITY CITY UNIVERSITY OF HONG KONG

How To Program In Java (Ipt) With A Bean And An Animated Object In A Powerpoint (For A Powerbook)

CS420: Operating Systems OS Services & System Calls

Effective unit testing with JUnit

Transcription:

GUIs with Swing Principles of Software Construction: Objects, Design, and Concurrency Jonathan Aldrich and Charlie Garrod Fall 2012 Slides copyright 2012 by Jeffrey Eppinger, Jonathan Aldrich, 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? One major difference: the user is in control 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

Reacting to events - from framework Setup phase Describe how the GUI window should look Use libraries for windows, widgets, and layout Embed specialized code for later use Customization (provided during setup) New widgets that display themselves in custom ways How to react to events Execution Framework gets events from OS Mouse clicks, key presses, window becomes visible, etc. Framework triggers application code in response The customization described above Application event mouse, key, redraw, Framework get event OS drawing commands next event 4

Pseudocode for GUIs Application code Creates and sets up a window Asks framework to show the window 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 a 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 5

Example: RabbitWorld GUI hw2.lib.ui.worldui.main() Creates a JFrame (i.e. a top-level window) Creates a WorldUI to go in it Sets some parameters Makes the JFrame (and its contents) visible hw2.lib.ui.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 6

Cookbook Programming Typical mode of using a framework Let s you follow a recipe for writing your programs All cakes are different, but there are a few basic recipes and everything else is a slight variation Add some cinnamon Substitute chocolate chips instead of nuts Tends to be most effective way to learn a framework Typically infeasible to read the documentation of all operations Instead, find a recipe similar to what you need to do Understand the recipe by reading about the ingredients Selective reading of the documentation Then you can combine the ingredients in new ways with confidence 7

Cookbook Programming You have a template for your program You change things around, but you don t mess with the overall structure Examples: public static void main(string[] args) { } for (int i=0; i<args.length; i++) { } Many people consider Swing development to be cookbook programming 8

A Little History In the beginning There was Java. It was like C++, but simpler and cleaner. Then came HotJava, a Java-based browser You could run chunks of Java code called Applets It was cool Netscape & then IE added Java support But Applets were a pain Browsers had out of date JVMs Used the AWT (lots of platform-based non-java code) Didn t have the look and feel of the rest of the platform Couldn t run as a standalone program with a GUI 9

Swing A new user interface environment Implemented in Java More consistent across implementations Offers different look and feel options Windows, Unix, and other (Metal) Can be a main method or a Japplet Still uses AWT for event handling, fonts, etc. BTW still issues with Swing non-native look and feel, predictable performance SWT An alternate Standard Widget Toolkit (from Eclipse) addresses this by staying closer to OS windowing support but, not standard for Java 10

Simplest Structure You make a Window (a JFrame) Make a container (a JPanel) Put it in the window Add your Buttons, Boxes, etc to the container Use layouts to control positioning Set up listeners to receive events Optionally, write custom widgets with application-specific display logic Set up the window to display the container Then wait for events to arrive 11

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

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

Layout Managers The default Layout Manager is FlowLayout Place items in the container from left to right When a line is full, FlowLayout goes to the next 14

More Layout Options GridLayout GridBagLayout Explicit Placement 15

Example: RabbitWorld GUI hw2.lib.ui.worldui.worldui() Sets the layout to a BorderLayout Adds a WorldPanel in the CENTER of the UI Creates a JPanel for the buttons at the bottom Adds 2 buttons to the JPanel (WEST and CENTER) Puts the button JPanel at the SOUTH side of the WorldPanel 16

Question How do you make a button work? 17

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 18

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

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. 20

Example: RabbitWorld GUI hw2.lib.ui.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 21

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) 22

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 23

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 ActionListener is 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 24

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: RabbitWorld GUI 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 27

Find That Pattern! What pattern is BorderLayout a part of? What pattern is JPanel a 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? 28

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 29

Questions? 30