You are on page 1of 64

ETIT-303

CSE 5th Semester


Lecture 14

A layout manager allows the java programmer to develop graphical


interfaces that will have a common appearance across the
heterogeneous internet.
There are five layout managers that the programmer may choose
from:
Flow Layout
Grid Layout
Border Layout
Card Layout
Gridbag Layout

Part of the AWT Class Hierarchy


Object

Component

Button

Checkbox
TextComponent

TextArea

TextField

Choice

List
Container

Panel

Window

ScrollPane

Applet
Dialog

Label
Canvas
ScrollBar

Frame

Layout Managers

A Component can be displayed on a screen and a user can


interact with a Component.

A Container is a Component that can hold other Components

A Layout Manager directs the placement of Components


within a Container.

A Container maintains a list of Components that it manipulates as well


as a LayoutManager to determine how components are displayed.
The Container class contains the following subclasses:
Window
Frame

Dialog
Panel
Applet
ScrollPane

Containers
Method defined in class Container include:

setLayoutManager (LayoutManager)

add (Component)
remove(Component)

add Component to display


remove Component from display

Containers

Window
A Window is a 2-dimensional drawing surface that can be displayed
on an output device.
A Window can be stacked on top of other Windows and can be
moved to the front or back of the visible windows.
Methods in class Window include:
show ( )

Make the Window visible

toFront( )

Move Window to front

toBack( )

Move window to back

Frame

A Frame is a type of Window with a title bar, a menu bar, a border, and a
cursor. It is used most frequently to display applications that contain a
graphical user interface or an animation.

Methods defined in Frame include:


setTitle(String)

getTitle(String)

setCursor(int)

setResizable( )

make the window resizable

setMenuBar(MenuBar)

include the menu bar for the window

Containers
Panel

A Panel is generally used as a component in a Frame or an


Applet.
It is used to group components into a single unit. The Panel with
its set of components is displayed as a single unit. It represents a
rectangular region of the display.
A Panel holds its own LayoutManager which may be different from the
LayoutManager of the Frame or Applet in which it resides.

Dialog

Always attached to an instance of Frame.


A window that is displayed for a short duration during execution.
Default LayoutManager is
for Frame)

