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

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

Unit 7: Event driven programming

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

Graphical User Interfaces. Comp 152

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

Java Programming Lecture 6

Graphical User Interface (GUI)

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

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

Window Interfaces Using Swing Objects

PIC 20A GUI with swing

User interfaces and Swing

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

Window Interfaces Using Swing Objects

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

Graphical User Interface (GUI)

Programming graphics

GUI in Java TalentHome Solutions

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

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

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

Introduction to the JAVA UI classes Advanced HCI IAT351

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Class 16: The Swing Event Model

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

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

CS 251 Intermediate Programming GUIs: Components and Layout

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

BASICS OF GRAPHICAL APPS

CS 2113 Software Engineering

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

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

Laying Out Components. What is Widget Layout?

G51PRG: Introduction to Programming Second semester Applets and graphics

Graphic User Interfaces. - GUI concepts - Swing - AWT

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

Graphical User Interfaces 2

Systems Programming Graphical User Interfaces

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

Lecture 5: Java Graphics

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

CS Exam 1 Review Suggestions

Graphical User Interfaces (GUIs)

2IS45 Programming

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

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

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

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

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

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

AP CS Unit 11: Graphics and Events

Java. GUI building with the AWT

H212 Introduction to Software Systems Honors

Part I: Learn Common Graphics Components

DM503 Programming B. Peter Schneider-Kamp.

COMPSCI 230. Software Design and Construction. Swing

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

Chapter 14: Applets and More

8/23/2014. Chapter Topics. Introduction to Applets. Introduction to Applets. Introduction to Applets. Applet Limitations. Chapter 14: Applets and More

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Chapter 14: Applets and More

Unit 6: Graphical User Interface

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */

Dr. Hikmat A. M. AbdelJaber

GUI (Graphic User Interface) Programming. Part 2 (Chapter 8) Chapter Goals. Events, Event Sources, and Event Listeners. Listeners

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

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

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

2110: GUIS: Graphical User Interfaces

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

Lecture 19 GUI Events

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

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

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

Computer Science 210: Data Structures. Intro to Java Graphics

CSE 331 Software Design & Implementation

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

1.00 Lecture 14. Lecture Preview

Class 14: Introduction to the Swing Toolkit

Programming Mobile Devices J2SE GUI

GUI Event Handlers (Part I)

To gain experience using GUI components and listeners.

Graphical User Interfaces 2

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

CS108, Stanford Handout #22. Thread 3 GUI

Graphical User Interfaces 2

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

Lecture 3: Java Graphics & Events

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

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

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

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

Basicsof. JavaGUI and SWING

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

HW#1: Pencil Me In Status!? How was Homework #1? Reminder: Handouts. Homework #2: Java Draw Demo. 3 Handout for today! Lecture-Homework mapping.

Chapter 12 Advanced GUIs and Graphics

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

Advanced Java Unit 6: Review of Graphics and Events

Transcription:

Topic 9: Swing Outline Swing = Java's GUI library Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 7: Expand moving shapes from Assignment 4 into game. "Programming Contest" last day of classes: A. Basics today 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 drawing pictures dynamically E. Mouse Events & Timers reacting to mouse clicks using timers for animation 1 2 GUIs Up to now: line-by-line programs: computer displays text user types text AWT Early GUIs: write your own, huge amount of work Common style emerged: buttons, text boxes, menus Libraries to help you write GUI programs GUI = Graphical User Interface Advantages & disadvantages? 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) 3 4

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) Packages For a basic Java GUI program, import these packages: import javax.swing.*; import java.awt.*; import java.awt.event.*; Still use parts of AWT that Swing hasn't replaced: same old layout managers, basic graphics commands 5 6 Tasks in GUI Programming Getting a Window Running 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 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") Another possibility: 1. put components on screen, quick & sloppy 2. add functionality, debug 3. improve appearance 7 8

Fonts A font consists of: name ("Serif", "Sanserif", "Monospaced") type (constants: PLAIN, ITALIC, BOLD) size (in points) Colours class Color: 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) Example: Font bigfont = new Font("Serif", Font.PLAIN, 24); quitbutton.setfont(bigfont); Notes: some components don't use both colours labels are transparent (no background colour) panels have no foreground colour 9 10 JOptionPane (1) JOptionPane (2) JOptionPane class for common pop-up windows many capabilities; we'll look at 3 basic static methods int result = JOptionPane.showConfirmDialog(myFrame, "are you awake?"); JOptionPane.showMessageDialog(myFrame, "hello, world!"); result gets one of three values: JOptionPane.YES_OPTION JOptionPane.NO_OPTION JOptionPane.CANCEL_OPTION 11 12

