Chapter Six
GUI
GUI
Graphical User Interface ("Goo-ee")
Pictoral interface to a program
Distinctive "look" and "feel"
Different applications with consistent GUIs
improve productivity
Example:
Netscape Communicator
Menu bar, text field, label
GUIs built from components
Component: object with which user interacts
Examples: Labels, Text fields, Buttons,
Checkboxes
2
GUI
The graphical user interface allows us to
interact with our programs through mouse
movements, button clicks, key presses,
and so on.
Your Windows or Macintosh operating
system provides you with a GUI so you
don't have to remember all sorts of
instructions to type at the command line.
3
GUI
There are three basic things that are necessary
to develop a graphical user interface
The GUI components sets
form the interface
buttons, labels, check boxes, etc
Component arrangement
the scheme whereby the UI components are arranged to
create the interface
Response to user requests
the act of associating actions to user requests, known as
'events'
4
Implementing GUIs in Java
The Java Foundation Classes (JFC)
Encompass a group of features for
constructing graphical user interfaces (GUI).
encompassing the following APIs:
Abstract Window Toolkit (AWT): native GUI
components
Swing: lightweight GUI components
2D: rendering two-dimensional shapes, text, and
images
Accessibility: allowing compatibility with, for
example, screen readers and screen magnifiers
5
Abstract Window Toolkit
(AWT)
Provides basic UI components:
Buttons, lists, menus, textfields, etc
Event handling mechanism
Clipboard and data transfer
Image manipulation
Font manipulation
Graphics
Platform independence is achieved
through peers, or native GUI components
6
Using AWT Components
AWT is Javas original set of classes for building
GUIs
Uses peer components of the OS; heavyweight
Not truly portable: looks different and lays out
inconsistently on different OSs
Due to OSs underlying display management system
Every GUI component is a subclass of the AWT
Component class (except for menus)
Controls allow simple user input
Labels display text
Containers arrange other components
Use Canvases for custom components
Components and Containers
The AWT set is structured in a class
hierarchy
every UI component is a descendant of
the Component class
This contains the very basic functionality
common to all components
AWT Components
primitive
container
Peers and Platform Independence
Thus an AWT menu on the Solaris platform,
for example, actually creates a Motif menu
object as its peer
UI components that have peers are called
heavyweight because
they are rendered in their own (opaque) windows
and thus are expensive to use,
they must be rectangular and cannot have
transparent backgrounds, and
they are not amenable to being subclassed
10
Using Peers
Java
Program
Java
AWT
Native
Window
System
Peers
A Java program creates and displays an
AWT component,
which creates and displays a native
component, or peer.
By using peers
Platform controls component appearance
Inconsistencies in implementations
11
Lightweight Components
AWT 1.1 introduced the notion of lightweight
components which:
are contained within a heavyweight component's window
do not have peers
are rendered in their container's window rather than one
of their own
do not incur performance penalties and can have
transparent backgrounds
Almost all Swing components are lightweight ones
that extend either
java.awt.Component or java.awt.Container
12
What is Swing?
is Java's graphical user interface library
Abstract Window Toolkit (AWT) V2
100% Pure Java
Requires JDK 1.1.2 or higher
Part of JFC
Components
New high-level components
Pluggable Look & Feel
You MUST import the following packages:
import java.awt.*;
import javax.swing.*;
13
Swing Philosophy
Richer Component Set
Replaces AWT Component Set
Adds more complex components
Swing Components Java-Based
If problems, same problems everywhere
14
The Swing Containment Hierarchy
typically has at least:
a top-level container: the root container that
holds everything together. e.g. JApplet,
JFrame, Window
an intermediate container: a container to
simplify the positioning of atomic components.
e.g. JPanel, JScrollPane
an atomic component: a self-sufficient
component not holding other components. eg.
JButton, JLabel
15
Components and Containers
a Container is a special type of component
you can add other components. Example,
JFrame, JApplet, JPanel etc
All containers have methods to add and
remove components
16
GUI Class Hierarchy (Swing)
Dimension
Font
Classes in the java.awt
package
LayoutManager
1
Heavyweight
FontMetrics
Object
Color
Panel
Applet
JApplet
Window
Frame
JFrame
Dialog
JDialog
Graphics
Component
Container
Swing Components
in the javax.swing package
JComponent
Lightweight
17
Description of Classes
Object: All classes ultimately derive from Object,
thus this class is at the top of the tree.
Component: represents an object that has a
visual representation that can be shown onscreen and that can interact with users. This class
defines some basic methods that are available to
all Swing classes.
18
Description of Classes
(Contd)
Container: builds on the basic visual capabilities
of the Component class by adding the ability to
hold other containers.
Window: a specialized type of container object
that has a border, a title bar, buttons that
minimize, maximize, and close the window, and
that can be repositioned and possibly even
resized by the user.
19
Description of Classes
(Contd)
Frame: a type of Window that serves as the basis
for Java GUI applications. Frame is an AWT class
that has been improved upon by the JFrame
class.
JFrame: the Swing version of the older Frame
class. Most of the Swing applications include at
least one JFrame object.
JComponent: is the basis for all other Swing
components except for frames.
20
Description of Classes
(Contd)
JPanel: used to organize and control the
layout of other components such as labels,
buttons, text fields, etc. In most Swing
applications, one or more panels are added
to a frame. Then, when the frame is
displayed, the components that were added
to its panels are made visible.
JLabel: creates a label that displays a simple
text value.
21
AWT vs. Swing
Swing does not replace the AWT; it is built on
top of it
All 1.0 AWT components are heavyweight;
corresponding Swing components are
lightweight
Swing component names begin with ``J'':
Component (AWT) vs. JComponent (Swing)
Button (AWT) vs. JButton (Swing)
Always use Swing components; however,
since Swing is built on top of AWT, you will
need to know some AWT methods
22
Transitioning from AWT
For most components, add J before
name
Button JButton, Applet JApplet,
Work from Components out to
Containers
Adding to top-level containers different /
delegate
23
Frames
Frame is a window that is not contained
inside another window. Frame is the basis
to contain other user interface components
in Java GUI applications.
The JFrame class can be used to create
windows.
For Swing GUI programs, use JFrame class
to create widows.
24
JFrame
JFrame is the application window class
It is special; it draws the window and
interacts with the operating system
When a JFrame is created, an inner
container called the contentPane is
automatically created
We don't draw graphics directly on
JFrame; we draw on the contentPane
25
Anatomy of a JFrame
title bar
minimize
maximize
close
The contentPane holds your
content; created automatically
when a JFrame is created
26
Example: Empty Frame
package swinglab;
import java.awt.*;
import javax.swing.*;
// extends keyword makes Calc a JFrame
public class Calc extends JFrame{
public Calc() {
// get the contentPane and assign it to cp
Container cp = getContentPane();
// exit program when user closes the window
setDefaultCloseOperation(EXIT_ON_CLOSE);
// sets the layout; will be covered in later slide
cp.setLayout(new FlowLayout());
// sets title to "My Funky Calculator"
setTitle("My Funky Calculator");
setSize(1000,700); // Frame has 0 default size
27
}
Example continued
. . .
public static void main (String[] args){
Calc trial = new Calc();
// Frame is invisible by default
trial.setVisible(true);
// main method exits but user interface
// stays alive
}
}
28
Using the JPanel Class
A panel is a type of container that's designed to hold
a group of components so they can be displayed on
a frame. The normal way to display a group of
controls such as text fields, labels, buttons, and other
GUI widgets is to add those controls to a panel, and
then add the panel to the frame.
You can bypass the panel and add the controls
directly to the frame if you want, but using a separate
panel to hold the frames control is almost always a
good idea.
29
Useful JPanel Constructors
and Methods
Constructor
JPanel ()
JPanel
(LayoutManager
layout)
Description
Creates a new panel.
Creates a new panel with
the specified layout
manager. The default
layout manager is
FIowLayout
30
Useful JPanel Constructors
and Methods (Contd)
Method
void add (Component c)
Description
Adds the specified
component to the
panel.
void remove (Component
c)
Removes the specified
component from the
panel.
void setLayout
(LayoutManager layout)
Sets the layout manager used to
control how components are
arranged when the panel is
displayed. The default is the
31
FIowLayout manager
Useful JPanel Constructors and
Methods (Contd)
Method
void setLocation (int
x, int y)
void setSize (int
width, int height)
void setToolTipText
(String text)
Description
Sets the x and y position
of the frame-screen. The
top-left corner of the
screen is 0, 0.
Sets the size of the frame to
the specified width and
height.
Sets the tooltip text that's
displayed if the user rests
the mouse over an empty
part of the panel.
32
Example:
package swinglab;
import java.awt.*;
import javax.swing.*;
public class Calc extends JFrame{
private JPanel entryPanel;
private JPanel answerPanel;
public Calc() {
Container cp = getContentPane();
setDefaultCloseOperation(EXIT_ON_CLOSE);
cp.setBackground(Color.white);
setTitle("My Funky Calculator");
setSize(1000,700);
entryPanel = new JPanel();
entryPanel.setBackground(Color.orange);
answerPanel = new JPanel();
answerPanel.setBackground(Color.yellow);
// . . .
33
Example:
cp.add(entryPanel);
cp.add(answerPanel);
}
public static void main (String[] args){
Calc trial = new Calc();
trial.setVisible(true);
}
}
34
Colors
There are 13 predefined colors
You can access them using Color.x where
x is
orange, pink, cyan, magenta, yellow, black, blue,
white, gray, lightGray, darkGray, red, green
You can define your own colors
Color ugly = new Color(30,90,120);
//RGB(red-green-blue); values between 0-255;
35
Frames, Panes and Panels
36
JComponents
JComponent: The base class for all Swing components
except top-level containers
JComponents do not extend their AWT counterparts:
For example, the JButton class is not a subclass (direct or
indirect) of Button
Note that JComponents are containers
However, some Swing components are not
JComponents
For example, some Swing containers are direct subclasses of
their AWT counterparts
Its subclasses present information or interact with the
user
Examples:labels(JLabels), buttons(JButtons),
textfields(JTextField)
- Containers are some JComponents that are designed to hold
other components (no interaction with the user)
- Examples: JPanel, JScrollPane
37
Using Labels
A label is a component that simply displays
text. Labels are used for a variety of
purposes: to display captions for other
controls such as text fields or combo boxes,
to display informational messages, or to
show the results of a calculation or a
database lookup.
38
Using Labels
A label can also display an image, or it can
display both an image and some text. And
you have complete control over the
appearance of the text.
You can specify the font, size, whether the
text is bold, italic, or underlined, what color
the text is displayed as, and so on.
39
Useful JLabels Constructors and
Methods
Constructor
JLabel ( )
Method
String getText ( )
void setText (String
text)
void setToolTipText
(String text)
Description
Creates a new label with no
initial text.
Description
Returns the text displayed
by the label.
Sets the text displayed by
the label.
Sets the tooltip text that's
displayed if the user rests
the mouse over the label
40
for a few moments
Swing Example
import java.awt.*;
import javax.swing.*;
public class MyTest extends JFrame {
JLabel myLabel = new JLabel("Hello, World!");
public MyTest() {
super("MyTest");
setSize(350, 100);
getContentPane().add(myLabel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main (String args[]) {
MyTest m = new MyTest();
}
}
41
Simple Swing Application
42
Creating Buttons
Next to labels, the Swing component used
most is the JButton component which
creates a button the user can click.
The constructors of the JButton class are
similar to the constructors for the JLabel
class. You can either create an empty
button or a button with text.
43
Useful JButton Constructors
and Methods
Constructor
JButton ( )
JButton (String text)
String getText ()
Description
Creates a new button
with no initial text.
Creates a new button
with the specified text.
Returns the text
displayed by the
button.
44
Useful JButton Constructors and
Methods (Contd)
Method
Description
void
setRolloverEnabled
(boolean value)
Enables or disables the
rollover effect, which
causes the border to get
thicker when the mouse
moves over the button.
The default setting is true
(rollover effect enabled).
void setEnabled
(boolean value)
Enables or disables the
button. The default setting is
45
true (enabled).
Useful JButton Constructors
and Methods (Contd)
Method
void setText
(String text)
Description
Sets the text displayed by the
button.
void setToolTipText Sets the tooltip text that's
(String text)
displayed if the user lets the
mouse rest over the button.
void setVisible
(boolean value)
Shows or hides the button.
The default setting is true (the
button is visible).
46
JTextField - JPassWordField
They are single-line areas in which text can be
entered by the user from the keyboard or text can
simply be displayed
Constructors
JTextField(int columns)
Creates an empty text field with the specified number of
columns.
JTextField(String text)
Creates a text field initialized with the specified text.
JTextField(String text, int columns)
Creates a text field initialized with the specified text and the
column size.
JTextField (String, int maximumNumberCharaters)
47
Methods
int getColomns(int col);
void setColoumns(int col);
getText()
Returns the string from the text field.
setText(String text)
Puts the given string in the text field.
setEditable(boolean editable)
Enables or disables the text field to be edited. By default,
editable is true.
setColumns(int)
Sets the number of columns in this text field. The length of
the text field is changeable.
48
When the user types data into them and presses
the Enter key, an action event occurs. If the
program registers an event listener, the listener
processes the event and can use the data in the
text field at the time of the event in the program
JTextField textField1 = new JTextField("This is the
initial text");
JTextField textField2 = new JTextField("Initial text",
columns);
textField.setText(hi);
49
JPasswordField class extends JTextField class
Methods
Char[ ] getPassword();
//To obtain the password
JTextArea: a component used to accept multiple
line text.
Constructors
JTextArea( )
Default constructor - Create an empty text area
JTextArea(int rows, int columns)
Creates a text area with the specified number of
rows and columns.
JTextArea(String s, int rows, int columns)
Creates a text area with the initial text and
the number of rows and columns specified.
50
Other JComponents
JComboBox
drop-down list of items from which the user can
makes selection by clicking an item or possibly
by typing into the box
Constructor
JComboBox(String str[]);
Methods
getSelectedItem();//returns the selected item
getSelectedIndex();
setMaximumRowCount(int n) - maximum of n items
will be displayed if there are more items adds
scrollbar.
51
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class Calc extends JFrame{
private
private
private
private
private
private
private
private
private
static
static
static
static
JLabel letLabel;
JLabel answerLabel;
JTextField num1;
JTextField num2;
JComboBox operation;
JButton calculate;
JButton quit;
JPanel entryPanel;
JPanel answerPanel;
final
final
final
final
String
String
String
String
ADD_OP
SUB_OP
MUL_OP
DIV_OP
=
=
=
=
"ADDITION";
"SUBTRACTION";
"MULTIPLICATION";
"DIVISION";
52
private static final int XSIZE = 1000;
private static final int YSIZE = 700;
public Calc() {
Container cp = getContentPane();
setDefaultCloseOperation(EXIT_ON_CLOSE);
cp.setLayout(new FlowLayout());
cp.setBackground(Color.WHITE);
setTitle("My Funky Calculator");
setSize(XSIZE,YSIZE);
entryPanel = new JPanel();
entryPanel.setBackground(Color.ORANGE);
answerPanel = new JPanel();
answerPanel.setBackground(Color.YELLOW);
letLabel = new JLabel("Let's Calculate!");
entryPanel.add(letLabel);
letLabel.setForeground(Color.GREEN);
53
num1 = new JTextField("1st Number", 10);
entryPanel.add(num1);
num1.setBackground(Color. LIGHT_GRAY);
num2= new JTextField("2nd Number", 10);
entryPanel.add(num2);
num2.setBackground(Color.LIGHT_GRAY);
operation = new JComboBox();
operation.addItem(ADD_OP);
operation.addItem(SUB_OP);
operation.addItem(MUL_OP);
operation.addItem(DIV_OP);
entryPanel.add(operation);
operation.setBackground(Color.BLUE);
answerLabel = new JLabel("Answer");
54
entryPanel.add(answerLabel);
answerLabel.setForeground(Color.red);
calculate = new JButton("Calculate");
calculate.setBackground(Color.pink);
answerPanel.add(calculate);
quit = new JButton("Quit");
answerPanel.add(quit);
Color quitter = new Color(50,100,50);
quit.setBackground(quitter);
cp.add(entryPanel);
cp.add(answerPanel);
}
public static void main(String[] args){
Calc trial = new Calc();
trial.setVisible(true);
}
}
55
56
Layout Managers
Associated with containers
Automate the layout of elements
When elements are added to the container
When the window is resized
automatically adjust the positions and sizes of the elements.
Layout managers control:
Where components appear
What sizes they are
How they react when they are resized
57
Hierarchy of Layout Managers
58
BorderLayout
It uses five areas to hold components:
north, south, east, west, and center.
All extra space is placed in the center
area.
59
FlowLayout
It simply lays out components from left to
right, starting new rows if necessary
60
CardLayout
Use the CardLayout class when you have
an area that can contain different
components at different times
61
GridLayout
GridLayouts simply make a bunch of
Components have equal size, displaying
them in the requested number of rows and
columns
62
Using Layout Managers
BorderLayout
<nameofcontainer>.setLayout(new BorderLayout());
When adding components to the container:
<nameofcontainer>.add(<nameofcomponent>,
BorderLayout.REGION);
where REGION is either NORTH, SOUTH, WEST,
CENTER OR EAST.
JPanel panel = new JPanel(); // default
// FlowLayout
panel.setLayout(new BorderLayout());
panel.add(button,BorderLayout.NORTH);
63
Using Layout Managers
FlowLayout
<nameofcontainer>.setLayout(new FlowLayout());
When adding components to the container:
<nameofcontainer>.add(<nameofcomponent>);
JPanel panel = new JPanel(); // default
// FlowLayout
//following line is redundant
panel.setLayout(new FlowLayout());
panel.add(button);
64