topic 9: swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with...

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

Upload: others

Post on 06-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

1CISC 124, Winter 2016, topic 9: Swing

Topic 9: Swing

Swing is a BIG libraryGoal:

• cover basics• give you concepts & tools for learning more

Swing = Java's GUI library

Assignment 5: Will be an open-ended Swing project."Programming Contest" last day of classes (if time permits)

Swing = Java's GUI librarySwing = Java's GUI library

Page 2: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

2CISC 124, Winter 2016, topic 9: Swing

Why are we studying Swing?1. Useful & fun!

2. Good application of OOP techniques

1. Useful

Page 3: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

3CISC 124, Winter 2016, topic 9: Swing

A. Basicsa little background & historyputting a frame (window) on the screen

B. Layoutsarranging multiple components in a framethree different kinds of "layout managers"

C. Components & Actionsmore kinds of componentsadding actions to components

D. Graphicsusing iconsdrawing custom pictures

Outline

Page 4: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

4CISC 124, Winter 2016, topic 9: Swing

Up to now: line-by-line programs:computer displays textuser types text

GUIs

Advantages & disadvantages?

GUI = Graphical User Interface

Page 5: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

5CISC 124, Winter 2016, topic 9: Swing

Early GUIs: write your own, huge amount of workCommon style emerged: mouse, buttons, text boxes, menusLibraries to help you write GUI programs

AWT

X-Windows for Unix/LinuxMicrosoft Foundation Classes (MFC) for Windowsetc.not portable

AWT = Abstract Window Toolkitpart of Java APIclasses for writing portable GUI programseasier to use than MFCcan be used by itself (no Swing)

Page 6: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

6CISC 124, Winter 2016, topic 9: 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)

Swing

Still use parts of AWT that Swing hasn't replaced:same old layout managers, basic graphics commands

Page 7: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

7CISC 124, Winter 2016, topic 9: Swing

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

Packages

Page 8: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

8CISC 124, Winter 2016, topic 9: Swing

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.

Tasks in GUI Programming

Common order:1. get screen looking right, no functionality2. add functionality

Another possibility:1. put components on screen, quick & sloppy2. add functionality, debug3. improve appearance

Page 9: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

9CISC 124, Winter 2016, topic 9: Swing

First practical task: get a window up on your screenand be able to exit gracefully

Getting a Window Running

Basic Swing class: JFrameA 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"

Page 10: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

10CISC 124, Winter 2016, topic 9: Swing

FontsA 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);

Page 11: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

11CISC 124, Winter 2016, topic 9: Swing

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

Notes: some components don't use both colours• labels are transparent (no background colour)• panels have no foreground colour

Page 12: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

12CISC 124, Winter 2016, topic 9: Swing

JOptionPane class for common pop-up windowsmany capabilities; we'll look at 3 basic static methods

JOptionPane (1)

JOptionPane.showMessageDialog(myFrame, "hello, world!");

Page 13: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

13CISC 124, Winter 2016, topic 9: Swing

JOptionPane (2)

int result = JOptionPane.showConfirmDialog(myFrame, "are you awake?");

result gets one of three values:JOptionPane.YES_OPTIONJOptionPane.NO_OPTIONJOptionPane.CANCEL_OPTION

Page 14: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

14CISC 124, Winter 2016, topic 9: Swing

JOptionPane (3)

String name = JOptionPane.showInputDialog(myFrame, "what is your name?");

name gets user input -- or null if user clicks "Cancel"

Page 15: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

15CISC 124, Winter 2016, topic 9: Swing

A. Basicsa little background & historyputting a frame (window) on the screen

B. Layoutsarranging multiple components in a framethree different kinds of "layout managers"

C. Components & Actionsmore kinds of componentsadding actions to components

Outline�

D. Graphicsusing iconsdrawing custom pictures

Page 16: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

16CISC 124, Winter 2016, topic 9: Swing

Layout Managerslayout 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

Page 17: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

