|
|||||
Web
Design & Development CS506
VU
Lesson
10
Graphical
User Interfaces
A
graphical user interface is a
visual interface to a program. GUIs are
built from GUI
components
(buttons,
menus, labels etc). A GUI component is an
object with which the user
interacts via the mouse
or
keyboard.
Together,
the appearance and how user
interacts with the program are
known as the program
look
and
feel.
Support
for GUI in Java
The
classes that are used to
create GUI components are
part of the "java.awt" or
"javax.swing"
package. Both these packages
provide rich set of user
interface components.
GUI
classes vs. Non-GUI Support
Classes
The
classes present in the awt
and swing packages can be
classified into two broad
categories.
GUI
classes & Non-GUI Support
classes.
The
GUI classes as the name indicates are
visible and user can
interact with them. Examples of
these
are JButton, JFrame &
JRadioButton etc
The
Non-GUI support classes provide
services and perform
necessary functions for GUI
classes. They
do
not produce any visual
output. Examples of these classes
are Layout managers
(discussed latter)
&
Event handling (see handout
on it) classes etc.
java.awt
package
AWT
stands for "Abstract
Windowing Toolkit "contains
original GUI components that
came with the
first
release of JDK. These
components are tied directly
to the local platform's (Windows,
Linux,
MAC
etc) graphical user
interface capabilities. Thus results in a
java program executing on
different java
platforms
(windows, Linux, Solaris etc)
has a different appearance
and sometimes even different
user
interaction
on each platform.
AWT
components are often called
Heavy Weight Components
(HWC) as they rely on the
local
platform's
windowing system to determine their
functionality and their look
and feel. Every time
you
create
an AWT component it creates a corresponding process on
the operating system. As compared
to
this
SWING components are managed
through threads and are
known as Light Weight
Components.
This
package also provides the
classes for robust event handling
(see handout on it) and
layout
managers.
javax.swing
package
These
are the newest GUI
components. Swing components
are written, manipulated and
displayed
completely
in java, therefore also
called pure java components.
The swing components allow
the
programmer
to specify a uniform look
and feel across all
platforms.
Swing
components are often
referred to as Light Weight
Components as they are
completely
written
in java. Several swing components
are still HWC. e.g. JFrame
etc.
76
Web
Design & Development CS506
VU
GUI
Creation Steps
1.
import required packages
import
java.awt.* and/or javax.swing.*
package.
2.
Setup
the top level containers
A
container is a collection of related
components, which allows
other components
to be
nested inside it. In
application with JFrame, we attatch
components to the content
pane
a container.
Two
important methods the container
class has add
and
setLayout.
The
add method is used for adding
components to the content pane while
setLayout
method is
used to specify the layout
manager.
Container
are classified into two
broad categories that are
Top Level containers
and
General Purpose Containers
Top
level containers can contain
(add) other containers as well as
basic components
(buttons,
labels etc) while general purpose containers
are typically used to
collect
basic
components and are added to
top level containers.
General
purpose containers cannot exist alone
they must be added to top
level containers
77
Web
Design & Development CS506
VU
Examples of
top level container are
JFrame, Dialog and Applet
etc. Our application
uses
one of these.
Examples of
general purpose container are
JPanel, Toolbar and ScrollPane
etc.
So,
take a top level container
and create its instance. Consider the
following code of line
if
JFrame
is selected as a top level
container
JFrame
frame
=
new JFrame();
3. Get
the component area of the
top level container
Review
the hierarchy given above, and observe
that JFrame is a
frame
is
a
window.
So, it can be interpreted as
JFrame is a
window.
Every
window has two areas.
System Area & Component
Area
The
programmer cannot add/remove components to the System
Area.
The
Component Area often known as
Client area is a workable place
for the programmer.
Components
can be added/removed in this
area.
So,
to add components, as you guessed
right component area of the JFrame is
required. It
can
be accomplished by the following code of
line
Conntainer
con
=
frame.getContentPane();
frame
is an
instance of JFrame and by calling
getContentPane()
method on
it, it returns the
component
area. This component area is of
type container and that is
why it is stored in a
variable
of a Container class. As already
discussed, container allows
other components to be
added
/ removed.
4.
Apply layout to component
area
The
layout (size & position
etc. How they appear) of
components in a container is
usually
governed by Layout Managers.
The
layout manager is responsible for
deciding the layout policy and
size of its
components
added to the container.
Layout
managers are represented in
java as classes. (Layout
Managers are going to
be
discussed
in detail later in this
handout)
To
set the layout, as already
discussed use setLayout method
and pass object of
layout
manager
as an argument.
con.setLayout( new
FlowLayout( ) );
We
passed an object of FlowLayout to the
setLayout method here.
We
can also use the following
lines of code instead of above.
FlowLayout layout
= new
FlowLayout();
con.setLayout(layout);
78
Web
Design & Development CS506
VU
Create
and Add
components
Create
required components by calling
their constructor.
JButton
button = new JButton ( );
After
creating all components your
are interested in, the next
task is to add these
components
into the component area of your
JFrame (i.e ContentPane, the reference
to
which
is in variable con of type
Container)
Use
add
method of the
Container to accomplish this and pass it
the component to be added.
con.add(button);
6. Set
size of frame and make it
visible
A frame
must be made visible via a
call to setVisible(true) and
its size defined via a
call
setSize(rows
in pixel, columns in pixel) to be
displayed on the screen.
frame.setSize(200,
300) ;
frame.setVisible(true)
;
Note:
By
default, all JFrame's are
invisible. To make visible frame
visible we have passed
true
to
the
setVisible
method.
frame.setVisible(false)
;
Making
a Simple GUI
The
above figured GUI contains one text field
and a button. Let's code it by
following the six GUI
creation
steps we discussed.
Code
for Simple GUI
//
File GUITest.java
//Step 1:
import packages
import
java.awt.*;
import
javax.swing.*;
public
class GUITest {
JFrame
myFrame ;
JTextField
tf;
JButton
b;
//method
used for setting layout of
GUI
public
void initGUI ( ) {
79
Web
Design & Development CS506
VU
//Step 2:
setup the top level
container
myFrame
= new JFrame();
//Step 3:
Get the component area of
top-level container
Container
c = myFrame.getContentPane();
//Step 4:
Apply layouts
c.setLayout( new
FlowLayout( ) );
//Step 5:
create & add
components
JTextField
tf = new JTextField(10);
JButton
b1 = new JButton("My Button");
c.add(tf);
c.add(b1);
//Step 6:
set size of frame and make
it visible
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(200,150);
myFrame.setVisible(true);
} //end
initGUI method
public
GUITest () { // default
constructor
initGUI
();
}
public
static void main (String
args[ ]) {
GUITest
gui = new GUITest();
}
} //
end of class
Important
Points to Consider
main
method
(from where program execution
starts) is written in the same
class. The main
method
can
be in a separate class instead of writing
in the same class its your
choice.
Inside
main, an object of GUI test
class is created that
results in calling of constructor of the
class
and
from the constructor, initGUI
method is
called that is responsible for
setting up the GUI.
The
following line of code is
used to exit the program
when you close the
window
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
If
you delete this line and run
your program, the desired GUI would be
displayed. However if
you
close the window by using
(X) button on top left
corner of your window,
you'll notice that
the
control doesn't return back to
command prompt. The reason
for this is that the java
process is
still
running. How ever if you put
this line in your code,
when you exit your
prompt will return.
References:
Sun
java tutorial: http://java.sun.com/docs/books/tutorial/java
Thinking
in java by Bruce Eckle
80
Web
Design & Development CS506
VU
Beginning
Java2 by Ivor Hortan
GUI
creation steps are taken
from the book Java A Lab
Course by Umair Javed
Graphical
User Interfaces - 2
Layout
Managers
Layout
Managers are used to form
the appearance of your GUI.
They are concerned with
the
arrangement
of components of GUI. A general question
is "why we can not place
components at our
desired
location (may be using the
x,y coordinate
position?"
The
answer is that you can
create your GUI without
using Layout Managers and
you can also do VB
style
positioning of components at some
x,y co-ordinate in Java, but
that is generally not
advisable if
you
desire to run the same
program on different
platforms
The
appearance of the GUI also depends on the
underlying platform and to keep that
same the
responsibility
of arranging layout is given to the
LayoutManagers so they can
provide the same look
and
feel across different
platforms
Commonly
used layout managers
are
1.
Flow
Layout
2.
Grid
Layout
3.
Border
Layout
4.
Box
Layout
5.
Card
Layout
6.
GridBag
Layout and so on
Let
us discuss the top three in detail one by
one with code examples.
These top three will meet
most of
your
basic needs
1. Flow
Layout
Position
components on line by line
basis. Each time a line is
filled, a new line is
started.
The
size of the line depends
upon the size of your frame. If
you stretch your frame while
your
program
is running, your GUI will be
disturbed.
Example
Code
//
File FlowLayoutTest.java
import
java.awt.*;
import
javax.swing.*;
public
class FlowLayoutTest {
JFrame
myFrame ;
JButton
b1, b2, b3, b4,
b5;
//method
used for setting layout of
GUI
public
void initGUI ( ) {
myFrame
= new JFrame("Flow Layout");
81
Web
Design & Development CS506
VU
Container
c = myFrame.getContentPane();
c.setLayout(
new FlowLayout( ) );
b1
=
new
JButton("Next Slide");
b2
=
new
JButton("Previous Slide");
b3
=
new
JButton("Back to Start");
b4
=
new
JButton("Last Slide");
b5
=
new
JButton("Exit");
c.add(b1);
c.add(b2);
c.add(b3);
c.add(b4);
c.add(b5);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(300,150);
myFrame.setVisible(true);
} //end
initGUI method
public
FlowLayoutTest () { // default
constructor
initGUI
();
}
public
static void main (String
args[ ]) {
FlowLayoutTest
flTest = new FlowLayoutTest();
}
} //
end of class
Output
2. Grid
Layout
Splits
the panel/window into a grid
(cells) with given
number of rows and
columns.
Forces
the size of each component to occupy the
whole
cell.
Size of each component is
same
Components
are added row wise. When
all the columns of
the
first row are get filled the
components are then
added
to the next row.
Only
one component can be added into
each cell.
Example
Code
//
File GridLayoutTest.java
import
java.awt.*;
import
javax.swing.*;
82
Web
Design & Development CS506
VU
public
class GridLayoutTest {
JFrame
myFrame ;
JButton
b1, b2, b3, b4,
b5;
//method
used for setting layout of
GUI
public
void initGUI ( ) {
myFrame
= new JFrame("Grid Layout");
Container
c = myFrame.getContentPane();
//
rows , cols
c.setLayout(
new GridLayout( 3 , 2 ) );
b1
=
new
JButton("Next Slide");
b2
=
new
JButton("Previous Slide");
b3
=
new
JButton("Back to Start");
b4
=
new
JButton("Last Slide");
b5
=
new
JButton("Exit");
c.add(b1);
c.add(b2);
c.add(b3);
c.add(b4);
c.add(b5);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(300,150);
myFrame.setVisible(true);
} //end
initGUI method
public
GridLayoutTest () { // default
constructor
initGUI
();
}
public
static void main (String
args[ ]) {
GridLayoutTest
glTest = new GridLayoutTest();
}
} //
end of class
output
Modification
The
grid layout also allows the
spacing between cells. To achieve
spacing
between cells, modify the above
program.
Pass
additional parameters to the constructor of
GridLayout, spaces between rows
&
83
Web
Design & Development CS506
VU
spaces
between columns as shown below
c.setLayout(
new GridLayout( 3 , 2 , 10 , 20)
);
The
output is look similar to
one given below.
3. Border
Layout
Divides
the area into five regions.
North, South, East, West and
Center
Components
are added to the specified
region
If
any region not filled, the
filled regions will occupy the
space but the center region
will
still
appear as background if it
contains no
component.
Only
one component can be added
into
each region.
Example
Code
//
File BorderLayoutTest.java
import
java.awt.*;
import
javax.swing.*;
public
class BorderLayoutTest {
JFrame
myFrame ;
JButton
b1, b2, b3, b4,
b5;
//method
used for setting layout of
GUI
public
void initGUI ( ) {
myFrame
= new JFrame("Border Layout");
Container
c = myFrame.getContentPane();
c.setLayout(
new BorderLayout( );
b1 = new
JButton("Next Slide");
b2 = new
JButton("Previous Slide");
84
Web
Design & Development CS506
VU
b3 = new
JButton("Back to Start");
b4 = new
JButton("Last Slide");
b5 = new
JButton("Exit");
c.add(
b1 , BorderLayout.NORTH );
c.add(
b2 , BorderLayout.SOUTH );
c.add(
b3 , BorderLayout.EAST );
c.add(
b4 , BorderLayout.WEST );
c.add(
b5 , BorderLayout.CENTER);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(300,150);
myFrame.setVisible(true);
} //end
initGUI method
public
BorderLayoutTest () { // default
constructor
initGUI
();
}
public
static void main (String
args[ ]) {
BorderLayoutTest
glTest = new BorderLayoutTest();
}
} //
end of class
Points
to Remember
Revisit
the code of adding components, we specify
the region in which we want to
add
component or
otherwise they will not be
visible.
Consider the
following segment of code:
BorderLayout.NORTH,
as you guessed
correctly
NORTH is a constant (final)
defined in BorderLayout class
public access
modifier.
Similarly the other ones are
defined. Now you
understand,
why
so much emphasis has been
made on following the naming
conventions.
Output
85
Web
Design & Development CS506
VU
Making
Complex GUIs
From
the discussion above it seems that the
basic Layout Managers may
not help us in
constructing
complex
GUIs, but generally a
combination of these basic
layouts can do the job. So
lets try to create
the
calculator
GUI given below
This
GUI has 16 different buttons each of
same size and text field on
the top and a label
`my
calculator' on the bottom.
So,
how we can make this
GUI? If Border Layout is
selected, it has five
regions (each region
can
have at
most one component) but here we have more
than five components to add.
Lets try Grid
Layout,
but all the components in a
Grid have same size and the
text field at the top and
label at the
bottom
has different size. Flow
Layout cannot be selected because if we
stretch our GUI it will
destroy
its
shape.
Can
we make this GUI? Yes, we
can. Making of such GUI is a
bit tricky business
but
General
Purpose Containers are there to
provide the solution.
JPanel
It is general
purpose container (can't
exist alone, it has to be in some
toplevel container) in
which
we can put in different
components (JButton , JTextField
etc even other
JPanels)
JPanel
has its own layout
that can be set while
creating JPanel
instance
JPanel
myPanel = new JPanel ( new FlowLayout( )
);
Add
components by using add
method
like shown below.
myPanel.add
(button );
Must
be added to a top level
container (like JFrame etc) in
order to be visible as they
(general
purpose
containers) can't exist alone.
Solution
To
make the calculator GUI shown above, take
JFrame (top level container)
and set its layout to
border.
Than take JPanel (general
purpose container) and set
its layout to Grid with 4
rows and 4
columns.
86
Web
Design & Development CS506
VU
Add
buttons to JPanel as they all have
equal size and JPanel
layout has been set to
GridLayout.
Afterthat,
add text field to the north
region, label to the south region and
panel to the center
region
of the
JFrame's container. The east
and west regions are left
blank and the center region
will be
stretched
to cover up these. So, that's
how we can build our
calculator GUI.
Code
for Calculator
GUI
//
File CalculatorGUI.java
import
java.awt.*;
import
javax.swing.*;
public
class CalculatorGUI {
JFrame
fCalc;
JButton
b1, b2, b3, b4,
b5, b6, b7, b8,
b9, b0;
JButton
bPlus, bMinus, bMul, bPoint,
bEqual, bClear;
JPanel
pButtons;
JTextField
tfAnswer;
JLabel
lMyCalc;
//method
used for setting layout of
GUI
public
void initGUI ( ) {
fCalc
= new JFrame();
b0
=
new
JButton("0");
b1
=
new
JButton("1");
b2
=
new
JButton("2");
b3
=
new
JButton("3");
b4
=
new
JButton("4");
b5
=
new
JButton("5");
b6
=
new
JButton("6");
b7 = new
JButton("7");
b8 = new
JButton("8");
b9 = new
JButton("9");
bPlus
= new JButton("+");
bMinus
= new JButton("-");
bMul
= new JButton("*");
bPoint
= new JButton(".");
bEqual
= new JButton("=");
bClear =
new JButton("C");
tfAnswer
= new JTextField();
lMyCalc
= new JLabel("My Clacualator");
87
Web
Design & Development CS506
VU
//creating
panel object and setting
its layout pButtons = new
JPanel
(new
GridLayout(4,4));
//adding
components (buttons) to
panel
pButtons.add(b1);
pButtons.add(b2);
pButtons.add(b3);
pButtons.add(bClear);
pButtons.add(b4);
pButtons.add(b5);
pButtons.add(b6);
pButtons.add(bMul);
pButtons.add(b7);
pButtons.add(b8);
pButtons.add(b9);
pButtons.add(bMinus);
pButtons.add(b0);
pButtons.add(bPoint);
pButtons.add(bPlus);
pButtons.add(bEqual);
//
getting componenet area of
JFrame
Container
con = fCalc.getContentPane();
con.setLayout(new
BorderLayout());
//adding
components to container
con.add(tfAnswer,
BorderLayout.NORTH);
con.add(lMyCalc,
BorderLayout.SOUTH);
con.add(pButtons,
BorderLayout.CENTER);
fcalc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fCalc.setSize(300,
300);
fCalc.setVisible(true);
} //end
initGUI method
public
CalculatorGUI () { // default
constructor
initGUI
();
}
public
static void main (String
args[ ]) {
CalculatorGUI
calGUI = new CalculatorGUI
();
}
} //
end of class
88
Web
Design & Development CS506
VU
Reference:
Sun
java tutorial: http://java.sun.com/docs/books/tutorial/java
Thinking
in java by Bruce Eckle
Beginning
Java2 by Ivor Hortan
Java
A Lab Course by Umair
Javed
89
Table of Contents:
|
|||||