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

Similar documents
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!

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

Graphical User Interfaces. Comp 152

Java Programming Lecture 6

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

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

Graphical User Interface (GUI)

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

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

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

Window Interfaces Using Swing Objects

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

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

CS 251 Intermediate Programming GUIs: Components and Layout

Graphical User Interface (GUI)

Window Interfaces Using Swing Objects

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Introduction to the JAVA UI classes Advanced HCI IAT351

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Unit 7: Event driven programming

Programming graphics

Java. GUI building with the AWT

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

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

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

CS Exam 1 Review Suggestions

Class 16: The Swing Event Model

PIC 20A GUI with swing

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Graphic User Interfaces. - GUI concepts - Swing - AWT

Part I: Learn Common Graphics Components

Graphical User Interfaces (GUIs)

Laying Out Components. What is Widget Layout?

H212 Introduction to Software Systems Honors

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

Unit 6: Graphical User Interface

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

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

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

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

User interfaces and Swing

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

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

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

BASICS OF GRAPHICAL APPS

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

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

To gain experience using GUI components and listeners.

Systems Programming Graphical User Interfaces

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

Agenda. Programming Seminar. By: dr. Amal Khalifa. Coordinate systems Colors Fonts Drawing shapes Graphics2D API

CS 2113 Software Engineering

Object-Oriented Programming Design. Topic : Graphics Programming GUI Part I

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

CS108, Stanford Handout #22. Thread 3 GUI

Lecture 18 Java Graphics and GUIs

Dr. Hikmat A. M. AbdelJaber

2IS45 Programming

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

1.00 Lecture 14. Lecture Preview

Class 14: Introduction to the Swing Toolkit

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

AP CS Unit 11: Graphics and Events

Chapter 12 Advanced GUIs and Graphics

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

DM503 Programming B. Peter Schneider-Kamp.

Lecture 5: Java Graphics

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

2110: GUIS: Graphical User Interfaces

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

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

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

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

Packages: Putting Classes Together

Chapter 12 GUI Basics

What is Widget Layout? COSC 3461 User Interfaces. Hierarchical Widget Layout. Resizing a Window. Module 5 Laying Out Components

CSE 331 Software Design & Implementation

Agenda. Container and Component

GUI in Java TalentHome Solutions

Building Java Programs Bonus Slides

Graphical User Interfaces

Chapter 7: A First Look at GUI Applications

Example: Building a Java GUI

An array is a type of variable that is able to hold more than one piece of information under a single variable name.

JAVA NOTES GRAPHICAL USER INTERFACES

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

Swing from A to Z Some Simple Components. Preface

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

Introduction. Introduction

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Programming Languages and Techniques (CIS120)

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

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

Example: Building a Java GUI

Here is a list of a few of the components located in the AWT and Swing packages:

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

COMPSCI 230. Software Design and Construction. Swing

CHAPTER 2. Java Overview

Lecture 9. Lecture

Transcription:

Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 5: Will be an open-ended Swing project. "Programming Contest" last day of classes (if time permits) 1

Why are we studying Swing? 1. Useful & fun! 2. Good application of OOP techniques 2

A. Basics a little background & history putting a frame (window) on the screen B. Layouts arranging multiple components in a frame three different kinds of "layout managers" C. Components & Actions more kinds of components adding actions to components D. Graphics using icons drawing custom pictures Outline 3

GUIs Up to now: line-by-line programs: computer displays text user types text GUI = Graphical User Interface Advantages & disadvantages? 4

AWT Early GUIs: write your own, huge amount of work Common style emerged: mouse, buttons, text boxes, menus Libraries to help you write GUI programs X-Windows for Unix/Linux Microsoft Foundation Classes (MFC) for Windows etc. not portable AWT = Abstract Window Toolkit part of Java API classes for writing portable GUI programs easier to use than MFC can be used by itself (no Swing) 5

Swing Extension to AWT: part of Java API in versions 1.2 & later some new features (file & color choosers, more graphics features) replaced some items with improved versions (Button -> JButton, Frame -> JFrame all start with "J") some improvements to existing features (double buffering) Still use parts of AWT that Swing hasn't replaced: same old layout managers, basic graphics commands 6

Packages For a basic Java GUI program, import these packages: import javax.swing.*; import java.awt.*; import java.awt.event.*; 7

