Building Graphical User Interfaces. GUI Principles

Similar documents
Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

Building Graphical User Interfaces. Overview

Introduction to the JAVA UI classes Advanced HCI IAT351

Chapter 13 Lab Advanced GUI Applications Lab Objectives. Introduction. Task #1 Creating a Menu with Submenus

Window Interfaces Using Swing Objects

Chapter 14. More Swing

Today. cisc3120-fall2012-parsons-lectiii.3 2

import javax.swing.*; import java.awt.*; import java.awt.event.*;

Chapter 13 Lab Advanced GUI Applications

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

Window Interfaces Using Swing Objects

Calculator Class. /** * Create a new calculator and show it. */ public Calculator() { engine = new CalcEngine(); gui = new UserInterface(engine); }

Graphic User Interfaces. - GUI concepts - Swing - AWT

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

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

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!

More Swing. Chapter 14. Chapter 14 1

Programming graphics

1005ICT Object Oriented Programming Lecture Notes

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

encompass a group of features for building Graphical User Interfaces (GUI).

AP CS Unit 11: Graphics and Events

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

Inheritance (cont) Abstract Classes

Jonathan Aldrich Charlie Garrod

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

Part I: Learn Common Graphics Components

A Simple Text Editor Application

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

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

MIT AITI Swing Event Model Lecture 17

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

CS 251 Intermediate Programming GUIs: Components and Layout

More Swing. CS180 Recitation 12/(04,05)/08

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

What is Widget Layout? Laying Out Components. Resizing a Window. Hierarchical Widget Layout. Interior Design for GUIs

Graphical Interfaces

CSE 8B Intro to CS: Java

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

Using Several Components

JLayeredPane. Depth Constants in JLayeredPane

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

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

Systems Programming Graphical User Interfaces

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Graphical User Interfaces in Java - SWING

Laying Out Components. What is Widget Layout?

Java: Graphical User Interfaces (GUI)

Graphical User Interface (GUI)

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

Graphical Interfaces

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

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

(Incomplete) History of GUIs

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

Java. GUI building with the AWT

1. Swing Note: Most of the stuff stolen from or from the jdk documentation. Most programs are modified or written by me. This section explains the

PIC 20A GUI with swing

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

JFrame In Swing, a JFrame is similar to a window in your operating system

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

Graphical interfaces & event-driven programming

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

Theory Test 3A. University of Cape Town ~ Department of Computer Science. Computer Science 1016S ~ For Official Use

JAVA NOTES GRAPHICAL USER INTERFACES

Programming Languages and Techniques (CIS120e)

Graphical User Interfaces. Comp 152

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

FirstSwingFrame.java Page 1 of 1

Introduction. Introduction

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

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

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

Window Interfaces Using Swing. Chapter 12

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

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

We are on the GUI fast track path

Programmierpraktikum

Swing UI. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

User interfaces and Swing

Resizing a Window. COSC 3461: Module 5B. What is Widget Layout? Size State Transitions. What is Widget Layout? Hierarchical Widget Layout.

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

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

Class 16: The Swing Event Model

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

Dr. Hikmat A. M. AbdelJaber

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

Chapter 6: Graphical User Interfaces

Programming Mobile Devices J2SE GUI

Example 3-1. Password Validation

State Application Using MVC

BASICS OF GRAPHICAL APPS

Attempt FOUR questions Marking Scheme Time: 120 mins

Event Driven Programming

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

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

COMPSCI 230. Software Design and Construction. Swing

Transcription:

Building Graphical User Interfaces 4.1 GUI Principles Components: GUI building blocks Buttons, menus, sliders, etc. Layout: arranging components to form a usable GUI Using layout managers. Events: reacting to user input Button presses, menu selections, etc. 2 1

Elements of a frame Menu bar Title Window controls Content pane 3 Creating a frame import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ImageViewer private JFrame frame; /** * Create an ImageViewer show it on screen. */ public ImageViewer() makeframe(); // rest of class omitted. 4 2

