Graphical User Interface

Download Report

Transcript Graphical User Interface

Graphical User Interface(GUI)
for IST410 Students only
Gui-1
Objectives



GUI Container classes
Layout managers
Flow, Border, Grid layouts
for IST410 Students only
Gui-2
Graphical User Interface: Introduction




Up to this point, we have written programs where our
interaction was limited to taking inputs from the
command line and writing output to the shell window
Most modern programs do not work that way; they allow
users to take inputs from the screen and display result
back to the screen
Such programs are generally called event driven
programs
Event driven programs use GUI objects such as buttons,
lists, text fields to facilitate user interaction
for IST410 Students only
Gui-3
Graphical User Interface: Introduction




Event driven programs use two different sets of objects:
one to paint the user interface components on the display
screen, and the other to handle or respond to events
Events are user interaction with a program: a mouse
click, a key stroke, selection of a menu choice
For example, when a mouse click occurs on a Button, it
is an action event i.e. the program is expected to take
‘some’ action
The user interface components are defined in graphics
packages of Java: AWT and Swing
for IST410 Students only
Gui-4
Graphical User Interface: Introduction

General strategy to write an event driven program







Define a container object
Place appropriate GUI components on the container object
Register listeners with GUI objects to listen for events;
Define event handlers
Listeners are interfaces whose method(s) are invoked by
the JVM when an event occurs
The response of the program is coded within these
methods - hence event handlers
In this section, we explore the mechanics of constructing
GUI interfaces
for IST410 Students only
Gui-5
Swing




Swing is a set of customizable graphical toolkit that can be
used in developing an enterprise level application
It is a part of a larger suite of libraries known as JFC - Java
Foundation Class
JFC includes 2 graphics component libraries

AWT - Abstract Window Toolkit
 Swing
JFC also includes other libraries to support graphics
oriented programming
for IST410 Students only
Gui-6
AWT and Swing






AWT is the graphical toolkit in all of jdk1.x series
AWT was the GUI toolkit of choice before the release of
Swing classes
Swing is not a replacement of AWT, but is built on top of
core AWT classes
Swing can be used with jdk1.1.5 or later versions, and is a
component of the core java in jdk1.2 and jdk1.3
A program can mix both AWT and Swing components
A program must import the java.awt package to use AWT
components and javax.swing package to use Swing
components.
for IST410 Students only
Gui-7
AWT

AWT package comprises a number of classes
 Layout classes: BorderLayout, FlowLayout,
GridLayout, CardLayout, GridBagLayout
 Graphics classes - Color, Dimension, Font, Image, etc.
 Toolkit
 Component classes - Button, Checkbox, Choice, Label,
and others
 Container classes - Panel, Window, Frame, Applet
 MenuComponent - MenuBar, MenuItem, Menu etc
for IST410 Students only
Gui-8
An initial AWT Program: Try It
import java.awt.*; //GuiFrame.java
All applications (not
public class GuiFrame extends Frame {
applets) need a background
public GuiFrame() {}
- a Frame
public GuiFrame(String s){
super(s);
Title string of the frame
}
public static void main(String[] args) {
GuiFrame gf = new GuiFrame("Hello Java Frame");
gf.setBackground(Color.red);
gf.setSize(300,300);
The frame becomes visible here,
gf.setVisible(true);
usually the last logical statement
}
}
for IST410 Students only
Gui-9
Discussion of GuiFrame.java







An application starts with defining a background surface: a
Frame in AWT
Components are then added on to the Frame - none in this
example
Placement of the components are left to Layout Managers
Background color is set to Red using Color.red, a
predefined color in the Color class of AWT
The size of the Frame is set to 300,300 pixels
The frame is finally made visible
There is no event handler in this program and therefore, we
cannot interact with this program
for IST410 Students only
Gui-10
Closing an Application






