Chapter 7 - A First Look at GUI Applications
Chapter 7 - A First Look at GUI Applications
Applications
Chapter 7
Introduction
Many Java applications use a graphical user
interface or GUI (pronounced “gooey”).
A GUI is a graphical window or windows that
provide interaction with the user.
GUI’s accept input from:
◦ the keyboard
◦ a mouse.
A window in a GUI consists of components that:
◦ present data to the user
◦ allow interaction with the application.
7-2
Introduction
Some common GUI components are:
◦ buttons, labels, text fields, check boxes, radio buttons,
combo boxes, and sliders.
7-3
JFC, AWT, Swing
Java programmers use the Java Foundation
Classes (JFC) to create GUI applications.
The JFC consists of several sets of classes,
many of which are beyond the scope of this
book.
The two sets of JFC classes that we focus on are
AWT and Swing classes.
Java is equipped with a set of classes for
drawing graphics and creating graphical user
interfaces.
These classes are part of the Abstract
Windowing Toolkit (AWT).
7-4
JFC, AWT, Swing
The AWT allows creation of applications and
applets with GUI components.
The AWT does not actually draw user interface
components on the screen.
The AWT communicates with a layer of
software, peer classes.
Each version of Java for a particular operating
system has its own set of peer classes.
7-5
JFC, AWT, Swing
Java programs using the AWT:
◦ look consistent with other applications on the same
system.
◦ can offer only components that are common to all the
operating systems that support Java.
The behavior of components across various
operating systems can differ.
Programmers cannot easily extend the AWT
components.
AWT components are commonly called
heavyweight components.
7-6
JFC, AWT, Swing
Swing was introduced with the release of Java 2.
Swing is a library of classes that provide an improved
alternative for creating GUI applications and applets.
Very few Swing classes rely on peer classes, so they are
referred to as lightweight components.
Swing draws most of its own components.
Swing components have a consistent look and
predictable behavior on any operating system.
Swing components can be easily extended.
7-7
Event Driven Programming
Programs that operate in a GUI environment
must be event-driven.
An event is an action that takes place within a
program, such as the clicking of a button.
Part of writing a GUI application is creating
event listeners.
An event listener is an object that automatically
executes one of its methods when a specific
event occurs.
7-8
javax.swing and java.awt
In an application that uses Swing classes, it is necessary to
use the following statement:
import javax.swing.*;
◦ Note the letter x that appears after the word java.
Some of the AWT classes are used to determine when
events, such as the clicking of a mouse, take place in
applications.
In an application that uses an AWT class, it is necessary to
use the following statement.
import java.awt.*;
Note that there is no x after java in this package
name.
7-9
Creating Windows
Often, applications need one or more
windows with various components.
A window is a container, which is simply
a component that holds other components.
A container that can be displayed as a
window is a frame.
In a Swing application, you create a frame
from the JFrame class.
7-
10
Creating Windows
A frame is a basic window that has:
◦ a border around it,
◦ a title bar, and
◦ a set of buttons for:
minimizing,
maximizing, and
closing the window.
These standard features are sometimes
referred to as window decorations.
7-11
Creating Windows
7-
12
Creating Windows
The following import statement is needed to use the
swing components:
import javax.swing.*;
7-
13
Creating Windows
Aninstance of the JFrame class needs to be created:
JFrame window = new JFrame();
This statement:
◦ creates a JFrame object in memory and
◦ assigns its address to the window variable.
7-
14
Creating Windows
To set the size of the window:
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
To specify the action to take place when the user clicks on the
close button.
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
7-
15
Creating Windows
The following code displays the window:
window.setVisible(true);
7-
16
import javax.swing.*; // Needed for Swing classes
// Create a window.
JFrame window = new JFrame();
7-
18
import javax.swing.*; // Needed for Swing classes
public SimpleWindow()
{
final int WINDOW_WIDTH = 350; // Window width in pixels
final int WINDOW_HEIGHT = 250; // Window height in pixels
Label
Button
7-
22
Components that are displayed in this
window must be added to the JFrame
object’s content pane.
public KiloConverter()
{
setTitle("Kilometer Converter");
setSize(500,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
7-
27
Handling Action Events
An event listener is an object that responds to
events.
The source component fires an event which is
passed to a method in the event listener.
Event listener classes are specific to each
application.
Event listener classes are commonly written as
private inner classes in an application.
7-
28
Writing Event Listener Classes as Private
Inner Classes
A class that is defined inside of another class is
known as an inner class
7-
29
Event Listeners Must Implement an
Interface
All event listener classes must implement an
interface.
7-
30
Handling Action Events
JButton components generate action events, which require
an action listener class.
calcButton.addActionListener(
new CalcButtonListener());
7-
33
import javax.swing.*;
import java.awt.event.*;
public KiloConverterWindow()
{
setTitle("Kilometer Converter");
setSize(500,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
When the user clicks the “Calculate” button, the buttonListener object’s
actionPerformed method will be executed.
7-
37
Color Constants
There are predefined constants that you can use for
colors.
Color.BLACK Color.BLUE
Color.CYAN Color.DARK_GRAY
Color.GRAY Color.GREEN
Color.LIGHT_GRAY Color.MAGENTA
Color.ORANGE Color.PINK
Color.RED Color.WHITE
Color.YELLOW
7-
38
The ActionEvent Object
Event objects contain certain information about
the event.
This information can be obtained by calling one of
the event object’s methods.
Two of these methods are:
◦ getSource - returns a reference to the object that
generated this event.
◦ getActionCommand - returns the action command
for this event as a String.
Example:
◦ EventObjectWindow.java, EventObjectDemo.java
7-
39
We create and register 3 separate instances
of the action listener class with the 3 buttons.
if (actionCommand.equals("Button 1"))
{
JOptionPane.showMessageDialog(null, "You clicked the first button.");
}
else if (actionCommand.equals("Button 2"))
{
JOptionPane.showMessageDialog(null, "You clicked the second button.");
}
else if (e.getSource() == button3)
{
JOptionPane.showMessageDialog(null, "You clicked the third button.");
}
Returns a reference to
}
the component that is
}
the source of the
event.
Equipping GUI Classes with a main
Method
Java applications always starts execution with a
method named main.
We have seen applications in two separate files,
one file for the class that defines the GUI
window and one file that contains the main
method that creates an object of the GUI
window class.
Applications can also be written with the main
method directly written into the GUI class.
See example: EmbeddedMain.java
7-
42
Layout Managers
An important part of designing a GUI application is
determining the layout of the components.
The term layout refers to the positioning and sizing
of components.
In Java, you do not normally specify the exact
location of a component within a window.
A layout manager is an object that:
◦ controls the positions and sizes of components, and
◦ makes adjustments when necessary.
7-
43
Layout Managers
The layout manager object and the container work
together.
Java provides several layout managers:
◦ FlowLayout - Arranges components in rows. This is the
default for panels.
◦ BorderLayout - Arranges components in five regions:
North, South, East, West, and Center.
This is the default layout manager for a JFrame object’s content
pane.
◦ GridLayout - Arranges components in a grid with rows
and columns.
7-
44
Layout Managers
The Container class is one of the base classes that many
components are derived from.
Any component that is derived from the Container class
can have a layout manager added to it.
You add a layout manager to a container by calling the
setLayout method.
7-
45
FlowLayout Manager
FlowLayout is the default layout manager for
JPanel objects.
Components appear horizontally, from left to
right, in the order that they were added. When
there is no more room in a row, the next
components “flow” to the next row.
See example: FlowWindow.java
7-
46
public FlowWindow()
{
setTitle("Flow Layout");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(button2);
add(button3);
setVisible(true);
}
FlowLayout Manager
The FlowLayout manager allows you to align components:
◦ in the center of each row
◦ along the left or right edges of each row.
An overloaded constructor allows you to pass:
◦ FlowLayout.CENTER,
◦ FlowLayout.LEFT, or
◦ FlowLayout.RIGHT.
Example:
setLayout(new FlowLayout(FlowLayout.LEFT));
7-
48
Example of left aligned FlowLayout manager
FlowLayout(int alignment,
int horizontalGap,
int verticalGap)
Example:
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 7));
7-
50
BorderLayout Manager
BorderLayout manages five regions where
components can be placed.
7-
51
BorderLayout Manager
A component placed into a container that is
managed by a BorderLayout must be placed
into one of five regions:
◦ BorderLayout.NORTH
◦ BorderLayout.SOUTH
◦ BorderLayout.EAST
◦ BorderLayout.WEST
◦ BorderLayout.CENTER
7-
52
BorderLayout Manager
Each region can hold only one component at a time.
When a component is added to a region, it is stretched
so it fills up the entire region.
BorderLayout is the default manager for JFrame
objects.
add(button, BorderLayout.NORTH);
7-
53
BorderLayout Manager
Normally the size of a button is just large
enough to accommodate the text that it displays
The buttons displayed in BorderLayout
region will not retain their normal size.
The components are stretched to fill all of the
space in their regions.
7-
54
BorderLayout Manager
Ifthe user resizes the window, the sizes of the
components will be changed as well.
BorderLayout manager resizes components:
◦ placed in the north or south regions may be resized
horizontally so it fills up the entire region,
◦ placed in the east or west regions may be resized
vertically so it fills up the entire region.
◦ A component that is placed in the center region may
be resized both horizontally and vertically so it fills
up the entire region.
7-
55
// Add a BorderLayout manager to the content pane.
setLayout(new BorderLayout());
Exampl
e
BorderLayout Manager
By default there is no gap between the regions.
An overloaded BorderLayout constructor
allows horizontal and vertical gaps to be
specified (in pixels).
The constructor has the following format
Example:
setLayout(new BorderLayout(5,10));
7-
57
// Add a BorderLayout manager to the content pane.
setLayout(new BorderLayout(5, 10));
Exampl
e
Nesting Components in a Layout
Adding components to panels and then nesting
the panels inside the regions can overcome the
single component limitation of layout regions.
By adding buttons to a JPanel and then
adding the JPanel object to a region,
sophisticated layouts can be achieved.
7-
59
public class BorderPanelWindow extends JFrame
{
public BorderPanelWindow()
{
setTitle("Border Layout");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.SOUTH); Add the panels to
add(panel3, BorderLayout.EAST); the content pane
add(panel4, BorderLayout.WEST);
add(panel5, BorderLayout.CENTER);
Exampl
e
GridLayout Manager
GridLayout creates a grid with rows and columns, much
like a spreadsheet. A container that is managed by a
GridLayout object is divided into equally sized cells.
columns
5 columns and 5
rows. 25 cells
rows
7-
62
GridLayout Manager
GridLayout manager follows some simple
rules:
◦ Each cell can hold only one component.
◦ All of the cells are the size of the largest component
placed within the layout.
◦ A component that is placed in a cell is automatically
resized to fill up any extra space.
You pass the number of rows and columns as
arguments to the GridLayout constructor.
7-
63
GridLayout Manager
The general format of the constructor:
GridLayout(int rows, int columns)
Example
setLayout(new GridLayout(2, 3));
A zero(0) can be passed for one of the
arguments but not both.
◦ passing 0 for both arguments will cause an
IllegalArgumentException to be
thrown.
7-
64
GridLayout Manager
Components are added to a GridLayout in
the following order (for a 5×5 grid):
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
7-
65
public GridWindow()
{
// Set the title bar text.
setTitle("Grid Layout");
Exampl
e
GridLayout also accepts nested components:
public GridPanelWindow()
{
setTitle("Grid Layout");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2, 3));
Exampl
e
Radio Buttons
7-
71
Radio Buttons
Radio buttons allow the user to select one choice
from several possible options.
The JRadioButton class is used to create radio
buttons. Button appears
JRadioButton constructors: already selected
when true
◦ JRadioButton(String text)
◦ JRadioButton(String text, boolean selected)
Example:
JRadioButton radio1 = new JRadioButton("Choice 1");
or
JRadioButton radio1 = new JRadioButton(
"Choice 1", true);
7-
72
Button Groups
Radio buttons normally are grouped together.
In a radio button group only one of the radio
buttons in the group may be selected at any
time.
Clicking on a radio button selects it and
automatically deselects any other radio button in
the same group.
An instance of the ButtonGroup class is
used to group radio buttons
7-
73
Button Groups
The ButtonGroup object creates the mutually
exclusive relationship between the radio buttons
that it contains.
7-
74
Button Groups
ButtonGroup objects are not containers like
JPanel objects, or content frames.
If you wish to add the radio buttons to a panel or
a content frame, you must add them
individually.
panel.add(radio1);
panel.add(radio2);
panel.add(radio3);
7-
75
Radio Button Events
JRadioButton objects generate an action
event when they are clicked.
To respond to an action event, you must write an
action listener class, just like a JButton event
handler.
See example: MetricConverterWindow.java
7-
76
public class MetricConverterWindow extends JFrame
{
private JPanel panel; // A holding panel
private JLabel messageLabel; // A message to the user
private JTextField kiloTextField; // To hold user input
private JRadioButton milesButton; // To convert to miles
private JRadioButton feetButton; // To convert to feet
private JRadioButton inchesButton; // To convert to inches
private ButtonGroup radioButtonGroup; // To group radio buttons
private final int WINDOW_WIDTH = 400; // Window width
private final int WINDOW_HEIGHT = 100; // Window height
Exampl
e public MetricConverterWindow()
{
setTitle("Metric Converter");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel()
{
messageLabel = new JLabel("Enter a distance in kilometers");
kiloTextField = new JTextField(10);
milesButton = new JRadioButton("Convert to miles");
feetButton = new JRadioButton("Convert to feet");
inchesButton = new JRadioButton("Convert to inches");
if (e.getSource() == milesButton)
{
convertTo = " miles.";
result = Double.parseDouble(input) * 0.6214;
}
Exampl else if (e.getSource() == feetButton)
e {
convertTo = " feet.";
result = Double.parseDouble(input) * 3281.0;
}
else if (e.getSource() == inchesButton)
{
convertTo = " inches.";
result = Double.parseDouble(input) * 39370.0;
}
JOptionPane.showMessageDialog(null, input +
" kilometers is " + result + convertTo);
}
}
Determining Selected Radio Buttons
The JRadioButton class’s isSelected
method returns a boolean value indicating if
the radio button is selected.
if (radio.isSelected())
{
// Code here executes if the radio
// button is selected.
}
7-
80
Selecting a Radio Button in Code
Itis also possible to select a radio button in code
with the JRadioButton class’s doClick
method.
When the method is called, the radio button is
selected just as if the user had clicked on it.
As a result, an action event is generated.
radio.doClick();
Exampl
e Open RadioSelect in Netbeans
7-
81
Check Boxes
7-
82
Check Boxes
A check box appears as a small box with a label
appearing next to it.
Like radio buttons, check boxes may be selected
or deselected at run time.
When a check box is selected, a small check
mark appears inside the box.
Check boxes are often displayed in groups but
they are not usually grouped in a
ButtonGroup.
7-
83
Check Boxes
The user is allowed to select any or all of the
check boxes that are displayed in a group.
The JCheckBox class is used to create check
Check appears in
boxes. box if true
Two JCheckBox constructors:
JCheckBox(String text)
JCheckBox(String text, boolean selected)
Example:
JCheckBox check1 = new JCheckBox("Macaroni");
or
JCheckBox check1 = new JCheckBox("Macaroni",
true);
7-
84
Check Box Events
When a JCheckBox object is selected or
deselected, it generates an item event.
Handling item events is similar to handling
action events.
Write an item listener class, which must meet
the following requirements:
◦ It must implement the ItemListener interface.
◦ It must have a method named
itemStateChanged.
This method must take an argument of the ItemEvent type.
7-
85
Check Box Events
Create an object of the class
Register the item listener object with the
JCheckBox component.
On an event, the itemStateChanged
method of the item listener object is
automatically run
◦ The event object is passed in as an argument.
7-
86
Determining Selected Check Boxes
The isSelected method will determine
whether a JCheckBox component is selected.
The method returns a boolean value.
if (checkBox.isSelected())
{
// Code here executes if the check
// box is selected.
}
7-
87
public class ColorCheckBoxWindow extends JFrame
{
private JLabel messageLabel; // A message to the user
private JCheckBox yellowCheckBox; // To select yellow background
private JCheckBox redCheckBox; // To select red foreground
Exampl private final int WINDOW_WIDTH = 300; // Window width
e
private final int WINDOW_HEIGHT = 100; // Window height
public ColorCheckBoxWindow()
{
setTitle("Color Check Boxes");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(messageLabel);
add(yellowCheckBox);
add(redCheckBox);
setVisible(true);
}
private class CheckBoxListener implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
if (e.getSource() == yellowCheckBox)
{
if (yellowCheckBox.isSelected())
{
getContentPane().setBackground(Color.yellow);
Exampl yellowCheckBox.setBackground(Color.yellow);
e redCheckBox.setBackground(Color.yellow);
}
else
{
getContentPane().setBackground(Color.lightGray);
yellowCheckBox.setBackground(Color.lightGray);
redCheckBox.setBackground(Color.lightGray);
}
}
else if (e.getSource() == redCheckBox)
{
if (redCheckBox.isSelected())
{
messageLabel.setForeground(Color.red);
yellowCheckBox.setForeground(Color.red);
redCheckBox.setForeground(Color.red);
Exampl }
e else
{
messageLabel.setForeground(Color.black);
yellowCheckBox.setForeground(Color.black);
redCheckBox.setForeground(Color.black);
}
}
}
}
Selecting Check Boxes in Code
Itis possible to select check boxes in code with
the JCheckBox class’s doClick method.
When the method is called, the check box is
selected just as if the user had clicked on it.
As a result, an item event is generated.
checkBox.doClick();
7-
92
Borders
Windows have a more organized look if related
components are grouped inside borders.
7-
93
Borders
The setBorder method is used to add a
border to the component.
The setBorder method accepts a Border
object as its argument.
A Border object contains detailed information
describing the appearance of a border.
The BorderFactory class, which is part of
the javax.swing package, has static methods
that return various types of borders.
You use the BorderFactory class to create
Border objects for you.
7-
94
Border BorderFactory Method Description
A border that has two parts: an inside edge
Compound createCompoundBorder and an outside edge. The inside and outside
border
edges can be any of the other borders.
Empty border createEmptyBorder A border that contains only empty space.
A border with a 3D appearance that looks
Etched border createEtchedBorder
“etched” into the background.
Line border createLineBorder A border that appears as a line.
A border that looks like beveled edges. It has
Lowered createLoweredBevelBorder
a 3D appearance that gives the illusion of
bevel border being sunken into the surrounding
background.
A line border that can have edges of different
Matte border createMatteBorder
thicknesses.
A border that looks like beveled edges. It has
Raised bevel createRaisedBevelBorder
a 3D appearance that gives the illusion of
border being raised above the surrounding
background.
Titled border createTitledBorder An etched border with a title.
7-
96
The Brandi’s Bagel House Application
ToppingPanel Class
GreetingPanel Class
BagelPanel Class
CoffeePanel Class
Open Bagel in Netbeans
Splash Screens
A splash screen is a graphic image that is
displayed while an application loads into
memory and starts up.
A splash screen keeps the user's attention
while a large application loads and
executes.
Beginning with Java 6, you can display
splash screens with your Java
applications.
7-
99
Splash Screens
To display the splash screen you use the java
command in the following way when you run the
application:
7-
100
Using Console Output to Debug a GUI