Tasks in GUI Programming 1. Getting your screen to look the way you want it to. (laying out components buttons, text boxes, etc.) 2. Getting the program to do what you want it to. (functionality) These tasks are somewhat independent. Common order: 1. get screen looking right, no functionality 2. add functionality Another possibility: 1. put components on screen, quick & sloppy 2. add functionality, debug 3. improve appearance 8

Getting a Window Running First practical task: get a window up on your screen and be able to exit gracefully Basic Swing class: JFrame A frame is a window with: a border a title menu bar (optional place to put menu items) minimize, maximize, close buttons inner area for contents ("content pane") First set of demos: "baby Swing" 9

Fonts A font consists of: name ("Serif", "Sanserif", "Monospaced") type (constants: PLAIN, ITALIC, BOLD) size (in points) Example: Font bigfont = new Font("Serif", Font.PLAIN, 24); quitbutton.setfont(bigfont); 10

class Color: Colours constants for common colours (RED, BLUE, BLACK, etc.) constructor to create a custom colour: Color(int r, int g, int b) methods in JComponent: setbackground(color c) setforeground(color c) Notes: some components don't use both colours labels are transparent (no background colour) panels have no foreground colour 11

JOptionPane (1) JOptionPane class for common pop-up windows many capabilities; we'll look at 3 basic static methods JOptionPane.showMessageDialog(myFrame, "hello, world!"); 12

JOptionPane (2) int result = JOptionPane.showConfirmDialog(myFrame, "are you awake?"); result gets one of three values: JOptionPane.YES_OPTION JOptionPane.NO_OPTION JOptionPane.CANCEL_OPTION 13

JOptionPane (3) String name = JOptionPane.showInputDialog(myFrame, "what is your name?"); name gets user input -- or null if user clicks "Cancel" 14

A. Basics a little background & history putting a frame (window) on the screen B. Layouts arranging multiple components in a frame three different kinds of "layout managers" C. Components & Actions more kinds of components adding actions to components D. Graphics using icons drawing custom pictures Outline 15

Layout Managers layout manager decides: position of each component in frame size of each component what changes when window is resized programmer's job: give layout manager some general instructions NOT exact positions and sizes 16

Different Kinds of Layout Managers We will concentrate on three: BorderLayout FlowLayout GridLayout Each has different purpose, different layout algorithms. Real power comes from combining them -- different parts of frame. 17

Sizes of Components Every component has a "preferred size" For buttons and labels, based on the text and the font Sometimes layout managers "stretch" components beyond the "preferred size" Button at preferred size: Same button, stretched: 18

BorderLayout default layout manager for frames frame has 5 positions: NORTH, SOUTH, EAST, WEST, CENTER demo... Rules: max of 1 component in each position OK to have some positions empty north & south stretched horizontally to fit frame east & west stretched vertically center stretched both ways can specify gaps 19

adds components left to right demo... FlowLayout Rules: components always at preferred sizes never stretches components breaks into multiple rows if necessary can specify alignment & gaps FAQ: can you create a vertical row with a FlowLayout? Answer: no 20

GridLayout lays out components in a rectangular grid demo... Rules: components are stretched to fill frame all components have same dimensions specify number of rows OR number of columns can specify gaps 21

Changing a Preferred Size You may state a preference about the size of a component: btn.setpreferredsize(new Dimension(120,45)); You may also query the preferred size: Dimension size3 = btn.getpreferredsize(); btn.setpreferredsize( new Dimension(size3.width*2,size3.height)); This does *not* guarantee that the button will be the size you asked for! The layout manager is still in charge. 22

Combining Layouts Now we know about 3 kinds of layouts Each fairly limited by itself Can sub-divide frame into sections, lay each out individually each section called a "panel" Swing class: JPanel a component which is also a container can add other components to a JPanel to create: new JPanel(new GridLayout(2,0)); new JPanel(); // default is FlowLayout 23

Panel Example 1 Suppose we want to put 6 buttons in a frame like this: 24

Panel Example 2 Suppose we want to put 6 buttons in a frame like this: 25

Panel Example 3 Suppose we want to put 6 buttons in a frame like this (small change from example 2): 26

More Complicated Example 27

A. Basics a little background & history putting a frame (window) on the screen Outline B. Layouts arranging multiple components in a frame three different kinds of "layout managers" C. Components & Actions more kinds of components adding actions to components D. Graphics using icons drawing custom pictures 28