JOptionPane (3) String name = JOptionPane.showInputDialog(myFrame, "what is your name?"); Outline 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 name gets user input -- or null if user clicks "Cancel" D. Graphics drawing pictures dynamically E. Mouse Events & Timers reacting to mouse clicks using timers for animation 13 14 Layout Managers Different Kinds of Layout Managers layout manager decides: position of each component in frame size of each component what changes when window is resized We will concentrate on three: BorderLayout FlowLayout GridLayout programmer's job: give layout manager some general instructions Each has different purpose, different layout algorithms. Real power comes from combining them -- different parts of frame. 15 16

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 BorderLayout default layout manager for frames frame has 5 positions: NORTH, SOUTH, EAST, WEST, CENTER demo... Button at preferred size: Same button, stretched: Rules: max of 1 component in each position north & south stretched horizontally to fit frame east & west stretched vertically center stretched both ways can specify gaps 17 18 FlowLayout GridLayout adds components left to right demo... lays out components in a rectangular grid demo... Rules: components always at preferred sizes breaks into multiple rows if necessary can specify alignment & gaps Rules: components are stretched to fill frame all components have same dimensions specify number of rows OR number of columns can specify gaps FAQ: can you create a vertical row with a FlowLayout? no! 19 20

Changing a Preferred Size Combining Layouts You may state a preference about the size of a component: btn.setpreferredsize(new Dimension(120,45)); You may also query the preferred size: 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" 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. 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 21 22 Panel Example 1 Panel Example 2 Suppose we want to put 6 buttons in a frame like this: Suppose we want to put 6 buttons in a frame like this: 23 24

Panel Example 3 More Complicated Example Suppose we want to put 6 buttons in a frame like this (small change from example 2): 25 26 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 Outline Part C: Components & Actions We will talk about 4 different kinds of components: buttons labels text fields text areas Plus how to use "listeners" to attach actions to components D. Graphics drawing pictures dynamically E. Mouse Events & Timers reacting to mouse clicks using timers for animation 27 28

Goal For This Sub-Topic A simple program using three kinds of components with actions attached demo... "clickable" button with a border JButton JButton addbutton = new JButton("add"); 29 30 JButton Methods JLabel String gettext() void settext(string newtext) Puts text on screen No borders, no actions, no background color (transparent) void setenabled(boolean enabled); default is true disabled button is "greyed out", no graphic reaction when clicked JLabel addlabel = new JLabel("amount to add: "); 31 32

JLabel Methods Text Components String gettext() void settext(string newtext) two kinds: text field (one line) text area (multiple lines) 33 34 one line only space for entering/displaying text JTextField "editable " JTextArea like a JTextField, but multiple lines not "editable" JTextField addfield = new JTextField(10); width in "m JTextField multfield = new JTextField(10); spaces" JTextArea quotetextarea = new JTextArea(3,20); JTextField totalfield = new JTextField(10); totalfield.seteditable(false); JTextArea databasearea = new JTextArea(20, 30); databasearea.seteditable(false); 35 36

Methods For Text Components String gettext() void settext(string newtext) 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 37 38 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 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 39 40

Sequence of Events Set-up (usually in constructor): create button create listener register listener with button you write this code Demo: Baby Calculator Three different styles: inner listener class(es) use frame as listener anonymous inner classes 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 41 42 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 Outline 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 D. Graphics drawing pictures dynamically E. Mouse Events & Timers reacting to mouse clicks using timers for animation 43 44

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 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 45 46 Graphics methods Note About Coordinates 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! Swing uses x & y coordinates, different from math x positive x: to the right positive y: down y 47 48

Simple Example Program start with a static display; add actions 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 49 50 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! 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 drawing pictures dynamically Outline E. Mouse Events & Timers reacting to mouse clicks using timers for animation 51 52

Part E: Timers & Mouse Events Timers & Animation 1. Using a timer for animation 2. Reacting to mouse events Goal: Picture changes at frequent intervals without user intervention. To accomplish this: program generates its own events that change the screen 53 54 Swing Timer Class Example Swing Timer: object that generates events at intervals. Timer(int delay, ActionListener listener) creates a timer, not started yet Program from last time: box with lines, grows & shrinks in response to buttons. New version: grows & shrinks by itself. demo... Timer timr = new Timer(500, new MyListenerClass()); will generate an ActionEvent every 500 milliseconds Caution: No guarantee events will occur exactly twice a second. Depends on program & system load. timr.start(); // timr starts generating events timr.stop(); // timr stops generating events 55 56

Review of Events & Listeners So Far We have discussed one kind of event: ActionEvent. Generated by several kinds of components: buttons text fields menu items ActionEvent object is simple: contains source of event Listener interface: ActionListener One method only -- actionperformed. Mouse Events A mouse event can be generated for mouse events inside any component. Kinds of mouse events: mouse enters the component mouse leaves the component mouse button pressed mouse button released mouse button clicked (pressed & released @ same spot) 57 58 MouseEvent Objects MouseListener interface A MouseEvent describes a mouse event. Methods to get location where event happened: getx() gety() public interface MouseListener { void mouseclicked(mouseevent e); void mouseentered(mouseevent e); void mouseexited(mouseevent e); void mousepressed(mouseevent e); void mousereleased(mouseevent e); } quick demo... 59 60

Helpful Class: MouseAdapter Next example: I want to react to mouse clicks, not the other 4 kinds of events. Straightforward way: create a MouseListener class, 4 of the methods will have empty bodies. Example: Line Drawing Program demo... Shortcut: MouseAdapter is a class that implements MouseListener. All 5 method bodies are empty. My example: extend MouseAdapter and just have to override one method. 61 62 Suggestion For Assignment 4 Use mousepressed instead of mouseclicked. Why? Hard to keep it mouse absolutely still during a click. 63