topic 9: swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with...
TRANSCRIPT
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
2CISC 124, Winter 2016, topic 9: Swing
Why are we studying Swing?1. Useful & fun!
2. Good application of OOP techniques
1. Useful
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
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
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)
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
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
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
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"
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);
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
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!");
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
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"
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
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
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.
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:
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
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
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
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:
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
24CISC 124, Winter 2016, topic 9: Swing
Panel Example 1Suppose we want to put 6 buttons in a frame like this:
25CISC 124, Winter 2016, topic 9: Swing
Panel Example 2Suppose we want to put 6 buttons in a frame like this:
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):
27CISC 124, Winter 2016, topic 9: Swing
More Complicated Example
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
�
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
30CISC 124, Winter 2016, topic 9: Swing
Goal For This Sub-TopicA simple program using three kinds of components with actions
attacheddemo...
31CISC 124, Winter 2016, topic 9: Swing
JButton"clickable" button with a border
JButton addButton = new JButton("add");
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
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: ");
34CISC 124, Winter 2016, topic 9: Swing
JLabel MethodsString getText()
void setText(String newText)
35CISC 124, Winter 2016, topic 9: Swing
Text Componentstwo kinds:
text field (one line)text area (multiple lines)
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"
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);
38CISC 124, Winter 2016, topic 9: Swing
Methods For Text ComponentsString getText()
void setText(String newText)
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
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
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
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
43CISC 124, Winter 2016, topic 9: Swing
Demo: Baby CalculatorThree different styles:
• inner listener class(es)
• use frame as listener
• anonymous inner classes
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�
�
�
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
�
�
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
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
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
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!
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
51CISC 124, Winter 2016, topic 9: Swing
Simple Example Programstart with a static display; add actions
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
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!