Computer Science 2
Java GUI Programming
Slides courtesy of Sean P. Strout
(
[email protected])
04/14/15
What is a GUI?
Java has standard packages for creating
custom Graphical User Interfaces
Some of the fundamental GUI components:
Button
Label
Text Field
Check Radio Buttons
Box
Combo
Box
/usr/local/pub/sps/courses/cs2/gui/ShowComponents/
04/14/15
What is AWT?
The Abstract Window Toolkit was a part of
Java from the beginning
import java.awt.*;
All AWT components must be mapped to
platform specific components using peers
The look and feel of these components is tied
to the native components of the window manager
AWT components are considered to be very
error prone and should not be used in
modern Java applications
04/14/15
What is AWT?
The same application using only AWT
components, running on X-Windows:
/usr/local/pub/sps/courses/cs2/gui/AWTComponents
04/14/15
What is Swing?
With the release of Java 2, the AWT user
interface components were replaced with
Swing
Swing is built on top of AWT to give a
more flexible, robust library
Lightweight components dont rely on the native
GUI
Heavyweight components do depend on the target
platform because they extend AWT components
Swing components are directly painted onto
the canvas using Java code
04/14/15
Java GUI API
AWT: java.awt
Dimensio
n
Font
Objec
t
FontMetri
cs
Colo
r
Graphics
Component
Heavyweight
LayoutManage
r
Pane
l
Contain
er
Window
Apple
t
JApple
t
Frame
JFrame
Dialo
g
JDial
og
JComponen
t
Swing: javax.swing
Lightweight
04/14/15
Java GUI API
AbstractBut
ton
JComponen
t
JTextCompone
nt
JMenuItem
JCheckBoxMenuIt
em
JButton
JMenu
JToggleButt
on
JRadioButtonMenuI
tem
JEditorPa
ne
JCheckBox
JTextFi
eld
JTextAr
ea
JRadioButton
JPasswordFie
ld
JLab
JLi
JComboBox JPan
JOptionPa
JScroll
JSlid
el
st
el
ne
Bar
er
JTabbedPan JSplitP
JLayeredPa JSeparat
JScrollP
JRootPa
e
ane
ne
or
ane
ne
JToolB JMenuBar JPopupMen
JFileChoo
JColorChoos JToolT
ar
u
ser
er
ip
JTre JTabl JTableHead JInternalFr
JProgress
JSpinn
e
e
er
ame
Bar
er
04/14/15
Container Classes
Container classes are GUI components that
are used as containers to contain other GUI
components
For Swing use: Component, Container, JFrame,
JDialog, JApplet, Jpanel
JFrame is a window not contained inside another
window
JDialog is a temporary popup window or message box
JApplet is an applet that can run in a web browser
JPanel is an invisible, nest-able container used
to hold UI components or canvases to draw graphics
A layout manager is used to position and
place components in a container
04/14/15
Frames
You need a frame to hold the UI components
(100, 100)
Title bar
Content
pane
300 pixels hi
400 pixels wide
/
usr/local/pub/sps/courses/cs2/gui/Frames/MyFrame.java
04/14/15
Content Pane
Layered pane
Glass pane
Menu bar
Content pane
The content pane is the part of the frame
where the UI components will be placed
It is a java.awt.Container object
04/14/15
10
Adding Components to a Frame
UI components can be added to the content pane
after they are created
Here, the OK button is centered in the frame
and occupies the whole frame, no matter how it
is resized
/
usr/local/pub/sps/courses/cs2/gui/Frames/MyFrameWithButton.jav
a
04/14/15
11
Layout Managers
There are three basic layout managers
which control how UI components are
organized on the frame
FlowLayout
GridLayout
BorderLayout
Once created, the layout can be set in the
content pane using setLayout
As the window is resized, the UI
components reorganize themselves based on
the rules of the layout
04/14/15
12
FlowLayout
With flow layout, the components arrange
themselves from left to right in the order they
were added
Rows/buttons are left
aligned using
FlowLayout.LEFT
Horizontal g
of 10 pixels
Vertical gap of 20 pixels
/
usr/local/pub/sps/courses/cs2/gui/Layout/ShowFlowLayout.j
ava
04/14/15
13
Extending JFrame
public class GUIMain extends JFrame {
// construct GUI interface with components
public GUIMain() {
// set the layout manager
Container container = getContentPane();
container.setLayout();
// create UI components and add
container.add()
} // GUIMain
// create instance of GUIMain and set
// frame behaviors
public static void main(String args[]) {
GUIMain frame = new GUIMain();
frame.setTitle();
} // main
} // GUIMain
04/14/15
14
GridLayout
With grid layout, the components arrange
themselves in a matrix formation (rows,
columns)
Either the row or column must be non-zero
The non-zero dimension is fixed and the
zero dimension is determined dynamically
The dominating parameter is the rows
/
usr/local/pub/sps/courses/cs2/gui/Layout/ShowGridL
ayout.java
04/14/15
15
GridLayout
2,4
10, 10
0,4
4,4
04/14/15
16
BorderLayout
With border layout, the window is divided
into five areas:
BorderLayout.NORTH
BorderLayout.WEST
BorderLayout.CENTER
BorderLayout.EAST
BorderLayout.SOUTH
Components are added to the frame using a
specified index:
container.add(new JButton(East), BorderLayout.EAST);
/
usr/local/pub/sps/courses/cs2/gui/Layout/ShowBorde
rLayout.java
04/14/15
17
BorderLayout
04/14/15
18
BorderLayout
The components stretch in this manner:
North and South stretch horizontally
East and West stretch vertically
Center can stretch in both directions to fill
space
The default location for a component is
BorderLayout.CENTER
If you add two components to the same
location, only the last one will be
displayed
It is unnecessary to place components to
occupy all areas
04/14/15
19
Color
The color of GUI components can be set
using the java.awt.Color class
Colors are made of red, green and blue
components which range from 0 (darkest
shade) to 255 (lightest shade)
Each UI component has a background and
foreground:
Color color = new Color(128, 0, 0);
JButton button = new JButton();
button.setBackground(color);
// reddish
button.setForeground(new Color(0, 0, 128));
04/14/15
// blueish
20
Color
There are 13 constant colors defined in Color:
BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY,
MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW
/
usr/local/pub/sps/courses/cs2/gui/Color/ColorButtons.ja
va
04/14/15
21
Panels
Write a program to organize the components
for a microwave oven:
text
field
button
12 buttons
The problem is we want to use different
layouts for different components
04/14/15
22
Panels
The window can be subdivided into different
panels
The panels act as sub-containers for grouping
UI components
The content pane
uses a border
layout:
Panel2: East
Button: Center
text
field
button
12 buttons
Panel 2
uses a
border
layout:
text: North
Panel 1:
Center1
Panel
uses a
grid
layout
/
usr/local/pub/sps/courses/cs2/gui/Panels/MicrowaveUI.java
04/14/15
23
Fonts
You can create a font using the Font class
public Font(String name, int style, int size);
The standard fonts are SansSerif,
Serif, Monospaced, Dialog, or
DialogInput
The styles are Font.PLAIN, Font.BOLD,
Font.ITALIC, and Font.BOLD + Font.ITALIC
Font font1 = new Font(SansSerif, Font.BOLD, 16);
Font font2 = new Font(Serif, Font.ITALIC, 12);
JButton button = new JButton(OK);
button.setFont(font1);
04/14/15
24
Graphics
Graphics can be drawn using a class which
extends JPanel
Swing will call the paintComponent method to
draw:
protected void paintComponent(Graphics g);
There are a variety of drawing methods:
drawString(String string, int x, int y);
drawLine(int x1, int y1, int x2, int y2);
drawRect(int x, int y, int w, int h);
drawOval(int x, int y, int w, int h);
drawPolygon(int[] xpoints, int[] ypoints, int npoints);
/
usr/local/pub/sps/courses/cs2/gui/Graphics/DrawStuff.java
04/14/15
25
Graphics
line
filled
oval
filled
arc
filled rectangle
unfilled rectangle
filled
polygon
04/14/15
string
unfilled
oval
unfilled
arc
26