17CISC 124, Winter 2016, topic 9: Swing

Different Kinds of Layout ManagersWe will concentrate on three:

● BorderLayout● FlowLayout● GridLayout

Each has different purpose, different layout algorithms.Real power comes from combining them -- different parts of frame.

Page 18: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

18CISC 124, Winter 2016, topic 9: Swing

Sizes of ComponentsEvery component has a "preferred size"For buttons and labels, based on the text and the fontSometimes layout managers "stretch" components beyond the "preferred size"

Button at preferred size: Same button, stretched:

Page 19: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

19CISC 124, Winter 2016, topic 9: Swing

BorderLayoutdefault layout manager for framesframe 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

Page 20: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

20CISC 124, Winter 2016, topic 9: Swing

FlowLayoutadds components left to rightdemo....

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

Page 21: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

21CISC 124, Winter 2016, topic 9: Swing

GridLayoutlays out components in a rectangular griddemo...

Rules:• components are stretched to fill frame• all components have same dimensions• specify number of rows OR number of columns• can specify gaps

Page 22: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

22CISC 124, Winter 2016, topic 9: Swing

Changing a Preferred SizeYou may state a preference about the size of a component:

btn.setPreferredSize(new Dimension(120,45));

This does *not* guarantee that the button will be the size you asked for!

The layout manager is still in charge.

Dimension size3 = btn.getPreferredSize();

btn.setPreferredSize(new Dimension(size3.width*2,size3.height));

You may also query the preferred size:

Page 23: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

23CISC 124, Winter 2016, topic 9: Swing

Combining LayoutsNow we know about 3 kinds of layoutsEach fairly limited by itselfCan sub-divide frame into sections, lay each out individuallyeach section called a "panel"

Swing class: JPanel

a component which is also a containercan add other components to a JPanel

to create:new JPanel(new GridLayout(2,0));

new JPanel(); // default is FlowLayout

Page 24: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

24CISC 124, Winter 2016, topic 9: Swing

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

Page 25: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

25CISC 124, Winter 2016, topic 9: Swing

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

Page 26: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

26CISC 124, Winter 2016, topic 9: Swing

Panel Example 3Suppose we want to put 6 buttons in a frame like this

(small change from example 2):

Page 27: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

27CISC 124, Winter 2016, topic 9: Swing

More Complicated Example

Page 28: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

28CISC 124, Winter 2016, topic 9: Swing

A. Basicsa little background & historyputting a frame (window) on the screen

B. Layoutsarranging multiple components in a framethree different kinds of "layout managers"

C. Components & Actionsmore kinds of componentsadding actions to components

Outline�

D. Graphicsusing iconsdrawing custom pictures

Page 29: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

29CISC 124, Winter 2016, topic 9: Swing

We will talk about 4 different kinds of components:● buttons● labels● text fields● text areas (optional – will not be tested)

Part C: Components & Actions

Plus how to use "listeners" to attach actions to components

Page 30: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

30CISC 124, Winter 2016, topic 9: Swing

Goal For This Sub-TopicA simple program using three kinds of components with actions

attacheddemo...

Page 31: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

31CISC 124, Winter 2016, topic 9: Swing

JButton"clickable" button with a border

JButton addButton = new JButton("add");

Page 32: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

32CISC 124, Winter 2016, topic 9: Swing

JButton MethodsString getText()

void setText(String newText)

void setEnabled(boolean enabled);

• default is true• disabled button is "greyed out", no graphic reaction when clicked

Page 33: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

33CISC 124, Winter 2016, topic 9: Swing

JLabelPuts text on screenNo borders, no actions, no background color (transparent)

JLabel addLabel =

new JLabel("amount to add: ");

Page 34: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

34CISC 124, Winter 2016, topic 9: Swing

JLabel MethodsString getText()

void setText(String newText)

Page 35: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

35CISC 124, Winter 2016, topic 9: Swing

Text Componentstwo kinds:

text field (one line)text area (multiple lines)