In order to close the frame, we need to incorporate an
event handler
There are different type of event handlers in Java; we need
the Window Event handler.
Window event handler is registered through the window
event interface known as WindowListener
We discuss the event handling mechanism in the next
chapter
We do incorporate one event handler in our examples
enabling us to close them
Let us modify the GuiFrame.java example to incorporate
event handling
for IST410 Students only
Gui-11
A Frame with Window Event handler
import java.awt.*;
// FrameWithExit.java
import java.awt.event.*;
// Events
public class FrameWithExit extends Frame implements WindowListener {
public FrameWithExit() {
super();
This class is closable
addWindowListener(this);
}
Registering the WindowListener
public FrameWithExit(String s) {
with the class
super(s);
addWindowListener(this);
}
public void windowClosed(WindowEvent e) {}
These 7 methods are the event
public void windowDeiconified(WindowEvent e) {}
handlers for Window events, defined
public void windowIconified(WindowEvent e) {}
in the WindowListener interface
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
windowClosing is the only
public void windowClosing(WindowEvent e) {
method implemented, provides
System.exit(0);
the capability to close a window
}
} // end FrameWithExit class
for IST410 Students only
Gui-12
A closable application
import java.awt.*;
//GuiFrameClosable.java
public class GuiFrameClosable extends FrameWithExit {
public GuiFrameClosable() {}
This class is closable since
public GuiFrameClosable(String s){
it extends a Frame with an
super(s);
event handler
}
public static void main(String[] args) {
GuiFrameClosable gf = new GuiFrameClosable("GUI Closable Frame");
gf.setBackground(Color.red);
gf.setSize(300,300);
gf.setVisible(true);
}
}
for IST410 Students only
Gui-13
An initial Swing Program
import javax.swing.*; //SwingFrame.java
This is almost exactly
import java.awt.Color;
same as
public class SwingFrame extends SwingFrameWithExit { FrameWithExit
public SwingFrame() {}
except it extends
JFrame
public SwingFrame(String s){
super(s);
}
public static void main(String[] args) {
SwingFrame gf = new SwingFrame("Swing Closable Frame");
gf.getContentPane().setBackground(Color.red);
gf.setSize(300,300);
We use the ContentPane of a
gf.setVisible(true);
JFrame; we do not directly place
}
components on a JFrame
}
for IST410 Students only
Gui-14
Component layering in a Graphical
Interface





A graphical interfce is built using a top-level component,
sometimes referred as heavy weight components
Graphical widgets such as Buttons, Combo boxes are
placed on heavy weight components
These widgets are sometimes referred as light weight
components
Heavy weight components provide the background that are
opaque and interact with the underlying operating system
Light weight components are painted on this opaque
background and do not depend on the underlying system
for IST410 Students only
Gui-15
Heavy weight and Light weight
Components


Heavy weight or top-level components are
JFrame, JApplet, JDialog, JWindow
Light weight components are many and are subclasses of
JComponent
 JPanel
 JList
 JLabel
 JToolTip
 AbstractButton JButton, JToggleButton, JMenuItem
 JMenuBar
for IST410 Students only
Gui-16
JFrame


Unless it is an applet, an application uses JFrame as the top
level component
The inheritance hierarchy of a JFrame
java.lang.Object
java.awt.Component
java.awt.Container
AWT Classes
java.awt.Window
java.awt.Frame
javax.swing.JFrame
for IST410 Students only
Gui-17
JFrame




An application creates a window by instantiating a frame
i.e. JFrame
JFrame can be thought of as a complete data structure on
which light weight components are painted
JFrame (also Frame) comes with built in controls such as
minimize, maximize and close buttons, however, event
handlers are still needed to make these buttons functional
Components cannot be directly placed on a JFrame, but a
layer of a JFrame known as ContentPane
JFrame jf = new JFrame();
Container cp = jf.getContentPane();
for IST410 Students only
Gui-18
JPanel




JPanels are also containers
Unlike JFrames, JPanels can be nested as well placed in a
JFrame
JFrames cannot be nested nor can be placed in another
container
The inheritance hierarchy
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
for IST410 Students only
Gui-19
JPanel




Components can be added to JPanels
Since JPanels can be nested, complex layouts can be
constructed by assigning different layouts to different
panels
add method is used to place a component on a container
The location of the placement is determined by the layout
manager
JFrame jf = new JFrame();
Container cp = jf.getContentPane();
JPanel jp = new JPanel();
cp.add(jp, BorderLayout.WEST);
for IST410 Students only
Gui-20
JButton





We use button objects for most of our examples to
demonstrate principles of component placement and event
handling
We, therefore, discuss JButton, the button object of Swing
class a bit out of turn
JButton is a subclas of AbstractButton, which in turn is
derived from JComponent
JButton is a light weight component and needs to be placed
in some container such as a panel or a frame to become
visible
JButtons, unlike its AWT cousin(Button), can be created
with a text and/or picture face
for IST410 Students only
Gui-21
JButton




