Swing
week date Day 1 (Mon/Tues) Day 2 (Tues/Wed) Day 3 (Thurs/Fri)
1 Jan 9 Intro Ariane 5 More Software Disasters
2 Jan 16 Software Quality Requirements Requirements
(assn 1 due Friday)
3 Jan 23 Assignment Discussion Requirements Testing overflow
4 Jan 30 Test Plans Usability Java/UML
(assn 2 due Thursday)
5 Feb 6 Java/UML Swing Swing
6 Feb 13 Swing Swing Swing
7 Feb 27 Swing Midterm Review no class!
(assn 3 due Tuesday) Midterm: Wed. p.m.
8 Mar 6 Design Patterns Design Patterns Design Patterns
9 Mar 13 Software Testing Software Testing Software Testing
10 Mar 20 Software Testing Software Testing Software Process
(assn 4 due Tuesday)
11 Mar 27 Software Process Software Process Guest lecture
12 Apr 3 overflow overflow Overflow
(assn 5 due Thursday)
CISC 323 winter 2006, Swing 1
New Topic: GUIs
GUI = Graphical User Interface
Up to now: line-by-line programs:
computer displays text
user types text
With a GUI:
computer displays information all over screen
(text, pictures, symbols, etc.)
user enters information by clicking buttons, choosing menu
options, typing text into special boxes, etc.
Advantages of GUIs:
prettier, more fun
more user-friendly
CISC 323 winter 2006, Swing 2
Why Study GUIs Now?
1. Good OOP practice
2. Useful (CISC 323 & later)
3. Fun / motivating
4. Learn about event-driven programming
CISC 323 winter 2006, Swing 3
Goals & Readings
This is a big topic – can't learn it all in 2 weeks!
Goals:
• learn the basics
• lay a foundation so you can look up more
Required Reading: chapter in courseware
Optional Extra Readings:
• listed on web, mostly Java Tutorial if you want more
details, extra examples
CISC 323 winter 2006, Swing 4
Sub-Topics
1. Basics (getting a Frame up & running)
2. Layouts (how to put things into your Frame)
3. Actions (making your components do things)
4. More kinds of components
5. Making your Frame pretty: colors, fonts, icons
6. Changing frames
7. Dialogs
CISC 323 winter 2006, Swing 5
GUI Libraries
Early GUIs: write your own, huge amount of work
Common style emerged: buttons, text boxes, menus
Libraries to help you write GUI programs
X-Windows for Unix/Linux
Microsoft Foundation Classes (MFC) for Windows
something else for Macs
none portable
AWT = Abstract Windows Toolkit
part of Java API
classes for writing portable GUI programs
easier to use than MFC
CISC 323 winter 2006, Swing 6
Swing
Extension to AWT: part of Java API in versions 1.2 & later
• some new features
(file & color choosers, fancier graphics features)
• replaced some items with improved versions
• some improvements to existing features
(double buffering)
• most Swing class start with "J":
• JButton
• JFrame
• etc.
Still use parts of AWT that Swing hasn't replaced:
same old layout managers, basic graphics commands
CISC 323 winter 2006, Swing 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 fairly 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
CISC 323 winter 2006, Swing 8
Kinds of Components
Task for Assignment 3: design user interface
What kinds of components can you use?
• buttons
• text fields
• labels
• pop-up windows (JOptionPane & dialogs)
• combo boxes (drop-down list of choices)
• optional: different fonts & colours, icons
CISC 323 winter 2006, Swing 9
Getting a Window Running
First Swing class to learn: JFrame
A frame is a window
with:
• a border
• a title
• menu bar
(optional)
• minimize,
maximize,
close buttons
• inner area for
contents
CISC 323 winter 2006, Swing 10
The Basics: Creating a Frame
First practical task: get a window up on your screen
and be able to exit gracefully
"baby" demos
Purpose: show how to get a simple frame onto the screen
Summary:
• convention is to subclass JFrame
• must explicitly make the frame visible
• must set size or get tiny frame
• must specify window-closing behavior
Programs are on the web for your reference
CISC 323 winter 2006, Swing 11
Next Sub-Topic: Layouts
1. Basics (creating a Frame with one button) 9
2. Layouts (how to put things into your Frame) ←
3. Actions (making your components do things)
4. More kinds of components
5. Making the Frame pretty: colors, fonts, icons
6. Changing frames
7. Dialogs
CISC 323 winter 2006, Swing 12
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
CISC 323 winter 2006, Swing 13
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.
CISC 323 winter 2006, Swing 14
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
Button at preferred size: Same button, stretched:
CISC 323 winter 2006, Swing 15
BorderLayout
Default layout manager for frames
Frame has 5 positions:
North, South, East, West, Center
Demo....
Rules:
• max of 1 component in each position
• north & south stretched horizontally to fit frame
• east & west stretched vertically
• center stretched both ways
CISC 323 winter 2006, Swing 16
GridLayout
Lays out components in a rectangular grid
Demo...
Rules:
• components are stretched to fill frame
• all components are stretched to exactly the same size
• specify number of rows OR number of columns
CISC 323 winter 2006, Swing 17
FlowLayout
Adds components left to right
Demo....
Rules:
• components always at preferred sizes, never stretched
• breaks into multiple rows if necessary
• can specify alignment
CISC 323 winter 2006, Swing 18
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“)
Java class: JPanel
• a component which is also a Container
• can add other components to a JPanel
• to create:
new JPanel(new GridLayout(2,0));
or:
new JPanel(); // default is FlowLayout
CISC 323 winter 2006, Swing 19
Panel Example
Suppose we want to put 6 buttons in a frame like this:
on web: SimplePanelDemo.java
CISC 323 winter 2006, Swing 20
Calculator Example (1)
CISC 323 winter 2006, Swing 21
Calculator Example (2)
First job: layout 3
Second job: functionality
How to lay out?
1
Identify 3 sections of screen
Section 1: 12 buttons in panel
with 4x3 grid layout
Section 2: 5 buttons in panel
2
5x1 grid
Section 3: text field
Use BorderLayout to lay these sections out on JFrame
CISC 323 winter 2006, Swing 22
Next Sub-Topic: Actions
1. Basics (creating a frame with one button) 9
2. Layouts (how to put things into your frame) 9
3. Actions (making your components do things) ←
4. More kinds of components
5. Making your frame pretty: colors, fonts, icons
6. Changing frames
7. Dialogs
CISC 323 winter 2006, Swing 23
Events
GUI programs are "event-driven"
many kinds of events in a GUI program:
• user clicks button
• user types a key
• window is re-sized
• user chooses menu item
• etc.
Programmer chooses which types of events program
will react to and how
CISC 323 winter 2006, Swing 24
Event-Driven Programming
Normal line-oriented program:
• Program specifies exactly what will happen.
• Knows when input will arrive.
• Makes decision on the basis of the input.
Event-Driven GUI Program:
set things up, then programmer’s responsibility
in infinite loop:
wait for a event Swing’s responsibility
react to the event
CISC 323 winter 2006, Swing 25
ActionEvent Class
describes a simple event like a button click or menu choice
methods:
getSource(): returns the component that "caused"
the event
(button that was clicked)
getActionCommand(): returns the label from the
component as a String
CISC 323 winter 2006, Swing 26
Event Handlers
Event Handler = method that reacts to an event.
For every possible event that you care about:
• write an event handler: takes an ActionEvent
object as a parameter
• "register" the handler with a component:
"please call this method when someone clicks this button."
In Java, an event handler is packaged inside an
object called a "listener".
CISC 323 winter 2006, Swing 27
ActionListener interface
public interface ActionListener {
void actionPerformed(ActionEvent e);
}
This is the event handler method
Program can register an action listener for a button.
Meaning: when button is clicked, call actionPerformed in
this listener
CISC 323 winter 2006, Swing 28
Sequence of Events
1. User clicks button
2. Does button have action listener?
If no, do nothing.
3. If yes, create an ActionEvent
describing the button click.
4. Call the action listener's
actionPerformed method
with the ActionEvent object
as argument
CISC 323 winter 2006, Swing 29
Common Trick
Make one class do double-duty: acts as frame and as its own
action listener (contains actionPerformed method)
demo: Add a simple action to a button
CISC 323 winter 2006, Swing 30
Digression: JOptionPane (1)
Class with useful static methods to provide common kinds of
small "pop-up" windows
JOptionPane.showMessageDialog(parent, "hello, world!");
parent must be a frame
usually use this
pop-up is modal: blocks input to all other windows
CISC 323 winter 2006, Swing 31
JOptionPane (2)
int result = JOptionPane.showConfirmDialog(parent,
"are you awake?");
result gets one of three values:
YES_OPTION
NO_OPTION
CANCEL_OPTION
CISC 323 winter 2006, Swing 32
JOptionPane (3)
String name = JOptionPane.showInputDialog(parent,
"what is your name?");
Name gets user input -- or null if user clicks "Cancel"
CISC 323 winter 2006, Swing 33
JOptionPane (4)
See API documentation for more JOptionPane stuff
• fourth kind of window: select among options
• all have overloaded versions with more parameters
• advice: stick to static methods
Simple demo program for JOptionPane on web site for your
reference
CISC 323 winter 2006, Swing 34
Sharing an ActionListener
use getActionCommand or getSource to see where event
came from
demo: two buttons with actions
CISC 323 winter 2006, Swing 35
Next Sub-Topic: More Components
1. Basics (creating a frame with one button) 9
2. Layouts (how to put things into your frame) 9
3. Actions (making your components do things) 9
4. More kinds of components ←
5. Making your frame pretty: colors, fonts, icons
6. Changing frames
7. Dialogs
CISC 323 winter 2006, Swing 36
Kinds of Components
Required for CISC 323:
JButton
JLabel
JTextField
JComboBox
These are enough for many GUIs
There are many more
CISC 323 winter 2006, Swing 37
JButton Class
To create:
JButton okButton = new JButton("OK");
Methods:
void setText(String text);
String getText();
void setEnabled(boolean);
Buttons are enabled by default
If not enabled, "greyed out" and user can't click
CISC 323 winter 2006, Swing 38
Labels
A way of putting text onto a frame
no border, no actions
May be a label for another component
May be a header or informative message
CISC 323 winter 2006, Swing 39
JLabel Class
To create:
JLabel nameLabel = new JLabel("enter name: ");
Methods:
void setText(String text);
String getText();
CISC 323 winter 2006, Swing 40
Label Alignment
Text in label is aligned. JLabel has 3 constants for alignment:
LEFT, RIGHT, CENTER
Set in constructor or with setHorizontalAlignment method
Alignment doesn’t matter unless label is stretched horizontally
CISC 323 winter 2006, Swing 41
Text Components
Two kinds:
• text field (one line)
• text area (multiple lines) (not required for 323)
CISC 323 winter 2006, Swing 42
JTextField
One line only
to create:
JTextField nameField = new JTextField(10);
or:
JTextField nameField = new JTextField("Fred");
or:
JTextField nameField = new JTextField("Fred", 10);
CISC 323 winter 2006, Swing 43
JTextField Methods
setText() and getText() like buttons and labels
setEditable(boolean b): if true, user can type in
setHorizontalAlignment like labels
CISC 323 winter 2006, Swing 44
Putting These Three Together
demo: simple calculator example
CISC 323 winter 2006, Swing 45
One More Component Type: JComboBox
Used in old CD catalog program.
First, create an array of the choices:
private static final String[] sortingChoices =
{"title","composer","performer"};
Now create the combo box:
sortComboBox = new JComboBox(sortingChoices);
In action listener for the buttons in the dialog:
int indexChosen = sortComboBox.getSelectedIndex();
Gets array index of currently selected item
CISC 323 winter 2006, Swing 46
Next Sub-Topic: Making a Frame Look
Nice
1. Basics (creating a frame with one button) 9
2. Layouts (how to put things into your frame) 9
3. Actions (making your components do things) 9
4. More kinds of components 9
5. Making your frame pretty: colors, fonts, icons ←
6. Changing frames
7. Dialogs
CISC 323 winter 2006, Swing 47
Ways to Change Your Frame's Appearance
This material is optional. We won’t test you on it or
require it in assignments.
1. Colours (optional)
2. Fonts (optional)
3. Icons (optional)
4. More fancy graphics: not covered
CISC 323 winter 2006, Swing 48
Colours
Most components have two colours: background & foreground
Labels have only foreground (background is "transparent")
Frames & panels have only background
yellow background white background
red foreground
blue foreground
frame has gray background (default)
CISC 323 winter 2006, Swing 49
Color class
Use a Color object to represent a colour.
Easiest way: constants
Color.red
Color.blue
etc. (on summary sheet or look up in API)
For more control, specify red, green and blue components:
new Color(200, 150, 255)
The above makes violet:
Each component from 0 to 255.
CISC 323 winter 2006, Swing 50
Putting Colours into a Frame
Every component has two methods for setting colours:
setForeground
setBackground
Example:
myButton.setForeground(Color.red);
CISC 323 winter 2006, Swing 51
Fonts
A font has three components:
name of font:
style (Font.PLAIN, Font.BOLD or Font.ITALIC)
size (in points, as in Word)
In many of our sample programs for demo in class:
button1.setFont(
new Font("Serif", Font.PLAIN, 24));
CISC 323 winter 2006, Swing 52
Icons
Examples so far: Labels and buttons contain text only
Can put pictures instead of or with text
Icon object represents a picture
Example:
ImageIcon stopIcon =
new ImageIcon("stop.jpg");
stopButton = new JButton(stopIcon);
Image file "stop.jpg" must be in same folder as program.
CISC 323 winter 2006, Swing 53
Next Sub-Topic: Changing Frames
1. Basics (creating a frame with one button) 9
2. Layouts (how to put things into your frame) 9
3. Actions (making your components do things) 9
4. More kinds of components 9
5. Making your frame pretty: colors, fonts, icons 9
6. Changing frames ←
7. Dialogs
CISC 323 winter 2006, Swing 54
Changing Contents of Frame Dynamically
So far, frame contents have not changed during program:
• add components to frame at start-up (constructor)
• components don't go away
• no new components added
Often convenient to add/remove components during program.
Program may have different "modes",
or need variable numbers of components
CISC 323 winter 2006, Swing 55
Reminder: Container Class
contents
JFrame Container
JPanel
CISC 323 winter 2006, Swing 56
Adding Components To Container
for all but BorderLayout, usual form is:
add(Component comp)
adds to last position in container
another version:
add(Component comp, int index)
adds to a specified position (counting from zero)
CISC 323 winter 2006, Swing 57
Removing Components From a Container
Container class also has remove methods:
void remove(Component comp)
removes a designated component
void remove(int index)
removes a component by index
(counting from zero)
CISC 323 winter 2006, Swing 58
Example Program: Area Calculator
User enters dimensions of shape
Program computes & displays the area
Prompts & fields depend on type of shape
demo....
CISC 323 winter 2006, Swing 59
Two Modes
Program can operate in two modes
Contents of frame is different for each mode
User switches modes by changing the combo box.
CISC 323 winter 2006, Swing 60
Changing Modes
Initial mode is circle.
Constructor creates all rows.
Only adds the three rows for circle mode to frame.
When user selects rectangle mode, event handler:
• removes radius row
• adds width and height rows
When user selects circle mode again, event handler:
• removes width and height rows
• adds radius row
CISC 323 winter 2006, Swing 61
More Lessons From This Program
• When contents of frame changes, needs to be re-packed.
• This program must read and write numbers to/from text
fields (we’ve already seen an example of this)
• This program must write a floating-point number to a text
field; it may be too long for the field.
CISC 323 winter 2006, Swing 62
Putting Numbers Into Text Fields
First draft of program:
Problem: Area is too big to fit into text field.
Solution: round it to a limited number of decimals.
CISC 323 winter 2006, Swing 63
DecimalFormat Class
A DecimalFormat object contains a format method to
transform a number into a String
To create a DecimalFormat object, give it a pattern –
instructions on how to format numbers
General pattern rules are complicated.
Simple pattern to round a number: "0.0##"
one or more digits before the decimal point
one to three digits after the decimal point
To use scientific notation instead: "0.0##E0"
CISC 323 winter 2006, Swing 64
Next Sub-Topic: Multi-Window Programs
(Dialogs)
1. Basics (creating a frame with one button) 9
2. Layouts (how to put things into your frame) 9
3. Actions (making your components do things) 9
4. More kinds of components (labels & text 9
components)
5. Making your frame pretty: colors, fonts, icons 9
6. Changing frames 9
7. Dialogs ←
CISC 323 winter 2006, Swing 65
Multiple-Window Programs
So far, GUIs with one window
Complicated problem: may want to separate into several
windows
One way to organize:
• one "main" window
• can pop up "dialogs" for particular purposes
• display a message (JOptionPane)
• input simple value (JOptionPane)
• custom dialog (subclass of JDialog)
CISC 323 winter 2006, Swing 66
Custom Dialogs: using the JDialog Class
A JDialog is almost exactly the same as a JFrame.
• same methods
• has a "content pane", can add components
Differences from a JFrame:
• has an owner (a frame or another dialog)
• may be modal
Constructor:
new JDialog(JFrame owner, boolean modal)
or JDialog
CISC 323 winter 2006, Swing 67
Modal Dialogs
When a modal dialog pops up the "parent" is frozen.
Can't do anything until you deal with the dialog.
Most windows programs use modal dialogs
Parent is suspended only while dialog is visible.
Usual pattern:
• Create custom dialogs during program set-up, all
invisible.
• Make visible when you need them.
• Faster than creating each time you need.
CISC 323 winter 2006, Swing 68
Example
Demo program uses custom dialog to input information about
people (name, address. phone number, age)
CISC 323 winter 2006, Swing 69
Person Class
// Simple class to group info about a person
public class Person {
private String name;
private String address;
private String phone;
private int age;
public Person(String name, String address,
String phone, int age) {
this.name = name;
this.address = address;
this.phone = phone;
this.age = age;
} // end constructor
CISC 323 winter 2006, Swing 70
Person Class (2)
public String getName() {return name;}
public String getAddress() {return address;}
public String getPhone() {return phone;}
public int getAge() {return age;}
// Creates a multi-line String describing the
// person
public String toString() {
return "name: " + name + "\n"
+ "address: " + address + "\n"
+ "phone number: " + phone + "\n"
+ "age: " + age;
} // end toString
} // end class Person
CISC 323 winter 2006, Swing 71
PersonDialog
public class PersonDialog extends JDialog
implements ActionListener {
// Person object from data entered by the user
private Person thePerson;
public Person getPerson() {return thePerson;}
private JTextField nameField, addressField,
phoneField, ageField;
CISC 323 winter 2006, Swing 72
PersonDialog (2)
public PersonDialog(JFrame parentFrame) {
// call JDialog constructor, make dialog modal
super(parentFrame, true);
Container contents = getContentPane();
contents.setLayout(new GridLayout(0,1));
// lay out components – just as in a JFrame
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
pack();
// Note: no call to setVisible
} // end constructor
CISC 323 winter 2006, Swing 73
PersonDialog (3)
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ok")) {
String name = nameField.getText();
String address = addressField.getText();
String phone = phoneField.getText();
String ageText = ageField.getText();
int age;
try {
age = Integer.parseInt(ageText.trim());
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this,
"error: \"" + ageText +
"\" is not an integer");
return; // don't continue with actionPerformed
} // end try/catch
CISC 323 winter 2006, Swing 74
PersonDialog (4)
if (age < 0 || age > 150) {
JOptionPane.showMessageDialog(this,
"error: age must be between 0 and 150");
return;
} // end if
// Create an object out of the data entered.
// Save it in instance variable so parent can
// as for it later.
thePerson = new Person(name, address, phone, age);
// Make dialog disappear and return control to
// its parent
setVisible(false);
}
CISC 323 winter 2006, Swing 75
PersonDialog (5)
else if (e.getActionCommand().equals("cancel")) {
thePerson = null;
setVisible(false);
}
else {
JOptionPane.showMessageDialog(this,
"internal error: unknown button");
} // end if
} // end actionPerformed
CISC 323 winter 2006, Swing 76
Main Frame: DialogDemo
public class DialogDemo extends JFrame
implements ActionListener {
private PersonDialog personDialog =
new PersonDialog(this);
private Vector people = new Vector();
private JButton enterButton, searchNameButton,
searchAgeButton, quitButton;
CISC 323 winter 2006, Swing 77
DialogDemo (2)
public DialogDemo() {
// Does the usual constructor stuff.
// Creates buttons and adds to frame.
// Registers frame as listener for the buttons
....
} // end constructor
CISC 323 winter 2006, Swing 78
DialogDemo (3)
public void actionPerformed(ActionEvent e) {
// use getSource to identify the button
Object source = e.getSource();
if (source == enterButton) {
personDialog.setVisible(true);
// no return from above until dialog is finished
// Retrieve the person that the user entered
Person newPerson = personDialog.getPerson();
// Add the new person to our list unless
// use cancelled
if (newPerson != null)
people.add(newPerson);
}
CISC 323 winter 2006, Swing 79
DialogDemo (4)
else if (source == searchNameButton)
{
....
else if (source == searchAgeButton) {
}....
}
else if (source == quitButton)
System.exit(0);
else
JOptionPane.showMessageDialog(this,
"internal error: unknown button");
} // end actionPerformed
CISC 323 winter 2006, Swing 80
One More Thing
Using PersonDialog a second time: Old input will still be in
the boxes. Do we want this?
Sometimes it's a good thing – if user will be entering a lot of
similar data.
This case, maybe not.
Prevent by adding actions to happen every time dialog becomes
visible.
demo...
CISC 323 winter 2006, Swing 81