Chapter 11
Using Layout Managers and the Event Model
· How to use Layout Managers
· How to use BorderLayout, FlowLayout, and GridLayout.
· How to use Panels
· About advanced Layout Managers
I.
Layout Managers allow the programmer to align Components on the screen.
A. Every
Component has a default Layout Manager.
B. Layout
managers are interfaces.
II. The BorderLayout class can be used with any class that uses five
or fewer
Components. This is because it has only 5 positions: North,
South, East, West and Center.
A. To create an
applet that uses a BorderLayout five or less containers are
created, the Layout is set, and the containers are added. The
five areas of the
Container are labeled and assigned as "North",
"South", "East", "West", and
"Center". The Java statements in the class are:
ContainerType containterName = new ContainerType(String Label); (in
the class)
add(containerName, "North");
(Or East, West, etc. – in the init method).
B.
Empty containers are eliminated. The other areas of the BorderLayout are
eliminated and are filled
with the other areas.
III. FlowLayout
A.
The FlowLayout interface allows the programmer to position any Components
in the class in a
"flowing" order. The components are added in order dependant on the
order in which they are added. They are added top to bottom, left to right.
B. The
FlowLayout implementation of the add(Component) is to add all
Components based on size. The number of Components that actually
fit
depends on the size of the panel.
IV. GridLayout
A. The
GridLayout class allows you to place Component in a set number of
columns and rows. The
GridLayout class places each Component in a spot,
left to right, top to
bottom.
B. With a
GridLayout, the number of rows is the first argument and the number
of columns is the second
argument.
V. Panels
A. The Panel is
a child of the Container class, thus it is a Component that can
contain other Components.
Each panel can have its own Layout manager.
B. Panels can be
placed with a Layout manager. Each Panel can have its own
Layout manager, giving the
Programmer an almost infinite number of possible
screen arrangements.
C. Each Panel is
constructed by one of two constructors, with the default
LayoutManager the FlowLayout:
Panel panelName = new Panel( );
Panel panelName = new Panel(LayoutManager layoutname);
Each Component is added to the Panel with the add statement.
V. Advanced Layout Managers – There are advanced Layout managers
which are available to the programmer, and programmers may define
their own layout interfaces.
A. GridBagLayout
– The ability to place Components exactly where you want
them. The programmer must
size and place every Component.
B. CardLayout
– The ability to display Components as in a deck of cards, with
only one card visible at any
one time.
C. The null
Layout may be used to create specialized layouts.
Summary
The three
most used layout managers are the Border,
Flow and Grid layout managers.
- Border is default for Window, Frame and Dialog objects.
- FlowLayout is default for Panel objects.
The BorderLayout
class places Components in 5
distinct areas of the screen: North, South,
East, West and Center.
The FlowLayout manager places Components sequentially, based on
size.
Some layouts depend on the size of the data.
The GridLayout manager allows you to place Components within a
row and a column. The GridLayout takes as arguments the number of columns and
the number of rows.
Panels are "sub-windows" which can be individually
created and then assembled to create
the larger Window. Each Component must be added to a specific Panel.
Creating your own complex Layout Manager is possible, but rather
difficult.
Example FlowLayout:
// FlowLayoutDemo.java
// Demonstrating FlowLayout alignments.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FlowLayoutDemo extends JFrame
{
private JButton left, center, right;
private Container c;
private FlowLayout layout;
public FlowLayoutDemo()
{
super( "FlowLayout
Demo" );
layout = new
FlowLayout();
c = getContentPane();
c.setLayout( layout );
left = new JButton(
"Left" );
left.addActionListener
(
new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
layout.setAlignment( FlowLayout.LEFT );
// re-align attached components
layout.layoutContainer( c );
}
}
);
c.add( left );
center = new JButton(
"Center" );
center.addActionListener
(
new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
layout.setAlignment( FlowLayout.CENTER );
// re-align attached components
layout.layoutContainer( c );
}
}
);
c.add( center );
right = new JButton(
"Right" );
right.addActionListener
(
new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
layout.setAlignment( FlowLayout.RIGHT );
// re-align attached components
layout.layoutContainer( c );
}
}
);
c.add( right );
setSize( 300, 75 );
show();
}
public static void main( String args[] )
{
FlowLayoutDemo app = new FlowLayoutDemo();
app.addWindowListener
(
new WindowAdapter()
{
public void
windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}




Events
Events
· How
to use the AWT Event class methods
· Event methods higher up
in the inheritance hierarchy
· How to handle mouse
events
When designing a GUI program, the programmer must determine which
of the many event types the program should listen for. All events that need to
be listened to must have the Listener incorporated, either implemented as an
interface or derived from as an adapter.
The Listeners are interfaces; the Events are classes. Demonstrate
the difference between
the Listeners and the Events.
When using events, make sure the program imports the appropriate
classes. Since the import statement wildcard can only stand for classes and not
folders or directories, the event methods must be imported specifically with:
import.java.awt.event.*;
I. All event classes are subclasses of the EventObject class, which
is a child of the Object class.
A.
AWT Event is parent to these interfaces:
· ActionEvent
· AdjustmentEvent
· ComponentEvent, which is parent to:
· ContainerEvent
· FocusEvent
· InputEvent, which is parent to:
· KeyEvent
· MouseEvent.
· PaintEvent
· WindowEvent
· ItemEvent
· TextEvent
B. When the user
clicks, types, hits enter or moves the mouse, an action has occurred. In order
for the program to "hear" the action, the program must have
implemented the appropriate listener.
C. Listeners are
interfaces. All methods in the Listener are abstract and must be made concrete
(even if with no actual coding) in the class implementing the Listener.
Listeners with multiple methods have adapters which make all methods concrete
but with no executable code.
D. All
Components that need to be heard must be specifically added to the Listener with
the
componentName.addXXXListener(this);
II. AWT Event class methods
A. All events
are derived from the AWT Event class. Each Event has some useful methods. These
methods can be used if the Events are listened for with the appropriate
Listener.
B. Some examples
of methods include:
getStateChanged( ) Returns an integer for SELECTED or DESELECTED
getItem( ) Returns the Object selected
getX( ) Returns the x-coordinate of the Mouse Pointer
There are many other methods that return data from an event.
III. Other Methods
A. Events
inherit all of the concrete methods from parent and grandparent
classes.
B. Mouse events
are very important in GUI programming, as many events are initiated by the
movement of the mouse. By using the mouse event, one is not restricted to
Components such as Buttons or Checkboxes. The actual movement of the mouse can
be used to gather data from the user.
Example:
Create a Frame named FontFrame that holds four buttons with the
names of four different fonts. Draw "Dang" string using the font
that the user selects. Write a program to instantiate a FontFrame.
import java.awt.*;
import java.awt.event.*;
public class FontFrame extends Frame implements ActionListener
{
Button hButton = new Button
("Helvetica");
Button tButton = new Button ("Times
Roman");
Button cButton = new Button
("Courier");
Button sButton = new Button ("Sans
Serif");
Panel p = new Panel();
Font cFont = new Font ("Courier",
Font.PLAIN, 16);
Font hFont = new Font ("Helvetica",
Font.PLAIN, 16);
Font tFont = new Font ("TimesRoman",
Font.PLAIN, 16);
Font sFont = new Font ("SansSerif",
Font.PLAIN, 16);
public
FontFrame()
{
setLayout (new
GridLayout(2,3));
setTitle ("Font
Frame");
add (hButton);
add (tButton);
add (cButton);
add (sButton);
add (p);
hButton.addActionListener (this);
tButton.addActionListener (this);
cButton.addActionListener (this);
sButton.addActionListener (this);
}
public
void actionPerformed(ActionEvent e)
{
Graphics gr =
getGraphics();
if
(e.getSource()
== hButton)
{
gr.setFont(hFont);
gr.drawString("Dang",200,180);
}
else
if (e.getSource()
== tButton)
{
gr.setFont(tFont);
gr.drawString("Dang",200,200);
}
else
if (e.getSource()
== sButton)
{
gr.setFont(sFont);
gr.drawString("Dang",200,220);
}
else
{
gr.setFont(cFont);
gr.drawString("Dang",200,240);
}
}
}
import java.awt.*;
public class UseFontFrame
{
public static void main(String [ ] args)
{
FontFrame ff = new FontFrame();
ff.setSize(300,300);
ff.setVisible(true);
}
}

Section A
Using Layout Mangers
A layout manager is an interface class that is part of the JDK and aligns your components so they neither crowd each other nor overlap. The three most used layout are the following:
Use this layout when you have five or fewer components.
Use this layout when you want to arrange components in rows across the width of a container.
Use this layout when you want to arrange components into equal rows and columns.
An demonstration program of using BorderLayout
import java.applet.*;
import java.awt.*;
public class DemoBorder extends Applet
{
private Button nb = new Button("North Button");
private Button sb = new Button("South Button");
private Button eb = new Button("East Button");
private Button wb = new Button("West Button");
private Button cb = new Button("Center Button");
public void init()
{
setLayout(new BorderLayout());
add(nb,"North");
add(sb,"South");
add(eb,"East");
add(wb,"West");
add(cb,"Center");
}
}
A demonstration program that uses flowlayout.
import java.applet.*;
import java.awt.*;
public class DemoFlow extends Applet
{
private Button nb = new Button("North Button");
private Button sb = new Button("South Button");
private Button eb = new Button("East Button");
private Button wb = new Button("West Button");
private Button cb = new Button("Center Button");
public void init()
{
setLayout(new FlowLayout());
add(nb,"North");
add(sb,"South");
add(eb,"East");
add(wb,"West");
add(cb,"Center");
}
}
A demonstration program that uses flowlayout that align to the right
import java.applet.*;
import java.awt.*;
public class DemoFlowRight extends Applet
{
private Button nb = new Button("North Button");
private Button sb = new Button("South Button");
private Button eb = new Button("East Button");
private Button wb = new Button("West Button");
private Button cb = new Button("Center Button");
public void init()
{
setLayout(new FlowLayout(FlowLayout.RIGHT));
add(nb,"North");
add(sb,"South");
add(eb,"East");
add(wb,"West");
add(cb,"Center");
}
}
A demonstration program that uses GridLayout
import java.applet.*;
import java.awt.*;
public class DemoGrid extends Applet
{
private Button nb = new Button("North Button");
private Button sb = new Button("South Button");
private Button eb = new Button("East Button");
private Button wb = new Button("West Button");
private Button cb = new Button("Center Button");
public void init()
{
setLayout(new GridLayout(2,3,5,5));
add(nb,"North");
add(sb,"South");
add(eb,"East");
add(wb,"West");
add(cb,"Center");
}
}
Using the borderlayout, flowlayout, and gridlayout managers provides a limited number of screen arrangements. You can increase the number of possible component arrangement by using the panel class. A panel is similar to a window in that a panel is a surface on which you can place components.
When you create a Panel object, you can use one of the two constructors:
First, create the WesternPanel object:
import java.awt.*;
import java.awt.event.*;
public class WesternPanel extends Panel implements ActionListener
{
Button wyButton = new Button("Wyoming");
Button coButton = new Button("Colorado");
Button nvButton = new Button("Nevada");
Label infoLabel = new Label("Location Info ");
public WesternPanel()
{
setLayout(new GridLayout(2,2));
add(wyButton);
wyButton.addActionListener(this);
add(coButton);
add(nvButton);
add(infoLabel);
}
public void actionPerformed(ActionEvent e)
{
infoLabel.setText("Cody");
}
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class DemoRegion extends Applet
{
Panel np = new Panel();
Panel sp = new Panel();
Panel ep = new Panel();
Panel cp = new Panel();
WesternPanel wp = new WesternPanel();
private Button nb = new Button("North Button");
private Button sb = new Button("sorth Button");
private Button eb = new Button("East Button");
private Button cb = new Button("Center Button");
public void init()
{
setLayout(new BorderLayout());
add(nb,"North");
add(sb,"South");
add(eb, "East");
add(wp,"West");
add(cb, "Center");
}
}
import java.awt.*;
import java.awt.event.*;
public class KeyFrame extends Frame implements KeyListener
{
public KeyFrame()
{
setTitle("Key Frame");
addKeyListener(this);
}
public void keyPressed(KeyEvent e)
{
System.out.println("passed");
}
public void keyTyped(KeyEvent e)
{
System.out.println("typed");
}
public void keyReleased(KeyEvent e)
{
System.out.println("Released");
}
}
Next, create a UseKeyFram program
public class UseKeyFrame
{
public static void main(String[] args)
{
KeyFrame KFrame = new KeyFrame();
KFrame.setSize(250,50);
KFrame.setVisible(true);
}
}
First, create a KeyFrame2.java
import java.awt.*;
import java.awt.event.*;
public class KeyFrame2 extends Frame implements KeyListener
{
char key;
public KeyFrame2()
{
setTitle("Key Frame");
addKeyListener(this);
}
public void keyPressed(KeyEvent e)
{
System.out.println("passed");
}
public void keyTyped(KeyEvent e)
{
System.out.println("typed");
}
public void keyReleased(KeyEvent e)
{
System.out.println("Released");
key = (char)e.getKeyChar();
System.out.println("Key is " + key);
System.out.println("Next key is " + (char)(key + 1));
}
}
Next, use UseKeyFrame2.java
public class UseKeyFrame2
{
public static void main(String[] args)
{
KeyFrame2 KFrame = new KeyFrame2();
KFrame.setSize(250,50);
KFrame.setVisible(true);
}
}
To write a class that uses the ObjectEvent method getSource() with an ActionEvent
import java.awt.*;
import java.awt.event.*;
public class ButtonFrame extends Frame implements ActionListener
{
Button redButton = new Button("Red");
Button blueButton = new Button("Blue");
Button greenButton= new Button("Green");
public ButtonFrame()
{
setLayout(new FlowLayout());
setTitle("Button Frame");
redButton.addActionListener(this);
add(redButton);
blueButton.addActionListener(this);
add(blueButton);
greenButton.addActionListener(this);
add(greenButton);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == redButton)
setBackground(Color.red);
else if (e.getSource() == blueButton)
setBackground(Color.blue);
else setBackground(Color.green);
}
}
Next, create a UseButtonFrame program to test the ButtonFrame
public class UseButtonFrame
{
public static void main(String[] args)
{
ButtonFrame bFrame = new ButtonFrame();
bFrame.setSize(350, 250);
bFrame.setVisible(true);
}
}
Create a MouseFrame class:
import java.awt.*;
import java.awt.event.*;
public class MouseFrame extends Frame implements MouseListener
{
int x, y;
int size;
public MouseFrame()
{
setTitle("Mouse Frame");
addMouseListener(this);
}
public void mousePressed(MouseEvent e)
{
x = e.getX();
y = e.getY();
repaint();
}
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount() == 2)
size = 10;
else
size = 4;
repaint();
}
public void mouseEntered(MouseEvent e)
{
setBackground(Color.yellow);
}
public void mouseExited(MouseEvent e)
{
setBackground(Color.black);
}
public void mouseReleased(MouseEvent e)
{
}
public void paint(Graphics g)
{
g.drawOval(x -size, y -size, size * 2, size * 2);
}
}
public class UseMouseFrame
{
public static void main(String[] args)
{
MouseFrame mFrame = new MouseFrame();
mFrame.setSize(250,150);
mFrame.setVisible(true);
}
}