Page 36: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

36CISC 124, Winter 2016, topic 9: Swing

JTextFieldone line onlyspace for entering/displaying text

"editable"

not "editable"

JTextField addField = new JTextField(10);

JTextField multField = new JTextField(10);

JTextField totalField = new JTextField(10);

totalField.setEditable(false);

width in "m spaces"

Page 37: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

37CISC 124, Winter 2016, topic 9: Swing

JTextArealike a JTextField, but multiple lines

JTextArea databaseArea = new JTextArea(20, 30);

databaseArea.setEditable(false);

JTextArea quoteTextArea = new JTextArea(3,20);

Page 38: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

38CISC 124, Winter 2016, topic 9: Swing

Methods For Text ComponentsString getText()

void setText(String newText)

Page 39: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

39CISC 124, Winter 2016, topic 9: Swing

Event-Driven ProgrammingImperative Programming:

You specify sequence of commandsProgrammer in control

Event-Driven Programming:sequence driven by user's choicesprogram waits for "events" and reacts to them

Examples of events:• button click• menu choice• window closed or resized• mouse clicks, mouse motion

Page 40: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

40CISC 124, Winter 2016, topic 9: Swing

ActionEvent Classdescribes a simple event like a button click, menu choicemethods:

Object getSource()returns the component that "caused" the event

(button that was clicked)

String getActionCommand()returns text from component

Page 41: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

41CISC 124, Winter 2016, topic 9: Swing

ActionListener Interfacepublic 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

Page 42: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

42CISC 124, Winter 2016, topic 9: Swing

Sequence of EventsSet-up (usually in constructor):• create button• create listener• register listener with button

During Program Run:1. user clicks button2. Swing checks whether button has a listener3. if yes:

Swing creates an ActionEvent objectSwing calls actionPerformed method in listener with the

object as argument

you write this code

Swing does this for you

Page 43: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

43CISC 124, Winter 2016, topic 9: Swing

Demo: Baby CalculatorThree different styles:

• inner listener class(es)

• use frame as listener

• anonymous inner classes

Page 44: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

44CISC 124, Winter 2016, topic 9: Swing

A. Basicsa little background & historyputting a frame (window) on the screen

B. Layoutsarranging multiple components in a framethree different kinds of "layout managers"

C. Components & Actionsmore kinds of componentsadding actions to components

D. Graphicsusing iconsdrawing custom pictures

Outline�

Page 45: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

45CISC 124, Winter 2016, topic 9: Swing

A. Basicsa little background & historyputting a frame (window) on the screen

B. Layoutsarranging multiple components in a framethree different kinds of "layout managers"

C. Components & Actionsmore kinds of componentsadding actions to components

Outline�

D. Graphicsusing iconsdrawing custom pictures

Page 46: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

46CISC 124, Winter 2016, topic 9: Swing

We've seen how to put text on componentsAlso possible to put "icon" (image from file) onto component.

Part D: Graphics

Sometimes we want to draw our own pictures dynamicallyOften use an empty panel

Page 47: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

47CISC 124, Winter 2016, topic 9: Swing

paintComponent (1)every component has a paintComponent method

default method: draws text, borders, etc. on screenyou can override to create your own graphics effects

Page 48: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

48CISC 124, Winter 2016, topic 9: Swing

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

Page 49: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

49CISC 124, Winter 2016, topic 9: Swing

Graphics methodsvoid 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!

Page 50: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

50CISC 124, Winter 2016, topic 9: Swing

Note About CoordinatesSwing uses x & y coordinates, different from math

x

y

positive x: to the right

positive y: down

Page 51: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

51CISC 124, Winter 2016, topic 9: Swing

Simple Example Programstart with a static display; add actions

Page 52: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

52CISC 124, Winter 2016, topic 9: Swing

paintComponent vs. repaintpaintComponent:

• 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

Page 53: Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some

53CISC 124, Winter 2016, topic 9: Swing

SummaryFor 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!