Part C: Components & Actions We will talk about 4 different kinds of components: buttons labels text fields text areas (optional will not be tested) Plus how to use "listeners" to attach actions to components 29

Goal For This Sub-Topic A simple program using three kinds of components with actions attached demo... 30

"clickable" button with a border JButton JButton addbutton = new JButton("add"); 31

JButton Methods String gettext() void settext(string newtext) void setenabled(boolean enabled); default is true disabled button is "greyed out", no graphic reaction when clicked 32

JLabel Puts text on screen No borders, no actions, no background color (transparent) JLabel addlabel = new JLabel("amount to add: "); 33

JLabel Methods String gettext() void settext(string newtext) 34

two kinds: text field (one line) text area (multiple lines) Text Components 35

JTextField one line only space for entering/displaying text "editable" not "editable" JTextField addfield = new JTextField(10); width in "m spaces" JTextField multfield = new JTextField(10); JTextField totalfield = new JTextField(10); totalfield.seteditable(false); 36

JTextArea like a JTextField, but multiple lines JTextArea quotetextarea = new JTextArea(3,20); JTextArea databasearea = new JTextArea(20, 30); databasearea.seteditable(false); 37

Methods For Text Components String gettext() void settext(string newtext) 38

Event-Driven Programming Imperative Programming: You specify sequence of commands Programmer in control Event-Driven Programming: sequence driven by user's choices program waits for "events" and reacts to them Examples of events: button click menu choice window closed or resized mouse clicks, mouse motion 39

ActionEvent Class describes a simple event like a button click, menu choice methods: Object getsource() returns the component that "caused" the event (button that was clicked) String getactioncommand() returns text from component 40

ActionListener Interface public interface ActionListener { void actionperformed(actionevent e); } Program can register an action listener for a button. Meaning: when button is clicked, call actionperformed in this listener 41

Sequence of Events Set-up (usually in constructor): create button create listener register listener with button you write this code During Program Run: Swing does this for you 1. user clicks button 2. Swing checks whether button has a listener 3. if yes: Swing creates an ActionEvent object Swing calls actionperformed method in listener with the object as argument 42

Demo: Baby Calculator Three different styles: inner listener class(es) use frame as listener anonymous inner classes 43

A. Basics a little background & history putting a frame (window) on the screen B. Layouts arranging multiple components in a frame three different kinds of "layout managers" C. Components & Actions more kinds of components adding actions to components D. Graphics using icons drawing custom pictures Outline 44

A. Basics a little background & history putting a frame (window) on the screen Outline B. Layouts arranging multiple components in a frame three different kinds of "layout managers" C. Components & Actions more kinds of components adding actions to components D. Graphics using icons drawing custom pictures 45

Part D: Graphics We've seen how to put text on components Also possible to put "icon" (image from file) onto component. Sometimes we want to draw our own pictures dynamically Often use an empty panel 46

paintcomponent (1) every component has a paintcomponent method default method: draws text, borders, etc. on screen you can override to create your own graphics effects 47

paintcomponent (2) void paintcomponent(graphics g) Parameter: "graphics context" current drawing colour & font position & size of component lots more You never call paintcomponent! Swing calls it automatically whenever the component needs painting: frame is created frame is resized frame is minimized then restored 48

Graphics methods void drawline(int x1, int y1, int x2, int y2) void drawstring(string str, int x, int y) void drawrect(int x, int y, int width, int height) void fillrect(int x, int y, int width, int height) void drawoval(int x, int y, int width, int height) void filloval(int x, int y, int width, int height)...and lots more! 49

Note About Coordinates Swing uses x & y coordinates, different from math x positive x: to the right positive y: down y 50

Simple Example Program start with a static display; add actions 51

paintcomponent vs. repaint paintcomponent: takes a Graphics object as a parameter you override paintcomponent to draw your picture Swing (not you!) calls paintcomponent when necessary repaint: no parameters you call it to tell Java the component's graphics need to be updated you don't write or override it defined by Swing: gets the appropriate Graphics context and calls paintcomponent 52

Summary For custom graphic effects: "state variables" to store information about current state of graphics button clicks & other actions change those variables create custom component subclass for drawing subclass gets special paintcomponent method which uses the state variables remember to call repaint() when you change the state variables! 53