BorderLayoutManager (same as

ScrollPane

It can hold only one Component.


It does not have a LayoutManager.
If size of the component held is larger than the size of the ScrollPane,
scroll bars will be automatically generated.

Layout Managers
Flow Layout
Lays out components row by row from left to right.
It is very straightforward to use, but it affords the programmer the
least ability to control the positioning of components. It is the
default layout manager in an applet.

As an example, consider an applet (subclass of Panel) that displays a


number of Buttons for selecting a language.

Layout Managers

English

French

Japanese

Spanish

Arabic

Greek

German

Portuguese

Chinese
Applet Started

Russian

Layout Managers
Constructing the previous display

import java.awt.*;
public class SelectLang extends java.applet.Applet {
Button eng = new Button(English);
.
Button rus = new Button (Russian);
FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
public void init ( ) {
setLayout(flow);
add(eng);
.
add(rus);
}
}

Layout Managers
Suppose we wish to construct the following layout

Age

Under 20

21-35

36-65

Name
Street Address
City

Zip

Over 65

Layout Managers

FlowLayout (int alignment, int hGap, int vGap);


In Example 1 FlowLayout(FlowLayout.LEFT, 30, 10)

A more orderly organization is achieved by first putting components


into panels and then placing panels in applet using Flow Layout

Layout Managers
Border Layout

North

West

Center

South

East

Layout Managers
Properties of a Border Layout Manager

More flexible in permitting programmer placement of components of


different sizes (such as panels, canvases and text areas.

Border areas adjust to accommodate the placement of a component.


The center consists of whats left over.

public BorderLayout (int hGap, int vGap)

Layout Managers
Example A BorderLayout with a Label in North, a Scrollbar in South,

a Panel containing a Checkboxgroup in West, a List in East, and a


Canvas in Center.

Border Layout Example


o
o
o
o
o

Red
Blue
Green
Black
White

Rectangle
Oval
Line
Fill
Background

Layout Managers
Grid Layout

Programmer specifies the number of


rows
columns
pixels between rows, pixels between columns

GridLayout myGrid = new GridLayout (3, 2, 10, 10);

Layout Managers
Grid Layout

Components expand or contract in size to fill a single grid


cell. Panels, canvases, and Lists are resized to fit into a grid
cell.

Components are placed in the container in order from left to right


and top to bottom.

Layout Managers
Grid Layout

name

address

e-mail

Layout Managers

Card Layout
A card layout is a group of components or
containers that are displayed one at a time.

Components or containers are placed on a card using the


statement:
add (String, component);

Layout Managers
Card Layout Construction

The Applet contains an ordered listing (array) of cards in


one of its panels

Card Panel

Layout Managers
Applet Declarations
public class CardDemo extends Applet {
private final int numCards = __;
//whatever the number
private String[ ] = new CardLabels[numCards];
//construct an array for holding CardPanel objects specified in separate file
private CardPanel[ ] cards = new CardPanel[numCards];
private CardLayout theLayout;
//Layout for CardPanels
//Create a Panel for displaying CardPanel objects in the Applet (green area)
private Panel cardDisplayPanel;

Applet initialization
public void init ( ) {
//essential statements for card display
setLayout (new BorderLayout);
//layout for the Applet
add(West, makeOtherPanel( )); //2nd parameter returns a Panel
add(Center, makeCardDisplayPanel( ));
//2nd param returns a Panel
}

Layout Managers
CardPanel Objects
CardPanel is a separately declared class that extends Panel
CardPanels are containers with their own Components and
Layout
CardPanel objects are created in method makeCardDisplayPanel() of
Applet

CardPanel objects are stored in the array cards

Java provides two sets of facilities for developing GUIs:


The Abstract Window Toolkit (AWT): package java.awt
Swing: package javax.swing

Swing architecture is rooted in the model-viewcontroller ( MVC) design that dates back to SmallTalk .
MVC architecture calls for a visual application to be broken
up into three separate parts:
A model that represents the data for the application.

The view that is the visual representation of that data.

A controller that takes user input on the view and


translates that to changes in the model.

Text-based interface
Predetermined
sequence of events
The program pauses
execution when it
expects input from the
user and continues on
the same set path after
it receives the input

Graphical interface
No set sequence of
events
The user can do any
number of things at
any time (type in a text
box, resize the
window, press a
button)
These responses are
called events.
We say the program is
event-driven.

AWT
AWT stands for Abstract windows
toolkit.

AWT components are called


Heavyweight component.

AWT components require java.awt


package.
AWT components are platform
dependent.

This feature is not supported in


AWT.

SWING
Swing is also called as JFCs (Java Foundation classes).
Swings are called light weight component because swing
components sits on the top of AWT components and do the work.
Swing components require javax.swing package.
Swing components are made in purely java and they are platform
independent.
We can have different look and feel in Swing.These feature is not
available in AWT.Swing has many advanced features like JTabel,
Jtabbed pane which is not available in AWT. Also. Swing
components are called "lightweight" because they do not require a
native OS object to implement their functionality. JDialog and
JFrame are heavyweight, because they do have a peer. So
components like JButton, JTextArea, etc., are lightweight because
they do not have an OS peer.
With Swing, you would have only one peer, the operating system's
window object. All of the buttons, entry fields, etc. are drawn by the
Swing package on the drawing surface provided by the window
object. This is the reason that Swing has more code. It has to draw
the button or other control and implement its behavior instead of
relying on the host operating system to perform those functions.
Swing is much larger. Swing also has very much richer functionality.

Constructors
These three constructors apply to checkboxes that operate

independently of each other (i.e., not radio buttons)


Checkbox()
Creates an initially unchecked checkbox with no label
Checkbox(String checkboxLabel)
Creates a checkbox (initially unchecked) with the specified label; see
setState for changing it
Checkbox(String checkboxLabel, boolean state)
Creates a checkbox with the specified label
The initial state is determined by the boolean value provided
A value of true means it is checked

INE2720 Web Application


Software Development

All copyrights reserved by C.C. Cheung 2003.

29

public class Checkboxes extends CloseableFrame {


public Checkboxes() {
super("Checkboxes");
setFont(new Font("SansSerif", Font.BOLD,
18));
setLayout(new GridLayout(0, 2));
Checkbox box;
for(int i=0; i<12; i++) {
box = new Checkbox("Checkbox " + i);
if (i%2 == 0) {
box.setState(true);
}
add(box);
}
pack();
setVisible(true);
}
}
INE2720 Web Application
Software Development

All copyrights reserved by C.C. Cheung 2003.

30

getState/setState
Retrieves or sets the state of the checkbox: checked (true)

or unchecked (false)

getLabel/setLabel
Retrieves or sets the label of the checkbox
After changing the label invalidate and validate the

window to force a new layout (same as button).

addItemListener/removeItemListener
Add or remove an ItemListener to process

ItemEvents in itemStateChanged
INE2720 Web Application
Software Development

All copyrights reserved by C.C. Cheung 2003.

31

CheckboxGroup Constructors
CheckboxGroup()
Creates a non-graphical object used as a tag to group checkboxes
logically together
Only one checkbox associated with a particular tag can be selected
at any given time

Checkbox Constructors
Checkbox(String label, CheckboxGroup group,

boolean state)
Creates a radio button associated with the specified group, with the
given label and initial state
INE2720 Web Application
Software Development

All copyrights reserved by C.C. Cheung 2003.

32

import java.applet.Applet;
import java.awt.*;
public class CheckboxGroups extends Applet {
public void init() {
setLayout(new GridLayout(4, 2));
setBackground(Color.lightGray);
setFont(new Font("Serif", Font.BOLD, 16));
add(new Label("Flavor", Label.CENTER));
add(new Label("Toppings", Label.CENTER));
CheckboxGroup flavorGroup = new CheckboxGroup();
add(new Checkbox("Vanilla", flavorGroup, true));
add(new Checkbox("Colored Sprinkles"));
add(new Checkbox("Chocolate", flavorGroup, false));
add(new Checkbox("Cashews"));
add(new Checkbox("Strawberry", flavorGroup, false));
add(new Checkbox("Kiwi"));
}
}
INE2720 Web Application
Software Development

All copyrights reserved by C.C. Cheung 2003.

33

Constructors
List(int rows, boolean multiSelectable)
Creates a listbox with the specified number of visible rows
Depending on the number of item in the list (addItem or add), a
scrollbar is automatically created
The second argument determines if the List is multiselectable

List()
Creates a single-selectable list box with a platform-dependent
number of rows and a platform-dependent width

List(int rows)
Creates a single-selectable list box with the specified number of
rows and a platform-dependent width
INE2720 Web Application
Software Development

All copyrights reserved by C.C. Cheung 2003.

34

import java.awt.*;
public class Lists extends CloseableFrame {
public Lists() {
super("Lists");
setLayout(new FlowLayout());
setBackground(Color.lightGray);
setFont(new Font("SansSerif", Font.BOLD, 18));
List list1 = new List(3, false);
list1.add("Vanilla");
list1.add("Chocolate");
list1.add("Strawberry");
add(list1);
List list2 = new List(3, true);
list2.add("Colored Sprinkles");
list2.add("Cashews");
list2.add("Kiwi");
add(list2);
pack();
setVisible(true);
}}

A list can be single-selectable or multi-selectable


INE2720 Web Application
Software Development

All copyrights reserved by C.C. Cheung 2003.

35

EVENT HANDING

A source generates an event and sends it to


one or more listeners.
The listener simply waits until it receives an
event.
Listener must register with source to receive
noticification.

-An event is an object that describes a state


change in a source.
-It can be generated as a consequence of a
person interacting with the elements in a
graphical user interface.
Examples.
Pressing a button, entering a character via the
keyboard, selecting an item in a list, and
clicking the mouse, timer expires, counter,
h/w or s/w failure.

A source is an object that generates an event.

This occurs when the internal state of that


object changes.

A source must register listeners.

public void addTypeListener(TypeListener el)


e.g. public void addKeyListener()

public void addTypeListener(TypeListener el)throws


java.util.TooManyListenersException

public void removeTypeListener(TypeListener el)

A listener is an object that is notified when an


event occurs.

It must register with one or more sources.

It must implement methods to receive and


process these notifications.

The methods that receive and process events


are defined in a set of interfaces found in
java.awt.event.

For example, the MouseMotionListener


interface defines two methods to receive
notifications when the mouse is dragged or
moved.

EventObject(java.util)
AWTEvent(java.awt)

EventObject contains two methods:


getSource( ) and toString()
The getSource( ) method returns the source
of the event.

general form : Object getSource( )


-The class AWTEvent, defined within the
java.awt package which is a sub class of
EventObject.
-AWTEvent is a superclass of all AWT events

Listeners are created by implementing one or

more of the interfaces defined by the


java.awt.event package.

When an event occurs, the event source invokes

the appropriate method defined by the listener


and provides an event object as its argument.

void actionPerformed(ActionEvent ae)

Void adjustmentValueChanged(AdjustmentEvent ae)

void componentResized(ComponentEvent ce)


void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)

void componentAdded(ContainerEvent ce)


Void componrntListener(ContainerEvrnt ce)
void componentRemoved(ContainerEvent ce)

void focusLost(FocusEvent fe)

void focusGained(FocusEvent fe)

void itemStateChanged(ItemEvent ie)

void keyPressed(KeyEvent ke)


void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

void mouseClicked(MouseEvent me)


void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

void mouseDragged(MouseEvent me)


void mouseMoved(MouseEvent me)

void mouseWheelMoved(MouseWheelEvent mwe)

void textChanged(TextEvent te)

void windowGainedFocus(WindowEvent we)


void windowLostFocus(WindowEvent we)

void windowActivated(WindowEvent we)


void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

void menuCanceled(MenuEvent e)
void menuDeselected(MenuEvent e)
void menuSelected(MenuEvent e)

You might also like