What We Will Cover
Illuminations
Questions on Completed Assignments?
^ top
8.1: Graphical-User Interfaces
Objectives
At the end of the lesson the student will be able to:
- Describe the basic operation of Graphical User Interfaces (GUUIs)
- Identify the common Swing components
- Create a simple GUI
|
^ top
8.1.1: About Graphical User Interface (GUIs)
- Graphical User Interface (GUI) -- pronounced "gooey"
- Graphical: not just text or characters but includes windows, menus, buttons, etc.
- User: person using the program via mouse, keyboard, etc.
- Interface: interaction with the program using visual controls, widgets, etc.
- Most modern programs use a GUI
- Typical graphical elements include:
- Window: portion of screen that serves as a smaller screen within the screen
- Menu: list of alternatives offered to user
- Button: looks like a button that can be pressed
- Objects that make up a GUI are called components
- Java provides two sets of components: AWT and Swing
- AWT (Abstract Window Toolkit) is the older set of components
- Relies on the underlying visual components of the operating system
- GUIs look different on each operating system
- Swing (like the dance) is the newer set of components
- Draws its own visual components on the screen
- Originates from AWT components
- Adds new capabilities
- We will use Swing components
Example GUI
^ top
8.1.2: Event-Driven Programming
- Programs with GUIs often use Event-Driven Programming
- Program waits for events to occur and then responds
- Examples of events include:
- Clicking a mouse button
- Dragging the mouse
- Pressing a key on the keyboard
Terminology
- Firing an event: when an object generates an event
- Listener: object that waits for events to occur
- Event handler: method that responds to an event
- Component: a visual object that responds to user actions
- Container: an object that holds other objects
Traditional "Uneventful" Programming vs. Event-Driven Programming
| "Uneventful" |
Event Driven |
| Which action is taken next determined by the computer |
Which action taken next determined by the user |
| Program starts in main and ends after the last statement completes |
Program starts in main but ends when the user says to end |
| Programs are lists of instructions performed in order with some branching |
Programs are objects that can fire events and objects that react to events |
| Program performed by one agent -- the computer |
Program is interaction between user and computer |
^ top
8.1.3: Containment Hierarchy
- Java GUI components fall into three categories
Top-Level Container
- Basic window structure that ties the GUI into the operating system
- Includes capabilities such as borders and resizability
- Holds intermediate containers and atomic components
- Every GUI program must have one top-level container
Intermediate Container
- Graphical object displayed in a top-level container
- Can also hold other intermediate containers and atomic components
- Used to simplify placement of atomic components
Atomic Components
- Graphical objects used to accept input or display information
- Must be placed in a container using the
add method
^ top
8.1.4: Swing Components
About Swing Components
- Special library of classes that allows Java programs to have a windowing interface
- Part of larger collection called Java Foundation Classes or JFC
- Standard part of all versions of Java 2 (JDK 1.2) in package javax.swing
- Can easily identify Swing components because their names start with "J"
- Some of the frequently used components are:
Top-Level Containers
| Component |
Description |
| JFrame |
A top-level window with a title, border and buttons for closing and iconifying the window. |
| JApplet |
Container for applets, which are small programs that run inside a Web browser |
| JOptionPane |
Limited window that makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something. |
Intermediate Containers
| Component |
Description |
| JPanel |
Provides a general-purpose container for atomic components and other intermediate containers. |
| JRootPane |
A container used by JFrame, JApplet and other containers. |
Atomic Components
| Component |
Description |
| JButton |
Display area that triggers an event when clicked. |
| JComboBox |
Drop-down list of items from which the user can make a selection by clicking an item in the list or possibly by typing into a box. |
| JCheckBox |
GUI component that can be selected or deselected and displays its state to the user as a checked square. |
| JRadioButton |
GUI component that can be selected or deselected and displays its state to the user as a filled or unfilled circle. |
| JLabel |
Display area for text or icons |
| JTextField |
Single-line display and input area for the user to enter data from the keyboard. |
| JTextArea |
Multi-line display and input area for the user to enter data from the keyboard. |
Further Information
^ top
8.1.5: Simple GUI Example
- Demonstrate use of Swing components in a simple window
import javax.swing.*;
public class HelloWindow extends JFrame {
public static void main(String[] args) {
new HelloWindow();
}
public HelloWindow() {
super("Hello Window Application");
JLabel msg = new JLabel("Hello GUI World");
getContentPane().add(msg);
setSize(300, 150);
setVisible(true);
}
}
Notes on Code
import javax.swing.*;
Must import the javax.swing library to use Swing components
public class HelloWindow extends JFrame {
Our application extends JFrame
Inherits all the methods available in JFrame
public static void main(String[] args) {
new HelloWindow();
}
Method main instantiates the window object for our application
public HelloWindow() {
super("Hello Window Application");
Constructor for our application calls the superclass constructor
- Sets the title of the window
JLabel msg = new JLabel("Hello GUI World");
getContentPane().add(msg);
JLabel shows text or an image on a component
Add the JLabel component to the JRootPane intermediate container
setSize(300, 150);
Set the size of the window to 300 pixels wide by 150 pixels high
setVisible(true);
Shows this window to the user
Window will not show up on the screen without a line like this one
^ top
Exercise 8.1
Take one minute to prepare answers to the following questions:
- What are the three types of GUI components?
- What elements of a GUI does a user see?
^ top
8.2: Event Handling
Objectives
At the end of the lesson the student will be able to:
- Add event handlers to GUIs
- Use Adapter Classes with GUIs
- Use Inner Classes with GUIs
- Use Anonymous Inner Classes with GUIs
- Use JButtons and Action Listeners
|
^ top
8.2.1: Java Event-Handling Model
About the Event-handling Model
- Three parts to the event-handling model
- Event source -- GUI component with which user interacts
- Event object -- encapsulates information about event that occurred
- Event listener -- receives event object when notified, then responds
- Programmer must perform two tasks:
- Implement the event-handling method (event handler)
- Register an event listener with an event source
Some Event Classes
- Event classes define events that are triggered when users do things
- Some of the common events are shown below
java.lang.Object
|
+--java.util.EventObject
|
+--java.awt.AWTEvent
|
+--java.awt.event.ActionEvent
|
+--java.awt.event.AdjustmentEvent
|
+--java.awt.event.ItemEvent
|
+--java.awt.event.ComponentEvent
|
+--java.awt.event.ContainerEvent
|
+--java.awt.event.FocusEvent
|
+--java.awt.event.PaintEvent
|
+--java.awt.event.WindowEvent
|
+--java.awt.event.InputEvent
|
+--java.awt.event.KeyEvent
|
+--java.awt.event.MouseEvent
Some Event-listener Interfaces
- Listener's contain methods that are activated when events occur
- Programmers implement the methods defined in the interface
- Must first register the event listener with the event source
EventCreatingObject.addSomeListener(eventHandlerObject)
Some of the common listener interfaces are shown below
java.util.EventListener
|
+--java.awt.event.ActionListener
|
+--java.awt.event.AdjustmentListener
|
+--java.awt.event.ComponentListener
|
+--java.awt.event.ContainerListener
|
+--java.awt.event.FocusListener
|
+--java.awt.event.ItemListener
|
+--java.awt.event.KeyListener
|
+--java.awt.event.MouseListener
|
+--java.awt.event.MouseMotionListener
|
+--java.awt.event.TextListener
|
+--java.awt.event.WindowListener
^ top
8.2.2: Adding Window Listeners
public void windowClosing(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
Each method is associated with a window event, such as a window closing
Can inherit all seven methods from WindowAdapter
- Defines methods with empty bodies
Must then override the methods you want to implement
For Example:
public class WinHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
Can then add the following lines to our HelloWindow class to register the event handler
WinHandler handler = new WinHandler();
addWindowListener(handler);
Further Information
^ top
8.2.3: Inner Classes
- For small listener classes, it is common to use an inner class
- Inner classes are classes within classes
- Advantages of inner classes:
- Make the outer class more self-contained
- Easily accessed by outer class
- Name is local to outer class so it can have the same name as another class
- Frequently used with GUI event-handling
- For example, can implement
WinHandler as an inner class
- Outer class is responsible for creating inner class objects
- For example, our
HelloWindow class would look like this:
import javax.swing.*;
import java.awt.event.*;
public class HelloWindow2 extends JFrame {
public static void main(String[] args) {
new HelloWindow2();
}
public HelloWindow2() {
super("Hello Window Application");
WinHandler handler = new WinHandler();
addWindowListener(handler);
JLabel msg = new JLabel("Hello GUI World");
getContentPane().add(msg);
setSize(300, 150);
setVisible(true);
}
public class WinHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}
Further Information
Compiling puts inner class code in a separate .class file
HelloWindow2$WinHandler.class
Inner classes with class names can have public, protected, private or package access
Inner classes can be declared static
Also see: Implementing Nested Classes
^ top
8.2.4: Anonymous Inner Classes
- One other commonly used way to write handlers is to use an anonymous class
- Anonymous inner class is an inner class without a name
- Place the event handling code within the statement that creates the event handling class
- For example:
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
System.exit(0);
}});
Comparing this to the preceding inner class code:
WinHandler handler = new WinHandler();
addWindowListener(handler);
...
public class WinHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
Notice both what is the same and what is different
Using an anonymous class, our HelloWindow class would look like this:
import javax.swing.*;
import java.awt.event.*;
public class HelloWindow3 extends JFrame {
public static void main(String[] args) {
new HelloWindow3();
}
public HelloWindow3() {
super("Hello Window Application");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
System.exit(0);
}});
JLabel msg = new JLabel("Hello GUI World");
getContentPane().add(msg);
setSize(300, 150);
setVisible(true);
}
}
Further Information
- Compiled class code shows up as a $ followed by a number
HelloWindow3$1.class
Since we do not assign a name, the compile makes one up
Being pragmatic, the compiler assigns the first anonymous class the name "1"
The next anonymous class get assigned the number 2, etc
Also see: Implementing Nested Classes
^ top
8.2.5: Default Operations on JFrame
- By default, when a user closes a
JFrame it is hidden
- Frame still exists even though it is not visible
- Can change the behavior using method
setDefaultCloseOperation
- Use one of the following
JFrame constants
- DO_NOTHING_ON_CLOSE
- Do nothing when the user requests that the frame close
- HIDE_ON_CLOSE
- The default operation
- Hide the frame when the user closes it
- Makes the frame invisible
- DISPOSE_ON_CLOSE
- Hide and dispose of the frame when the user closes it
- Removes the frame from the screen and frees up any resources it is using
- EXIT_ON_CLOSE
- Exit the application using
System.exit(0)
- Use for applications only (not applets)
- Our
HelloWindow class would look like this:
import javax.swing.*;
public class HelloWindow4 extends JFrame {
public static void main(String[] args) {
new HelloWindow4();
}
public HelloWindow4() {
super("Hello Window Application");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JLabel msg = new JLabel("Hello GUI World");
getContentPane().add(msg);
setSize(300, 150);
setVisible(true);
}
}
Using the setDefaultCloseOperation method is the simplest way to handle closing a JFrame
- As long as we are satisfied with one of the four options
^ top
8.2.6: Adding a Button
- Button: a component the user clicks to trigger a specific action
- Basic buttons are created with class
JButton
- Generates
ActionEvents when user clicks the button
- Steps for using a button in a Swing program as follows:
- Create a
JButton object
- Add the
JButton to a container
- Create an
ActionListener object that has an actionPerformed method
- Register the listener for the
JButton object
1. Create a JButton Object
- Use a construct like the following:
JButton stopButton = new JButton("Exit");
JButton is a predefined Swing class for buttons
"Exit" is the label that will appear on the button
2. Add the JButton to a Container
- Use a construct like the following:
getContentPane().add(stopButton);
JButton will be added to the JRootPane container
3. Create an ActionListener
- Need to define a class that implements the
ActionListener interface:
- Can create an inner class like the WinHandler we made previously
public class ActHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
}
What other ways could we have chosen to implement the ActionListener?
4. Register the Listener
- Must register a button to get a response when the button is clicked
- Example of registering a listener for a button:
ActHandler act = new ActHandler();
stopButton.addActionListener(act);
All Together Now
Following code implements a button and two handlers
WinHandler takes care of a user pressing the "X" button
ActionHandler takes care of the user pressing the "Exit" button
import javax.swing.*;
import java.awt.event.*;
public class HelloWindow5 extends JFrame {
public static void main(String[] args) {
new HelloWindow5();
}
public HelloWindow5() {
super("Hello Window Application");
WinHandler handler = new WinHandler();
addWindowListener(handler);
JButton stopButton = new JButton("Exit");
getContentPane().add(stopButton);
ActHandler act = new ActHandler();
stopButton.addActionListener(act);
setSize(300, 150);
setVisible(true);
}
public class WinHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.out.println("WindowEvent received");
System.exit(0);
}
}
public class ActHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Exit")) {
System.out.println("ActionEvent received");
System.exit(0);
}
}
}
}
^ top
Exercise 8.2
Take two minutes to prepare answers to the following questions:
- What gets executed when an event occurs?
- Define what is meant by an inner class.
- Describe the purpose of an adapter class.
- What are the four steps for implementing a button?
^ top
8.3: Adding Multiple Components
Objectives
At the end of the lesson the student will be able to:
- Use Containers
- Use many components within a container
- Use Layout Managers to arrange the components
|
^ top
8.3.1: Container Classes
- Containers are classes that can have components added to them
- Every Swing container class has an
add method
- Used to add other components to the container
- Some commonly used container classes are:
JPanel
Container
- Content pane of a JFrame
JPanel Class
- Used for hierarchical organization of GUIs:
- A panel can contain other components
- A panel can be added to another container
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(stopButton);
buttonPanel.add(goButton);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
Note that the default layout manager of a JFrame is BorderLayout
Must include a location with the add method
Container Class
- Any descendant of the Container class can have components added to it
- Need to import the AWT library when using Container because it is not part of the Swing library:
import java.awt.*;
JComponent is derived from the Container class
Components in the container are arranged by the container’s layout manager
Content Pane of a JFrame
- JFrame is a window with title bar and a border
- Components are added to the content pane of a JFrame rather than directly to the JFrame
- The method
getContentPane returns a reference to the content pane, which is treated as type Container
Container contentPane = getContentPane();
JLabel label = new JLabel("blue");
contentPane.add(label);
Some JFrame Class Methods
JFrame(String title): constructor for creating a JFrame with a title
Container getContentPane(): returns the content pane of the JFrame
void setBackgroundColor(Color c)
void setForegroundColor(Color c)
void setSize(int width, int height)
void setVisible(boolean b)
void show(): sets visible and brings to front
setDefaultCloseOperation: sets operation that happens when user closes from
- DISPOSE_ON_CLOSE
- DO_NOTHING_ON_CLOSE
- EXIT_ON_CLOSE
- HIDE_ON_CLOSE
- More information: Class JFrame
^ top
8.3.2: Adding Components to Containers
- Procedure for adding components follows the same pattern as before:
- Construct the component so it appears visually
- Instantiate a specific component
- Add the component to the container object
- Provide an event handler for the component
- Write the code for the event handler
- Instantiate an object of the event handler
- Register the listener object
- Same procedure used for one or many components
- However, more consideration must be given to the placement of multiple components
- Placement is controlled using Layout Managers
^ top
8.3.3: Layout Managers
Layout Manager: an object that decides how components will be arranged in a container.
- Used because containers can change size
- Some types of layout managers:
- BorderLayout
- FlowLayout
- GridLayout
- Each type of layout manager has rules about how to rearrange components when the size or shape of the container changes.
Border Layout Manager
- Arranges components into five regions

