Advanced Programming - Chapter 6
Advanced Programming - Chapter 6
GUI
GUI
Graphical User Interface ("Goo-ee")
Pictoral interface to a program
Distinctive "look" and "feel"
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
AWT Components
primitive
container
Using Peers
Java
Program
Java
AWT
Native
Window
System
Peers
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
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
Swing Philosophy
Richer Component Set
Replaces AWT Component Set
Adds more complex components
14
15
16
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
22
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
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
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
Description
Adds the specified
component to the
panel.
void setLayout
(LayoutManager layout)
Method
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
36
JComponents
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
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.
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
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
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
Description
void
setRolloverEnabled
(boolean value)
void setEnabled
(boolean value)
Description
Sets the text displayed by the
button.
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.
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
Methods
Char[ ] getPassword();
JTextArea( )
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
53
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.
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
63
64