JButton provides 4 constructors
JButton() - No text or icon
JButton(Icon icon) - Button with an icon face
JButton(String text) - Button with a text face
JButton(String text, Icon icon) - Button with both icon and
text face
Icon is an interface and is implemented by, among others,
ImageIcon class in Swing
We can use ImageIcon class to translate graphics files such
as gif files to ImageIcon objects
These icon objects can then be used to paint the face of a
JButton as well as many other swing components
for IST410 Students only
Gui-22
Layout Managers




Layout of a container is controlled by a class of objects
called Layout managers
Swing inherits several layout managers from AWT, and
also adds new ones
These layout managers decide the placement of
components in the container
They are also responsible for repainting windows and
containers when the user resizes the frame, or the
application is moved to a machine with a different
resolution, or to a different machine
for IST410 Students only
Gui-23
Layout Managers




A program can, of course, turn off the layout managers
If layout managers are not used, it is the program’s
responsibility to locate each component, as well as manage
resizing and repainting
Several layout managers are discussed in this section
 BorderLayout
Other available layouts
 FlowLayout
GridBagLayout
 GridLayout
CardLayout
BoxLayout
Except for BoxLayout, all others are available in AWT
for IST410 Students only
Gui-24
BorderLayout Manager

A BorderLayout divides the container into 5 regions
North
West
Center
East
South


JFrame and Frame(AWT) use BorderLayout as their
default layout managers
To assign Border layout to panels, one has to construct a
BorderLayout object
for IST410 Students only
Gui-25
BorderLayout Object




A BorderLayout object can be constructed by calling the
constructor of the layout manager
BorderLayout bl = new BorderLayout();
cp.setLayout(bl); // set the layout of cp to bl
cp can be a Frame, the content pane of a JFrame, Panel, or
a JPanel
It is necessary to create a named layout object only if the
program is going to make a reference to such an object
Otherwise, the layout manager can be created and assigned
anonymously
cp.setLayout(new BorderLayout());
for IST410 Students only
Gui-26
BorderLayout Object


BorderLayout class provides a second constructor through
which horizontal and vertical gaps among components can
be specified
BorderLayout bl = new BorderLayout(10,10);
The integers 10,10 define horizontal and vertical gaps
respectively among components placed in the container
for IST410 Students only
Gui-27
GuiWithBorderLayout.java

Output from the program
for IST410 Students only
Gui-28
Example: GuiWithBorderLayout.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GuiWithBorderLayout extends
SwingFrameWithExit {
Container cp;
JButton left, right, top, bottom, center;
cp.add(center,BorderLayout.CENTER);
top = new JButton("Top");
cp.add(top,BorderLayout.NORTH);
bottom = new JButton("Bottom");
cp.add(bottom,BorderLayout.SOUTH);
setSize(300,300);
setVisible(true);
}
public GuiWithBorderLayout() {
cp = getContentPane();
cp.setLayout(new BorderLayout(10,10));
cp.setBackground(Color.red);
left = new JButton("Left");
cp.add(left,BorderLayout.WEST);
right = new JButton("Right");
cp.add(right,BorderLayout.EAST);
center = new JButton("Center");
public static void main(String[] args) {
GuiWithBorderLayout gbl = new
GuiWithBorderLayout();
}
}

We use JButtons to fill in
regions of the JFrame
for IST410 Students only
Gui-29
FlowLayout Manager






Panels and JPanels use Flow layout as their default
manager
FlowLayout objects are needed for Frames and JFrames
In FlowLayout, components are added left to right in the
order they are inserted into the container
When one row is completed, next insert automatically
flows into the next row
Components are centered in a row by default
Components can be aligned left or right by using an
overloaded version of the layout manager’s constructor
for IST410 Students only
Gui-30
FlowLayout Object

Create a FlowLayout object
FlowLayout fl = new FlowLayout();

// defaults are used
Align components on the left side of the row
FlowLayout fl = new FlowLayout(FlowLayout.LEFT);

Align components to the right side of the row, use a
horizontal gap of 2 pixels, and a vertical gap of 3 pixels
among components
FlowLayout fl = new FlowLayout(FlowLayout.RIGHT,2,3);

As in the case of BorderLayout, we can create FlowLayout
object anonymously
for IST410 Students only
Gui-31
GuiWithFlowLayout.java