content.setLayout(new BorderLayout());
. . .
content.add(label1, BorderLayout.NORTH);
CENTER region grows the most when the container grows
Also shrinks the most when the container shrinks
Further information: How to Use BorderLayout
Flow Layout Manager
- Simplest layout manager
- Displays components from left to right in the order they are added to the container
- Add method has one parameter which is the component to add
Container content = getContentPane();
content.setLayout(new FlowLayout());
JLabel label1 = new JLabel("First label here");
content.add(label1);
JLabel label2 = new JLabel("Second label there");
content.add(label2);
Further information: How to Use FlowLayout
Grid Layout Manager
- Divides container into grid of specified row and columns
- Specify a number of rows and columns
- All regions in the grid are equal size
- Components are added starting at top-left cell
- Proceeds left-to-right until row is full
- When the container changes size, each region grows or shrinks by the same amount
aContainer.setLayout(new GridLayout(2, 3));
. . .
aContainer.add(label1);
aContainer.add(label2);
Creates a grid layout with two rows and three columns
Further information: How to Use GridLayout
Other Layout Managers
^ top
8.3.4: Multiple Button Example
- Create a GUI with 3 buttons
- Follow the same procedure in constructing the GUI
- To resolve which button is pressed, we use method getSource
import java.awt.*; // for layout manager
import java.awt.event.*;
import javax.swing.*;
public class MultiButton extends JFrame
implements ActionListener {
private JButton msgButton;
private JButton clearButton;
private JButton exitButton;
public static void main(String[] args) {
new MultiButton();
}
public MultiButton() {
super("Hello Again");
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Create the buttons
msgButton = new JButton("Hello World");
clearButton = new JButton("Hello Again");
exitButton = new JButton("Exit");
// Set the layout manager
Container c = getContentPane();
c.setLayout(new FlowLayout());
// Add buttons to content pane
c.add(msgButton);
c.add(clearButton);
c.add(exitButton);
// Add event handlers
msgButton.addActionListener(this);
clearButton.addActionListener(this);
exitButton.addActionListener(this);
setSize(300, 150);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == msgButton) {
JOptionPane.showMessageDialog(null,
"Hello World",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
} else if (e.getSource() == clearButton) {
JOptionPane.showMessageDialog(null,
"Hello Again",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
} else if (e.getSource() == exitButton) {
System.exit(0);
}
}
}
^ top
Exercise 8.3
Take one minute to prepare answers to the following questions:
- How are components positioned with a BorderLayout manager?
- How are components positioned with a FlowLayout manager?
- How are components positioned with a GridLayout manager?
^ top
8.4: More Controls
Objectives
At the end of the lesson the student will be able to:
- Use check boxes
- Use radio buttons
|
^ top
8.4.1: About Controls
- Check boxes and radio buttons useful for allowing users to chose among predefined choices
- Check boxes have individual yes/no or true/false choices
- Radio buttons work as a group
^ top
8.4.2: Check Boxes
- Check boxes provide a simple yes/no or true/false option
- Provide a caption and user selects an answer
- One choice does not affect another choice
- Can compactly group a set of questions
- User can click on a check box to check or uncheck a box

Adding a Check Box Listener
- Often do not need a listener for a check box
- Can use the
isSelected method to see whether its checked
- When a listener is needed, use either
ActionListener or ItemListener interface
For Example
- Create an application to select available times
- Note that the event is not used to discover which button is selected
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyCheckBoxes extends JFrame
implements ActionListener, ItemListener
{
JCheckBox morning;
JCheckBox afternoon;
JCheckBox evening;
public static void main(String[] args) {
new MyCheckBoxes();
}
public MyCheckBoxes() {
super("Available Times");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
// Create the controls
morning = new JCheckBox("Mornings", true);
afternoon = new JCheckBox("Afternoons");
evening = new JCheckBox("Evenings");
//Add to content pane
c.add(morning);
c.add(afternoon);
c.add(evening);
// Add event handlers
morning.addActionListener(this);
afternoon.addItemListener(this);
evening.addActionListener(this);
setSize(300, 75);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
System.out.println("ActionEvent");
printChecks();
}
public void itemStateChanged(ItemEvent e) {
System.out.println("ItemEvent");
printChecks();
}
private void printChecks() {
if (morning.isSelected())
System.out.println("Mornings selected");
if (afternoon.isSelected())
System.out.println("Afternoons selected");
if (evening.isSelected())
System.out.println("Evenings selected\n");
}
}
Further Information
^ top
8.4.3: Radio Buttons
- Group of radio buttons allows selection of one item from a group
- Only one item can be selected at a time
- Radio buttons in a group operate together
- Selecting one immediately deselects all others
- Provide a caption and user selects an answer

- Must group set of radio buttons by adding them to a
ButtonGroup object
ButtonGroup b = new ButtonGroup();
b.add(morning);
b.add(afternoon);
b.add(evening);
Adding a Radio Button Listener
- Often do not need a listener for a radio button
- Can use the
isSelected method to see whether its checked
- When a listener is needed, use either
ActionListener or ItemListener interface
For Example
- Create an application to one of several preferred times
- Note that the event is not used to discover which button is selected
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyRadioButtons extends JFrame
implements ActionListener, ItemListener
{
JRadioButton morning;
JRadioButton afternoon;
JRadioButton evening;
public static void main(String[] args) {
new MyRadioButtons();
}
public MyRadioButtons() {
super("Preferred Time");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
// Create the controls
morning = new JRadioButton("Mornings", true);
afternoon = new JRadioButton("Afternoons");
evening = new JRadioButton("Evenings");
// Add to button group
ButtonGroup b = new ButtonGroup();
b.add(morning);
b.add(afternoon);
b.add(evening);
// Add radio buttons to content pane
c.add(morning);
c.add(afternoon);
c.add(evening);
// Add event handlers
morning.addActionListener(this);
afternoon.addItemListener(this);
evening.addActionListener(this);
setSize(300, 75);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
System.out.println("ActionEvent");
printChecks();
}
public void itemStateChanged(ItemEvent e) {
System.out.println("ItemEvent");
printChecks();
}
private void printChecks() {
if (morning.isSelected())
System.out.println("Mornings selected");
if (afternoon.isSelected())
System.out.println("Afternoons selected");
if (evening.isSelected())
System.out.println("Evenings selected");
System.out.println();
}
}
Further Information
^ top
Exercise 8.4
Determine whether the following should be presented in a GUI with check boxes or radio buttons:
- Choice of CD player on a new car order form
- Radio station buttons on a car radio
- Choices of courses you may be interested in taking:
- Advanced Java
- C# programming
- Computer Security
- Choice of monitors for a new computer system:
- 15-inch
- 17-inch
- 19-inch
- 21-inch
^ top
Wrap Up
^ top
Home
| WebCT
| Announcements
| Schedule
| Expectations
| Syllabus
Help
| FAQ's
| HowTo's
| Links
Last Updated: November 02 2003 @17:45:32
|