The content pane /** * Create the Swing frame and its content. */ private void makeframe() frame = new JFrame("ImageViewer"); Container contentpane = frame.getcontentpane(); JLabel label = new JLabel("I am a label."); contentpane.add(label); frame.pack(); frame.setvisible(true); 5 General Template for Stand- Alone GUI public static void main(string[] args) JFrame frame = new JFrame( Picture Test"); frame.setdefaultcloseoperation(jframe.ex IT_ON_CLOSE); JPanel panel = new PictureApp(); panel.setpreferredsize(new Dimension(500,500)); frame.getcontentpane().add(panel); frame.pack(); frame.setvisible(true); 6 3

Adding menus JMenuBar Displayed below the title Contains the menus JMenu e.g. File. Contains the menu items JMenuItem e.g. Open. Individual items 7 // Called from makeframe(): makemenubar(frame); private void makemenubar(jframe frame) JMenuBar menubar = new JMenuBar(); frame.setjmenubar(menubar); // create the File menu JMenu filemenu = new JMenu("File"); menubar.add(filemenu); JMenuItem openitem = new JMenuItem("Open"); filemenu.add(openitem); JMenuItem quititem = new JMenuItem("Quit"); filemenu.add(quititem); 8 4

Event handling Events = user interactions with components Components are associated with different event types: Frame interactions => WindowEvent Menu interactions => ActionEvent Mouse interactions => MouseEvent Objects can be notified when an event occurs, called listeners Two implementation styles: Centralized: single class handles all events Unique listeners for each event (with inner classes) 9 Centralized event handling A single object handles all events Implements the ActionListener interface Defines an actionperformed method It registers as a listener with each component item.addactionlistener(this) It has to work out which component has dispatched the event 10 5

ActionListener & ActionEvent 11 public class ImageViewer implements ActionListener public void actionperformed(actionevent e) String command = e.getactioncommand(); if(command.equals("open")) else if (command.equals("quit")) private void makemenubar(jframe frame) openitem.addactionlistener(this); 12 6

Limitations of centralized event handling Although used in practice Doesn t scale well (i.e., hard to extend in future) Identifying components by their text is fragile (i.e., potentially buggy & hard to maintain) Preferred alternative: each event assigned its own unique listener Uses nested inner classes 13 Nested class syntax Class definitions may be nested. public class Enclosing private class Inner 14 7

Inner classes Instances of the inner class are localized within the enclosing class Instances of the inner class have access to the private members of the enclosing class 15 Anonymous inner classes Same access and creation rules as inner classes, but no class name Use special syntax can be created inside a method The instance is always referenced via its supertype, since it has no subtype name 16 8

Anonymous action listener JMenuItem openitem = new JMenuItem("Open"); openitem.addactionlistener(new ActionListener() public void actionperformed(actionevent e) openfile(); ); 17 Anonymous class elements Anonymous object creation openitem.addactionlistener( new ActionListener() public void actionperformed(actionevent e) openfile(); ); Class definition Actual parameter 18 9

Exit on window close frame.addwindowlistener(new WindowAdapter() public void windowclosing(windowevent e) System.exit(0); ); WindowAdapter provides a no-op implementation of the WindowListener interface. 19 Why use anonymous classes? Each event gets its own simplified actionperformed method Since event listener code is separated to handle each event individually: Improved scalability (easier to extend in future) Improved maintainability & understandability 20 10

Next Step: Loading a file 21 ImageViewer design for handling files 22 11

Class responsibilities ImageViewer Sets up the GUI structure. ImageFileManager Static methods for image file loading and saving. ImagePanel Displays the image within the GUI. OFImage Models a 2D image. 23 OFImage Our subclass of BufferedImage. Represents a 2D array of pixels. Important methods: getpixel, setpixel getwidth, getheight Each pixel has a color. We use java.awt.color. 24 12

Adding an ImagePanel public class ImageViewer private JFrame frame; private ImagePanel imagepanel; private void makeframe() Container contentpane = frame.getcontentpane(); imagepanel = new ImagePanel(); contentpane.add(imagepanel); 25 public class ImageViewer private JFrame frame; private ImagePanel imagepanel; Loading an image private void openfile() File selectedfile = ; OFImage image = ImageFileManager.loadImage(selectedFile); imagepanel.setimage(image); frame.pack(); 26 13

Next Step: Finish the Layout 27 Layout managers Manage limited space for competing components (like our content pane) FlowLayout, BorderLayout, GridLayout, BoxLayout, GridBagLayout. Manage Container objects, e.g. a content pane Each imposes its own style 28 14

FlowLayout 29 BorderLayout 30 15

GridLayout 31 BoxLayout Note: no component resizing. 32 16

GridBagLayout http://download.oracle.com/javase/tutorial/uiswing/examples/layout/gridbaglayoutdemoproject/src/layout/gridbaglayoutdemo.java 33 A message dialog private void showabout() JOptionPane.showMessageDialog(frame, "ImageViewer\n" + VERSION, "About ImageViewer", JOptionPane.INFORMATION_MESSAGE); 34 17

Which Layout? ImageViewer 1-0 35 Review Aim for cohesive application structures Endeavor to keep GUI elements separate from application functionality (loose coupling) Pre-defined components simplify creation of sophisticated GUIs Layout managers handle component juxtaposition Nest containers for further control 36 18

Review Many components recognize user interactions with them Reactive components deliver events to listeners Anonymous inner classes are commonly used to implement listeners 37 Additional Materials 38 19

Nested containers Sophisticated layouts can be obtained by nesting containers Use JPanel as a basic container. Each container will have its own layout manager Often preferable to using a GridBagLayout (less control) 39 Struts and Glue Invisible components used as spacing Available from the Box class Strut: fixed size Component createhorizontalstrut(int width) Component createverticalstrut(int height) Glue: fills available space Component createhorizontalglue() Component createverticalglue() 40 20

Dialogs Modal dialogs block all other interaction Forces a response from the user Non-modal dialogs allow other interaction This is sometimes desirable May be difficult to avoid inconsistencies 41 JOptionPane standard dialogs Message dialog Message text plus an OK button. Confirm dialog Yes, No, Cancel options. Input dialog Message text and an input field. Variations are possible. 42 21

Image filters Functions applied to the whole image. int height = getheight(); int width = getwidth(); for(int y = 0; y < height; y++) for(int x = 0; x < width; x++) Color pixel = getpixel(x, y); alter the pixel's color value; setpixel(x, y, pixel); 43 Adding further filters private void makelighter() if(currentimage!= null) currentimage.lighter(); frame.repaint(); showstatus("applied: lighter"); else showstatus("no image loaded."); Code duplication? Refactor! private void threshold() if(currentimage!= null) currentimage.threshold(); frame.repaint(); showstatus("applied: threshold"); else showstatus("no image loaded."); 44 22

Adding further filters Define a Filter superclass (abstract). Create function-specific subclasses. Create a collection of subclass instances in ImageViewer. Define a generic applyfilter method. See imageviewer2-0. 45 imageviewer2-0 46 23

Buttons and nested layouts A GridLayout inside a FlowLayout inside a BorderLayout. 47 Borders Used to add decoration around components. Defined in javax.swing.border BevelBorder, CompoundBorder, EmptyBorder, EtchedBorder, TitledBorder. 48 24

Adding spacing JPanel contentpane = (JPanel)frame.getContentPane(); contentpane.setborder(new EmptyBorder(6, 6, 6, 6)); // Specify the layout manager with nice spacing contentpane.setlayout(new BorderLayout(6, 6)); imagepanel = new ImagePanel(); imagepanel.setborder(new EtchedBorder()); contentpane.add(imagepanel, BorderLayout.CENTER); 49 Other components Slider Spinner Tabbed pane Scroll pane 50 25