Output from GuiWithFlowLayout.java
for IST410 Students only
Gui-32
Example: GuiWithFlowLayout.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GuiWithFlowLayout {
SwingFrameWithExit jf;
Container cp;
JButton one, two, three;
JButton exit;
JPanel jp;
public GuiWithFlowLayout() {
ImageIcon bullet = new
ImageIcon("bullet2.gif");
ImageIcon middle = new
ImageIcon("middle.gif");
jf = new SwingFrameWithExit();
cp = jf.getContentPane();
cp.setLayout(new BorderLayout(2,2));
cp.setBackground(Color.red);
// create the Panel
jp = new JPanel();
jp.setBackground(Color.blue);
// create the buttons and add to the panel
one = new JButton("ONE",bullet);
jp.add(one);
two = new JButton(middle);
jp.add(two);
three = new JButton("THREE",bullet);
jp.add(three);
cp.add(jp,BorderLayout.CENTER);
// add panel to the frame
exit = new JButton("EXIT");
cp.add(exit,BorderLayout.SOUTH);
jf.setSize(300,300);
jf.setVisible(true);
}
public static void main(String[] args) {
GuiWithFlowLayout gbl = new
GuiWithFlowLayout();
}
}
for IST410 Students only
Gui-33
Discussion: GuiWithFlowLayout.java




We use an object of type SwingFrameWithExit instead of a
JFrame; this works correctly since the class
SwingFrameWithExit not only extends JFrame but also has
an event handler associated with it.
Several JButtons are created using Icon option of the
constructor
A JPanel object is placed in the JFrame object; JFrame has
BorderLayout and JPanel has FlowLayout
Notice the usage of the add method. It is used to add
JPanel to the JFrame, as well as JButtons to JPanel and
JFrame
for IST410 Students only
Gui-34
GridLayout Manager





GridLayout enables a program to divide a container into a
grid
For example a 3,4 grid:
Not a default layout manager
for any container type
Creating a layout object
GridLayout gl = new GridLayout(3,4);
cp.setLayout(gl); // cp is a JPanel, Panel, Frame, JFrame
Components are added left to right, top to bottom in the
order of insertion
for IST410 Students only
Gui-35
GridLayout Object




As before, there are multiple constructors available
Default: One column per component, in a single row
GridLayout gl = new GridLayout();
Specify number of rows and column
GridLayout gl = new GridLayout(3,4);
Specify grid size as well as horizontal and vertical gaps
GridLayout gl = new GridLayout(3,4,2,2);
for IST410 Students only
Gui-36
GuiWithGridLayout.java

Output from GuiWithGridLayout
for IST410 Students only
Gui-37
Example: GuiWithGridLayout.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GuiWithGridLayout {
private SwingFrameWithExit jf;
private Container cp;
private JButton[] gridBtns;
private JLabel jl;
private JPanel jp;
private ImageIcon im;
public GuiWithGridLayout() {
im = new ImageIcon("middle.gif");
}
public void build() {
jf = new SwingFrameWithExit();
jf.setTitle("Grid Layout Test");
cp = jf.getContentPane();
cp.setLayout(new BorderLayout(1,1));
cp.setBackground(Color.red);
// create the Panel
jp = new JPanel();
jp.setBackground(Color.blue);
jp.setLayout(new GridLayout(4,4,1,1));
// create the buttons and add them to the panel
gridBtns = new JButton[16];
for (int i = 0; i< 16; i++){
gridBtns[i] = new JButton(im);
jp.add(gridBtns[i]);
}
cp.add(jp,BorderLayout.CENTER);
// add panel to the frame
jl = new JLabel("Border Layout
JFrame",SwingConstants.RIGHT);
cp.add(jl,BorderLayout.NORTH);
jf.setSize(300,300);
jf.setVisible(true);
}
public static void main(String[] args) {
GuiWithGridLayout gl = new
GuiWithGridLayout();
gl.build();
}
}
for IST410 Students only
Gui-38
Discussion: GuiWithGridLayout.java




We use SwingFrameWithExit in place of an ordinary
JFrame
We use an array of JButton objects; instantiation and
handling of these buttons are no different than ordinary
JButtons
Since GridLayout is not the default layout of any container
class, an anonymous GridLayout object is created and
assigned as the layout manager of the JPanel
We also use JLabel, a passive Swing component, to display
text as well as image
for IST410 Students only
Gui-39
Exercise

We will create a minimal calculator which looks like the
following
Use a JLabel to
display messages
1
4
7
0
2
5
8
C
3 +
6 9 *
= /
for IST410 Students only
Other items are
JButtons
Gui-40