0% found this document useful (0 votes)
2 views62 pages

Java Unit 4 Notes_23_24

The document provides an overview of event handling in Java's AWT, detailing the roles of events, sources, and listeners. It explains the event-driven programming model, the delegation event model, and the necessary steps for handling mouse and keyboard events through listener interfaces. Additionally, it discusses the limitations of AWT components and provides examples of implementing mouse and key listeners in Java applications.

Uploaded by

vpvnspranay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views62 pages

Java Unit 4 Notes_23_24

The document provides an overview of event handling in Java's AWT, detailing the roles of events, sources, and listeners. It explains the event-driven programming model, the delegation event model, and the necessary steps for handling mouse and keyboard events through listener interfaces. Additionally, it discusses the limitations of AWT components and provides examples of implementing mouse and key listeners in Java applications.

Uploaded by

vpvnspranay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

198

Event Handling
.

Introduction:

The java.awt.event package provides many event classes and Listener interfaces for event
handling

Three kinds object used in event handling

• Event
• Source
• Listener

Events:
Changing the state of an object is known as an Event. For example, click on button, dragging
mouse etc.
Events to be generated are pressing a button, entering a character via the keyboard, selecting
an item in a list, and clicking the mouse.
Events may also occur that are not directly caused by interactions with a user interface.
For example, an event may be generated when a timer expires, a counter exceeds a value,a
software or h ardware failure occurs, or an operation is completed.

Event Sources:
A source is an object that generates an event.Sources may generate more than one type of
event. A source must register listeners in order for the listeners to receive notifications about
a specific type of event.

Each type of event has its own registration method.

Here is the general form:

public void addTypeListener(TypeListener el);

Here, Type is the name of the event, and el is a reference to the event listener.

For example, the method that registers a keyboard event listener is called addKeyListener( ).

The method that registers a mouse motion listener is called addMouseMotionListener( ).


199

When an event occurs, all registered listeners are notified and receive a copy of the event
object. This is known as multicasting the event. In all cases, notifications are sent only to
listeners that register to receive them.

A source must also provide a method that allows a listener to unregister an interest in a
specific type of event.

The general form of such a method is this:

public void removeTypeListener(TypeListener el);

Here, Type is the name of the event, and el is a reference to the event listener.

For example,to remove a keyboard listener, you would call removeKeyListener( ).

Event Listerners:
A listener is an object that is notified when an event occurs.

It has two major requirements.

 First, it must have been registered with one or more sources to receive notifications
about specific types of events.
 Second, 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. Any object may receive and process one
or both of these events if it provides an implementation of this interface

The Delegation event model


Java adopts the so-called "Event-Driven" (or "Event-Delegation") programming model for
event-handling, similar to most of the visual programming languages, such as Visual Basic.

In event-driven programming, a piece of event-handling codes is executed (or called back by


the graphics subsystem) when an event was fired in response to an user input (such as
clicking a mouse button or hitting the ENTER key in a text field).

Call Back methods

In the above examples, the method actionPerformed() is known as a call back method. In
other words, you never invoke actionPerformed() in your codes explicitly. The
actionPerformed() is called back by the graphics subsystem under certain circumstances in
response to certain user actions.
200

Source, Event and Listener Objects

The AWT's event-handling classes are kept in package java.awt.event.

Three kinds of objects are involved in the event-handling: a source, listener(s) and an event
object.

The source object (such as Button and Textfield) interacts with the user. Upon triggered, the
source object creates an event object to capture the action (e.g., mouse-click x and y, texts
entered, etc). This event object will be messaged to all the registered listener object(s), and an
appropriate event-handler method of the listener(s) is called-back to provide the response. In
other words, triggering a source fires an event to all its listener(s), and invoke an appropriate
event handler of the listener(s).

To express interest for a certain source's event, the listener(s) must be registered with the
source. In other words, the listener(s) "subscribes" to a source's event, and the source
"publishes" the event to all its subscribers upon activation. This is known as subscribe-
publish or observable-observer design pattern.

Figure 12.1: The Delegation event model

The sequence of steps is illustrated above:


201

1. The source object registers its listener(s) for a certain type of event.(A source fires an
event when
triggered. For example, clicking a Button fires an ActionEvent, clicking a mouse
button fires MouseEvent, typing a key fires KeyEvent, and etc.).
2. The source is triggered by a user.
3. The source create a XxxEvent object, which encapsulates the necessary information
about the activation. For example, the (x, y) position of the mouse pointer, the text
entered, etc.
4. Finally, for each of the XxxEvent listeners in the listener list, the source invokes the
appropriate handler on the listener(s), which provides the programmed response

Event Classes
At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the
superclass for all events. Its one constructor is shown here:

EventObject(Object src);

Here, src is the object that generates this event.

EventObject contains two methods: getSource( ) and toString( ).

General form is shown here:

Object getSource( ); ---- returns the source of the event

String toString( ); --- returns the string equivalent of the event

List of Event Classes and Listener Interfaces

Source Event Classes Listener Interfaces


Button,menuIteam,
ActionEvent ActionListener
TextField
Mouse MouseListener and
MouseEvent
MouseMotionListener

MouseWheelEvent MouseWheelListener
Keyboard KeyEvent KeyListener
CheckBox,Choice,List ItemEvent ItemListener
TextField,TextArea TextEvent TextListener
AdjustmentEvent AdjustmentListener
Window WindowEvent WindowListener
Component ComponentEvent ComponentListener
202

Container ContainerEvent ContainerListener


FocusEvent FocusListener

Handling Mouse and Keyboard Events


Steps to perform EventHandling
Following steps are required to perform event handling :
1. Implement the Listener interface and overrides its methods
2. Register the component with the Listener
For registering the component with the Listener, many classes provide the registration
methods.
Component Registration Methods
Button public void addActionListener(ActionListener a){}
MenuItem public void addActionListener(ActionListener a){}
TextField public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea public void addTextListener(TextListener a){}
Checkbox public void addItemListener(ItemListener a){}
Choice public void addItemListener(ItemListener a){}
List public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}

Mouse Event:
 A MouseEvent is fired when you press, release, or click (press followed by release) a
mouse-button (left or right button) at the source object; or position the mouse-pointer
at (enter) and away (exit) from the source object.
 A MouseEvent listener must implement either MouseListener interface or
MouseMotionListener interface or both dependending a action.
 The Java MouseListener is notified whenever you change the state of mouse
 The Java MouseMotionListener is notified whenever you move or drag mouse

Java MouseListener Interface

 The Java MouseListener is notified whenever you change the state of mouse. It is
notified against MouseEvent.
 The MouseListener interface is found in java.awt.event package.
203

It has five methods.

Methods Description
public abstract void Called-back when the mouse-button has
mouseClicked(MouseEvent e); been clicked on the
source.
public abstract void Called-back when the mouse-pointer has
mouseEntered(MouseEvent e); entered the source
public abstract void mouseExited(MouseEvent Called-back when the mouse-pointer has
e); exited the source
public abstract void mousePressed(MouseEvent Called-back when a mouse-button has been
e); pressed on the source

public abstract void Called-back when a mouse-button has been


mouseReleased(MouseEvent e); released on the source

Note: A mouse-click invokes mousePressed(), mouseReleased() and mouseClicked().

Java MouseMotionListener Interface

The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified
against MouseEvent. The MouseMotionListener interface is found in java.awt.event package.
It has two methods.

Methods of MouseMotionListener interface


The signature of 2 methods found in MouseMotionListener interface is given below:
1. public abstract void mouseDragged(MouseEvent e);

2. public abstract void mouseMoved(MouseEvent e);


204

Example on Java Mouse Event/ Example on Mouse listener interface:

import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}

Output:
205

Example on Java MouseMotionListener

import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements
MouseMotionListener
{
MouseMotionListenerExample(){
addMouseMotionListener(this);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.Black);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}

public static void main(String[] args) {


new MouseMotionListenerExample();
}
}

Output:
206

Example On Key Events/Key Listeners

// importing awt libraries


import java.awt.*;
import java.awt.event.*;

public class KeyListenerExample extends Frame implements KeyListener {

Label l;
TextArea area;
// class constructor
KeyListenerExample() {
// creating the label
l = new Label();
// setting the location of the label in frame
l.setBounds (20, 50, 100, 20);
// creating the text area
area = new TextArea();
// setting the location of text area
area.setBounds (20, 80, 300, 300);
// adding the KeyListener to the text area
area.addKeyListener(this);
// adding the label and text area to the frame
add(l);
add(area);
// setting the size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// overriding the keyPressed() method of KeyListener interface where we set the text of the
label when key is pressed
public void keyPressed (KeyEvent e) {
l.setText ("Key Pressed");
}
// overriding the keyReleased() method of KeyListener interface where we set the text of the
label when key is released
public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
}
// overriding the keyTyped() method of KeyListener interface where we set the text of the
label when a key is typed
207

public void keyTyped (KeyEvent e) {


l.setText ("Key Typed");
}
// main method
public static void main(String[] args) {
new KeyListenerExample();
}
}
Output:

Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If you inherit
the adapter class, you will not be forced to provide the implementation of all the methods of
listener interfaces. So it saves code.

The Adapter classes with their corresponding listener interfaces are given below

Adapter class Listener interface


WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
208

MouseMotionAdapter MouseMotionListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener

Example on Java KeyAdapter :

import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter{
Label l; TextArea area; Frame f;
KeyAdapterExample(){
f=new Frame("Key Adapter");
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
f.add(l);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
area.addKeyListener(this);
}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public static void main(String[] args) {
new KeyAdapterExample();
}
}

Output:
209

Example on Java MouseAdapter :

import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Label l;
Frame f;
MouseAdapterExample(){
f=new Frame("MOUSE Adapter");
l=new Label();
l.setBounds(20,50,200,20);
f.add(l);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
l.addMouseListener(this);
}
public void mousePressed(MouseEvent e)
{
l.setText("mouse Pressed");
}

public static void main(String[] args) {


new MouseAdapterExample();
}
}

Output:
210

AWT Introduction
Computer users today expect to interact with their computers using a graphical user
interface (GUI). Java can be used to write GUI programs ranging from simple applets which
run on a Web page to sophisticated stand-alone applications.

The Basic GUI Application

There are two basic types of GUI program in Java:

•Applets.

•Stand-Alone Applications

An applet is a program that runs in a rectangular area on a Web page.

A stand-alone application is a program that runs on its own, without depending on a Web
browser. You’ve been writing stand-alone applications all along. Any class that has a main()
routine defines a stand-alone application; running the program just means executing this
main() routine.

The user uses a mouse and keyboard to interact with GUI components such as windows,
menus, buttons, check boxes, text input boxes, scroll bars, and so on..

11.2 Limitations of AWT


The AWT defines a basic set of controls, windows, and dialog boxes that support a usable,
but limited graphical interface. One reason for the limited nature of the AWT is that the look
and feel of a component is defined by the platform, not by java.

Because the AWT components use native code they are referred to as heavy weight.

The use of native peers led to several problems.

 First, because of variations between operating systems, a component might look, or


even act, differently on different platforms. This variability threatened java’s
philosophy: write once, run anywhere.
 Second, the look and feel of each component was fixed and could not be changed.
 Third,the use of heavyweight components caused some frustrating restrictions.
211

Summary on limitations of AWT

AWT supports limited number of GUI components

AWT component are Heavy weight components

AWT components are developed by using platform specific code

AWT components behave differently in different Operating Systems.

AWT Components
A Component is an abstract super class for GUI controls and it represents an object with
graphical representation

Figure 11.2 : Hierarchy of Components

Every AWT controls inherits properties from Component class


212

Figure 11.2 : Representation of Components

List of Components:

Component Description

Label The easiest control to use is a label. A label is an object of type Label,
and it contains a string, which it displays. Labels are passive controls
that do not support any interaction with the user. Label defines the
following constructors

Button This class creates a labelled button.

Check Box A check box is a graphical component that can be in either an on (true)
or off (false) state.

Check Box The CheckboxGroup class is used to group the set of checkbox.
Group

List The List component presents the user with a scrolling list of text items.

Text Field A TextField object is a text component that allows for the editing of a
single line of text.

Text Area A TextArea object is a text component that allows for the editing of a
multiple lines of text.

Choice A Choice control is used to show pop up menu of choices. Selected


choice is shown on the top of the menu.

Canvas A Canvas control represents a rectangular area where application can


draw something or can receive inputs created by user.

Image An Image control is superclass for all image classes representing


213

graphical images.

Scroll Bar A Scrollbar control represents a scroll bar component in order to enable
user to select from range of values.

Dialog A Dialog control represents a top-level window with a title and a border
used to take some form of input from the user.

File Dialog A FileDialog control represents a dialog window from which the user
can select a file.

Commonly used Methods of Component class:

Method Description
public void add(Component c) inserts a component on this component.

public void setSize(intwidth,int height) sets the size (width and height) of the
component.
public void setLayout(LayoutManager m) defines the layout manager for the
component.

Component:Labels
The easiest control to use is a label. A label is an object of type Label, and it contains a
string,which it displays. Labels are passive controls that do not support any interaction with
theuser.
Constructor of Label
Constructors Description
Label( ) throws HeadlessException creates a blank label.
Label(String str) throws HeadlessException creates a label that contains thestring
specified by str. This string is left-justified
Label(String str, int how) throws creates a label that contains the string
specified by str using the alignment specified
HeadlessException
by how(Label.LEFT,
Label.RIGHT, orLabel.CENTER)
Methods of Label:

Method Description
void setText(String str) For setText( ), str specifies the new label
String getText( ) For getText( ), the current label is returned.
214

Example on Label:

import java.awt.*;

public class LabelExample {


public static void main(String args[]){

// creating the object of Frame class and Label class


Frame f = new Frame ("Label example");
Label l1, l2;

// initializing the labels


l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");

// set the location of label


l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);

// adding labels to the frame


f.add(l1);
f.add(l2);

// setting size, layout and visibility of frame


f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
215

Component:Buttons
A push button is a component thatcontains a label and that generates an event when it is
pressed. Push buttons are objects oftype Button

Constructor of Button

Constructors Description
Button( ) throws HeadlessException The first version creates an empty button.

Button(String str) throws HeadlessException The second creates a button that contains str
as a label
Methods of Button:

Method Description
void setLabel(String str) After a button has been created, you can set
its label,Here, str becomes the new label for
the button
String getLabel( ) You can retrieve its label

Example on Button component:

import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {

// create instance of frame with the label


Frame f = new Frame("Button Example");

// create instance of button with label


Button b = new Button("Click Here");

// set the position for the button in frame


b.setBounds(50,100,80,30);

// add button to the frame


f.add(b);
// set size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
216

Component: Canvas

The Canvas class controls and represents a blank rectangular area where the application can
draw or trap input events from the user. It inherits the Component class.

AWT Canvas class Declaration

1. public class Canvas extends Component implements Accessible

Canvas Class Constructors

Sr. Constructor Description


no.

1. Canvas() It constructs a new Canvas.

2. Canvas(GraphicConfiguration It constructs a new Canvas with the given Graphic


config) Configuration object.

Class methods

Sr. Method name Description


no.

1. void addNotify() It creates the canvas's peer.


217

2. void createBufferStrategy (int numBuffers) It creates a new multi buffering


strategies on the particular component.

3. void createBufferStrategy (int numBuffers, It creates a new multi buffering


BufferCapabilities caps) strategies on the particular component
with the given buffer capabilities.

4. AccessibleContextgetAccessibleContext() It gets the accessible context related to


the Canvas.

5. BufferStrategygetBufferStrategy() It returns the buffer strategy used by the


particular component.

6. void paint(Graphics g) It paints the canvas with given Graphics


object.

7. void pdate(Graphics g) It updates the canvas with given


Graphics object.

Example on Canvas:
// importing awt class
import java.awt.*;

// class to construct a frame and containing main method


public class CanvasExample
{
// class constructor
public CanvasExample()
{

// creating a frame
Frame f = new Frame("Canvas Example");
// adding canvas to frame
f.add(new MyCanvas());

// setting layout, size and visibility of frame


f.setLayout(null);
f.setSize(400, 400);
218

f.setVisible(true);
}

// main method
public static void main(String args[])
{
new CanvasExample();
}
}

// class which inherits the Canvas class


// to create Canvas
class MyCanvas extends Canvas
{
// class constructor
public MyCanvas() {
setBackground (Color.GRAY);
setSize(300, 200);
}

// paint() method to draw inside the canvas


public void paint(Graphics g)
{

// adding specifications
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
219

Component: Scrollbars
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a
GUI component allows us to see invisible number of rows and columns.

It can be added to top-level container like Frame or a component like Panel. The Scrollbar
class extends the Component class.

AWT Scrollbar Class Declaration

public class Scrollbarextends Component implements Adjustable, Accessible

Scrollbar Class Fields

The fields of java.awt.Image class are as follows:

o static int HORIZONTAL - It is a constant to indicate a horizontal scroll bar.

o static int VERTICAL - It is a constant to indicate a vertical scroll bar.

Scrollbar Class Constructors

Sr. Constructor Description


no.

1 Scrollbar() Constructs a new vertical scroll bar.

2 Scrollbar(int orientation) Constructs a new scroll bar with the specified


orientation.

3 Scrollbar(int orientation, int Constructs a new scroll bar with the specified
value, int visible, int minimum, int orientation, initial value, visible amount, and
maximum) minimum and maximum values.

Where the parameters,

orientation:specifiey whether the scrollbar will be horizontal or vertical.

Value: specify the starting position of the knob of Scrollbar on its track.

Minimum: specify the minimum width of track on which scrollbar is moving.


220

Maximum: specify the maximum width of track on which scrollbar is moving.

Scrollbar Class Methods

Sr. Method name Description


no.

1. void addAdjustmentListener It adds the given adjustment listener to


(AdjustmentListener l) receive instances of AdjustmentEvent
from the scroll bar.

2. void addNotify() It creates the peer of scroll bar.

3. int getBlockIncrement() It gets the block increment of the scroll


bar.

4. int getMaximum() It gets the maximum value of the scroll


bar.

5. int getMinimum() It gets the minimum value of the scroll


bar.

6. int getOrientation() It returns the orientation of scroll bar.

7. int getUnitIncrement() It fetches the unit increment of the


scroll bar.

8. int getValue() It fetches the current value of scroll


bar.

9. int getVisibleAmount() It fetches the visible amount of scroll


bar.

10. booleangetValueIsAdjusting() It returns true if the value is in process


of changing where action results are
221

being taken by the user.

11. protected String paramString() It returns a string representing the


state of Scroll bar.

12. protected void processAdjustmentEvent It processes the adjustment event


(AdjustmentEvent e) occurring on scroll bar by dispatching
them to any registered
AdjustmentListener objects.

13. protected void processEvent(AWTEvent e) It processes the events on the scroll bar.

14. void removeAdjustmentListener It removes the given adjustment


(AdjustmentListener l) listener. Thus it no longer receives the
instances of AdjustmentEvent from the
scroll bar.

15. void setBlockIncrement(int v) It sets the block increment from scroll


bar.

16. void setMaximum (int newMaximum) It sets the maximum value of the scroll
bar.

17. void setMinimum (int newMinimum) It sets the minimum value of the scroll
bar.

18. void setOrientation (int orientation) It sets the orientation for the scroll bar.

19. void setUnitIncrement(int v) It sets the unit increment for the scroll
bar.

20. void setValue (int newValue) It sets the value of scroll bar with the
given argument value.

21. void setValueIsAdjusting (boolean b) It sets the valueIsAdjusting property to


scroll bar.
222

22. void setValues (int value, int visible, int It sets the values of four properties for
minimum, int maximum) scroll bar: value, visible amount,
minimum and maximum.

23. void setVisibleAmount (int newAmount) It sets the visible amount of the scroll
bar.

24. AccessibleContextgetAccessibleContext() It gets the accessible context related to


the scroll bar.

25. AdjustmentListener[] It returns an array of al lthe


getAdjustmentListeners() adjustment listeners registered on the
scroll bar.

26. T[] getListeners(Class listenerType) It returns an array if all objects that


are registered as FooListeners on the
scroll bar currently.

Example on ScrollBar:

// importing awt package


import java.awt.*;

public class ScrollbarExample1 {

// class constructor
ScrollbarExample1() {

// creating a frame
Frame f = new Frame("Scrollbar Example");
// creating a scroll bar
Scrollbar s = new Scrollbar();

// setting the position of scroll bar


s.setBounds (100, 100, 50, 100);

// adding scroll bar to the frame


f.add(s);
223

// setting size, layout and visibility of frame


f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}

// main method
public static void main(String args[]) {
new ScrollbarExample1();
}
}
224

Java AWT Scrollbar Example with AdjustmentListener

In the following example, we are creating a Scrollbar and adding it into the Frame. Here, we
are using addAdjustmentListener() method of Scrollbar class which receives the instances of
AdjustmentEvent and eventually we display it in the form of Label.

// importing necessary packages


import java.awt.*;
import java.awt.event.*;

public class ScrollbarExample2 {

// class constructor
ScrollbarExample2() {
// creating a Frame with a title
Frame f = new Frame("Scrollbar Example");

// creating a final object of Label


final Label label = new Label();

// setting alignment and size of label object


label.setAlignment(Label.CENTER);
label.setSize(400, 100);

// creating a final object of Scrollbar class


final Scrollbar s = new Scrollbar();

// setting the position of scroll bar


s.setBounds(100, 100, 50, 100);

// adding Scrollbar and Label to the Frame


f.add(s);
f.add(label);

// setting the size, layout, and visibility of frame


f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);

// adding AdjustmentListener to the scrollbar object


s.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
label.setText("Vertical Scrollbar value is:"+ s.getValue());
}
});
}

// main method
225

public static void main(String args[]){


new ScrollbarExample2();
}
}

TextComponents

1. Text Field
2. Text Area

TextField

The TextField class implements a single-line text-entry area, usually called an edit
control.Text fields allow the user to enter strings and to edit the text using the arrow keys, cut
and paste keys, and mouse selections. TextField is a subclass of TextComponent

Constructor of TextField

Constructors Description

TextField( ) creates a default text field

TextField(int numChars) creates a text field that is numChars characters


wide.

TextField(String str) initializes the text field with the string


contained in.

TextField(String str, int numChars) creates a text field that the string contained in
226

with

numChars characters wide

Methods of TextField

Method Description

String getText( ) To obtain the string currently contained in the


text field

void setText(String str) To set the text Here, str is the new string.

String getSelectedText( ) program can obtain the currently selected text

void select(int startIndex, int endIndex) The user can select a portion of the text in a
text field. Also, you can select a portion of
text under program control. The select(
)method selects the charactersbeginning at
startIndex and ending at endIndex–1.

booleanisEditable( ) returns true if the text may be changed and


false if not

void setEditable(booleancanEdit) if canEdit is true, the text may be changed. If


it is false, the text cannot be altered

Example programming:

// importing AWT class


import java.awt.*;
public class TextFieldExample {
// main method
public static void main(String args[]) {
// creating a frame
Frame f = new Frame("TextField Example");

// creating objects of textfield


TextField t1, t2;
// instantiating the textfield objects
// setting the location of those objects in the frame
t1 = new TextField("Welcome to Java programming.");
t1.setBounds(50, 100, 200, 30);
t2 = new TextField("AWT Tutorial");
t2.setBounds(50, 150, 200, 30);
// adding the components to frame
f.add(t1);
227

f.add(t2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

TextArea

Sometimes a single line of text input is not enough for a given task. To handle these
situations,the AWT includes a simple multiline editor called TextArea

Constructor of TextArea

Constructors Description

TextArea( ) throws HeadlessException Create a text Area

TextArea(int numLines, int numChars) Here, numLines specifies the height, in lines, of the
text area, and numChars specifies its width,in
228

throws HeadlessException characters.

TextArea(String str) throws Initial text can be specified by str


HeadlessException

TextArea(String str, int numLines, int Initial text can be specified by strHere, numLines
numChars) throws HeadlessException specifies the height, in lines, of the text area, and
numChars specifies its width,in characters

TextArea(String str, int numLines, int you can specify the scroll bars that you want the
numChars, int sBars) throws control to have. sBars must be one of these values:
HeadlessException
SCROLLBARS_BOTH, SCROLLBARS_NONE,

SCROLLBARS_HORIZONTAL_ONLY,
SCROLLBARS_VERTICAL_ONLY

Methods of TextArea

Method Description

void append(String str) appends the string specified by str to the end
of the current text

void insert(String str, int index) inserts the string passed in str at the specified
index

void replaceRange(String str, int startIndex, It replaces the characters from startIndex to
int endIndex) endIndex–1, with the replacement text passed
in str
229

Example program on TextArea:

//importing AWT class


import java.awt.*;
public class TextAreaExample
{
// constructor to initialize
TextAreaExample() {
// creating a frame
Frame f = new Frame();
// creating a text area
TextArea area = new TextArea("Welcome to java programming");
// setting location of text area in frame
area.setBounds(10, 30, 300, 300);
// adding text area to frame
f.add(area);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new TextAreaExample();
}
}

Output:
230

Component:Check Box
A check box is a control that is used to turn an option on or off. It consists of a small box that
can either contain a check mark or not. There is a label associated with each check box that
describes what option the box represents. You change the state of a check box by clicking on
it. Check boxes can be used individually or as part of a group. Check boxes are objects of the
Checkbox class.

Constructor of Check Box

Constructors Description
Checkbox( ) throws HeadlessException creates a check box whose label is initially
blank. The state of the check box
isunchecked.
Checkbox(String str) throws creates a check box whose label is
HeadlessException specified by str. The state of the check box
is unchecked
Checkbox(String str, boolean on) throws set the initial state of the checkbox. If on
HeadlessException is true, the check box is initially checked;
otherwise, it is cleared.
Checkbox(String str, boolean on, create a check box whose label is
CheckboxGroupcbGroup) throws specified by str and whose group is
HeadlessException specified by cbGroup. If this check box is
Checkbox(String str, not part of a group, then cbGroup must be
CheckboxGroupcbGroup, boolean on) throws null
HeadlessException The value of on determines the initial state
of the check box

Methods of Check Box:

Method Description
booleangetState( ) To retrieve the current state of a check box
void setState(boolean on) To set its state,Here, if on is true, the box is
checked. If it is false, the box is cleared

String getLabel( ) You can obtain the current label associated


with a check box
void setLabel(String str) To set the label,The string passed in str
becomes the new label associated with the
invoking check box
231

Component:CheckboxGroup
Example on CheckBox component:

// importing AWT class


import java.awt.*;
public class CheckboxExample1
{
// constructor to initialize
CheckboxExample1() {
// creating the frame with the title
Frame f = new Frame("Checkbox Example");
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
// setting location of checkbox in frame
checkbox2.setBounds(100, 150, 50, 50);
// adding checkboxes to frame
f.add(checkbox1);
f.add(checkbox2);

// setting size, layout and visibility of frame


f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main (String args[])
{
new CheckboxExample1();
}
}
232

It is possible to create a set of mutually exclusive check boxes in which one and only one
check box in the group can be checked at any one time. These check boxes are often called
radio buttons

Methods of CheckboxGroup

Method Description
Checkbox getSelectedCheckbox( ) You can determine which check box in a
group is currently selected
void setSelectedCheckbox(Checkbox which) You can set a check boxHere, which is the
check box that you want to be selected.
The previously selected check box will be
turned off

Example on CheckBoxGroup:

import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroupcbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
233

Component:Choice
The Choice class is used to create a pop-up list of items from which the user may choose.

Thus, a Choice control is a form of menu. When inactive, a Choice component takes up only
enough space to show the currently selected item. When the user clicks on it, the whole list of
choices pops up, and a new selection can be made.

Each item in the list is a string that appears as a left-justified label in the order it is added to
the Choice object.

Choice only defines the default constructor, which creates an empty list.

void add(String name); To add a selection to the list,

Here, name is the name of the item being added. Items are added to the list in the order
inwhich calls to add( ) occur.

Methods of Choice

Method Description
int getItemCount( ) To obtain the number of items in the list
void select(int index) You can set the currently selected item with a zero-
based integer index
void select(String name) You can set the currently selected item with a string
that will match a name in the list
String getItem(int index) you can obtain the name associated with the item at that
index
Here, index specifies the index of the desired item
String getSelectedItem( ) returns a string containing the name of the item
int getSelectedIndex( ) returns the index of the item. The first item is at index
0By default,the first item added to the list is selected
234

Example on Choice:
// importing awt class
import java.awt.*;
public class ChoiceExample1 {

// class constructor
ChoiceExample1() {

// creating a frame
Frame f = new Frame();

// creating a choice component


Choice c = new Choice();

// setting the bounds of choice menu


c.setBounds(100, 100, 75, 75);

// adding items to the choice menu


c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
// adding choice menu to frame
f.add(c);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}

// main method
public static void main(String args[])
{
new ChoiceExample1();
}
}
235

Component:Lists
The List class provides a compact, multiple-choice, scrolling selection list. Unlike theChoice
object, which shows only the single selected item in the menu, a List object can be
constructed to show any number of choices in the visible window. It can also be created to
allow multiple selections.

Constructor of Lists

Constructors Description
List( ) throws HeadlessException The first version creates a List control that
allows only one item to be selected at any
onetime.
List(int numRows) throws In the second form, the value of numRows
HeadlessException specifies the number of entries in the list
that will always be visible (others can be
scrolled into view as needed).
List(int numRows, In the third form, if multipleSelect is true,
booleanmultipleSelect) throws then the user may select two or more items
at a time. If it is false, then only one item
HeadlessException
may be selected

Methods of Lists

Method Description
void add(String name) adds items to the end of the list
void add(String name, int adds the item at the index specified by index. Indexing
index) begins at zero--You can specify –1 to add the item to the
end of the list
String[ ] getSelectedItems() returns an array containing the names of the currently
selected items
int[ ] getSelectedIndexes( ) returns an array containing the indexes of the currently
selected items
int getItemCount( ) To obtain the number of items in the list,
void select(int index) You can set the currently selected item
String getItem(int index) you can obtain the name associated with the item
Here, index specifies the index of the desired item
236

Example on List:

// importing awt class


import java.awt.*;

public class ListExample1


{
// class constructor
ListExample1() {
// creating the frame
Frame f = new Frame();
// creating the list of 5 rows
List l1 = new List(5);

// setting the position of list component


l1.setBounds(100, 100, 75, 75);

// adding list items into the list


l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");

// adding the list to frame


f.add(l1);

// setting size, layout and visibility of frame


f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}

// main method
public static void main(String args[])
{
new ListExample1();
}
}
Output:
237

AWT Panel

The Panel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the Container class.

It doesn't have title bar.

AWT Panel class declaration


public class Panel extends Container implements Accessible

Panel Example
import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
238

}
}

JScrollPane

A JscrollPane is used to make scrollable view of a component. When screen size is limited,
we use a scroll pane to display a large component or a component whose size can change
dynamically.

Constructors
Constructor Purpose

JScrollPane() It creates a scroll pane. The Component


parameter, when present, sets the scroll pane's
client. The two int parameters, when present, set
JScrollPane(Component)
the vertical and horizontal scroll bar policies
(respectively).
JScrollPane(int, int)
239

JScrollPane(Component,
int, int)

Useful Methods

Modifier Method Description

void setColumnHeaderView(Component) It sets the column header for the scroll pane.

void setRowHeaderView(Component) It sets the row header for the scroll pane.

void setCorner(String, Component) It sets or gets the specified corner. The int parameter
specifies which corner and must be one of the
following constants defined in ScrollPaneConstants:
Component getCorner(String) UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

void setViewportView(Component) Set the scroll pane's client.


240

Example on JScrollPane
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;

public class JScrollPaneExample {


private static final long serialVersionUID = 1L;

private static void createAndShowGUI() {

// Create and set up the window.


final JFrame frame = new JFrame("Scroll Pane Example");

// Display the window.


frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// set flow layout for the frame


frame.getContentPane().setLayout(new FlowLayout());

JTextArea textArea = new JTextArea(20, 20);


JScrollPane scrollableTextArea = new JScrollPane(textArea);

scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBA
R_ALWAYS);

scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AL
WAYS);

frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
241

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {


createAndShowGUI();
}
});
}
}

Dialog

java AWT Dialog


The Dialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Window class.

Unlike Frame, it doesn't have maximize and minimize buttons.

Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons
but Dialog doesn't have.
242

AWT Dialog class declaration


public class Dialog extends Window

N. Constructor & Description

Dialog(Dialog owner)
1 Constructs an initially invisible, modeless Dialog with the specified owner
Dialog and an empty title.

Dialog(Dialog owner, String title)


2 Constructs an initially invisible, modeless Dialog with the specified owner
Dialog and title.

Dialog(Dialog owner, String title, boolean modal)


3 Constructs an initially invisible Dialog with the specified owner Dialog, title,
and modality.

Dialog(Dialog owner, String title, boolean modal, GraphicsConfiguration


gc)
4
Constructs an initially invisible Dialog with the specified owner Dialog, title,
modality and GraphicsConfiguration.

Dialog(Frame owner)
5 Constructs an initially invisible, modeless Dialog with the specified owner
Frame and an empty title.

S.N. Method & Description

void addNotify()
1
Makes this Dialog displayable by connecting it to a native screen resource.

AccessibleContext getAccessibleContext()
2
Gets the AccessibleContext associated with this Dialog.

Dialog.ModalityType getModalityType()
3
Returns the modality type of this dialog.

String getTitle()
4
Gets the title of the dialog.
243

void hide()
5
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).

boolean isModal()
6
Indicates whether the dialog is modal.

boolean isResizable()
7
Indicates whether this dialog is resizable by the user.

boolean isUndecorated()
8
Indicates whether this dialog is undecorated.

protected String paramString()


9
Returns a string representing the state of this dialog.

void setModal(boolean modal)


10
Specifies whether this dialog should be modal.

void setModalityType(Dialog.ModalityType type)


11
Sets the modality type for this dialog.

void setResizable(boolean resizable)


12
Sets whether this dialog is resizable by the user.

void setTitle(String title)


13
Sets the title of the Dialog.

void setUndecorated(boolean undecorated)


14
Disables or enables decorations for this dialog.

void setVisible(boolean b)
15
Shows or hides this Dialog depending on the value of parameter b.

void show()
16
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).

void toBack()
17 If this Window is visible, sends this Window to the back and may cause it
to lose focus or activation if it is the focused or active Window.
244

Example1:
Java AWT Dialog Example
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
245

Example 2 on Dialog:
import javax.swing.*;

class SimpleDialog{

public static void main(String args[]){


JFrame frame = new JFrame("Main Window");

JOptionPane.showMessageDialog(frame, "Message for the dialog box goes


here.","Error", JOptionPane.ERROR_MESSAGE);

frame.setSize(350,350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:

MenuBar Class
AWT MenuBar

The MenuBar class helps manage the menu bar of a particular frame. The menu bar handles the
menu items that are a part of it. It helps set keyboard shortcuts for easy access and passes them
along to its child menus.

The MenuBar class provides menu bar bound to a frame and is platform specific.

Class declaration

Following is the declaration for java.awt.MenuBar class:


246

public class MenuBar


extends MenuComponent
implements MenuContainer, Accessible

Class constructors
S.N. Constructor & Description

MenuBar()
1
Creates a new menu bar.

Functions
247

Example On MenuBar

import java.awt.*;

class MenuExample

MenuExample(){

Frame f= new Frame("Menu and MenuItem Example");

MenuBar mb=new MenuBar();

Menu menu=new Menu("Menu");

Menu submenu=new Menu("Sub Menu");

MenuItem i1=new MenuItem("Item 1");

MenuItem i2=new MenuItem("Item 2");

MenuItem i3=new MenuItem("Item 3");

MenuItem i4=new MenuItem("Item 4");

MenuItem i5=new MenuItem("Item 5");

menu.add(i1);

menu.add(i2);

menu.add(i3);

submenu.add(i4);

submenu.add(i5);

menu.add(submenu);

mb.add(menu);

f.setMenuBar(mb);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

}
248

public static void main(String args[])

new MenuExample();

Graphics

Java AWT Graphics


Graphics is an abstract class provided by Java AWT which is used to draw or paint on the
components. It consists of various fields which hold information like components to be painted, font,
color, XOR mode, etc., and methods that allow drawing various shapes on the GUI components.
Graphics is an abstract class and thus cannot be initialized directly. Objects of its child classes can be
obtained in the following two ways.

1. Inside paint() or update() method

It is passed as an argument to paint and update methods and therefore can be accessed inside these
methods. paint() and update() methods are present in the Component class and thus can be overridden
for the component to be painted.

void paint(Graphics g)

void update(Graphics g)
249

example on Graphics
import java.awt.*;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

public class GraphicsDemo extends Frame {

public GraphicsDemo()

setVisible(true);

setSize(300, 300);

addWindowListener(new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e)

System.exit(0);

});

public void paint(Graphics g)

g.drawOval(50, 100, 50, 30);

g.fillOval(120, 100, 50, 30);

g.drawOval(50, 150, 50, 50);

g.fillOval(120, 150, 50, 50);

}
250

public static void main(String[] args)

new GraphicsDemo();

Output:
251

Layout Manager
A container has a so‐called layout manager to arrange its components. The layout
managers provide a level of abstraction to map your user interface on all windowing systems,
so that the layout can be platform‐independent.

AWT provides the following layout managers ﴾in package java.awt﴿:

 Flow Layout
 Border Layout
 Grid Layout
 Card Layout
 Grid Bag Layout

Container's setLayout() method: container has a setLayout() method to set its layout manager

public void setLayout(LayoutManager mgr)

To set up the layout of a Container (such as Frame, JFrame, Panel, or JPanel), you
have to:
1.Construct an instance of the chosen layout object, via new and constructor, e.g., new
FlowLayout())
2.Invoke the setLayout() method of the Container, with the layout object created as
the argument;
3.Place the GUI components into the Container using the add() method in the correct
order; or into the correct zones.

11.6.1 Layout Manager :FlowLayout


In the java.awt.FlowLayout, components are arranged from left-to-right inside the
container in the order that they are added (via method aContainer.add(aComponent)). When
one row is filled, a new row will be started. The actual appearance depends on the width of
the display window
Constructor of FlowLayout
Constructors Description
public FlowLayout() Default flowlayout
public FlowLayout(int alignment) alignment :
FlowLayout.LEFT or FlowLayout.RIGHT or
FlowLayout.CENTER
252

public FlowLayout(int alignment, hgap, vgap: horizontal/vertical gap between the


int hgap, int vgap) componentsDefault value: By default: hgap = 5,
vgap = 5, alignment = FlowLayout.CENTER

Example program on FlowLayoutDemo

import java.awt.*;
import java.awt.event.*;
// An AWT GUI program inherits the top-level container java.awt.Frame
public class AWTFlowLayoutDemo extends Frame
{
private Button btn1, btn2, btn3, btn4, btn5, btn6;
public AWTFlowLayoutDemo ()
{
setLayout(new FlowLayout());
btn1 = new Button("Button 1");
btn2 = new Button("This is Button 2");
btn3 = new Button("3");
btn4 = new Button("Another Button 4");
btn5 = new Button("Button 5");
btn6 = new Button("One More Button 6");
add(btn1); add(btn2); add(btn3); add(btn4); add(btn5);add(btn6);
setTitle("FlowLayout Demo"); // "super" Frame sets title
setSize(280, 150); // "super" Frame sets initial size
setVisible(true); // "super" Frame shows
}
// The entry main() method
public static void main(String[] args)
{
new AWTFlowLayoutDemo(); // Let the constructor do the job
}
}
Output:
253

11.6.2 Layout Manager : GridLayout


In java.awt.GridLayout, components are arranged in a grid (matrix) of rows and columns
inside the Container. Components are added in a left-to-right, top-to-bottom manner in the
order they are added (via method aContainer.add(aComponent)).

Constructors
 public GridLayout(int rows, int columns);
 public GridLayout(int rows, int columns, int hgap, int vgap);
// By default: rows = 1, cols = 0, hgap = 0, vgap = 0

import java.awt.*;
import java.awt.event.*;
// An AWT GUI program inherits the top-level container java.awt.Frame
public class AWTGridLayoutDemo extends Frame
{
private Button btn1, btn2, btn3, btn4, btn5, btn6;
// Constructor to setup GUI components and event handlers
public AWTGridLayoutDemo ()
{
setLayout(new GridLayout(3, 2, 3, 3));

// "super" Frame sets layout to 3x2 GridLayout, horizontal and vertical


gaps of 3 pixels
// The components are added from left-to-right, top-to-bottom
btn1 = new Button("Button 1");
btn2 = new Button("This is Button 2");
btn3 = new Button("3");
btn4 = new Button("Another Button 4");
btn5 = new Button("Button 5");
btn6 = new Button("One More Button 6");
add(btn1); add(btn2); add(btn3); add(btn4); add(btn5); add(btn6);

setTitle("GridLayout Demo"); // "super" Frame sets title


setSize(280, 150); // "super" Frame sets initial size
setVisible(true); // "super" Frame shows
}
// The entry main() method
public static void main(String[] args)
{
new AWTGridLayoutDemo(); // Let the constructor do the job
}
}
Output:
254

11.6.3 Layout Manager : Border Layout

In java.awt.BorderLayout, the container is divided into 5 zones: EAST, WEST,


SOUTH, NORTH, and CENTER. Components are added using method
Container.add(aComponent, zone),

where zone is either

BorderLayout.NORTH(orPAGE_START),

BorderLayout.SOUTH (or PAGE_END),

BorderLayout.WEST (or LINE_START),

BorderLayout.EAST (or LINE_END),

BorderLayout.CENTER.

You need not place components to all the 5 zones. The NORTH and SOUTH
components may be stretched horizontally; the EAST and WEST components may be
stretched vertically; the CENTER component may stretch both horizontally and vertically to
fill any space left over

Constructors

public BorderLayout();

public BorderLayout(int hgap, int vgap); // By default hgap = 0, vgap = 0


255

import java.awt.*;
import java.awt.event.*;
// An AWT GUI program inherits the top-level container java.awt.Frame
public class AWTBorderLayoutDemo extends Frame
{
private Button btnNorth, btnSouth, btnCenter, btnEast, btnWest;
// Constructor to setup GUI components and event handlers
public AWTBorderLayoutDemo ( )
{
setLayout(new BorderLayout(3, 3));
// "super" Frame sets layout to BorderLayout, horizontal and vertical gaps of 3
pixels The components are added to the specified zone
btnNorth = new Button("NORTH");
add(btnNorth, BorderLayout.NORTH);
btnSouth= new Button("SOUTH ");
add(btnSouth, BorderLayout.SOUTH);
btnCenter = new Button("CENTER");
add(btnCenter, BorderLayout.CENTER);
btnEast = new Button("EAST");
add(btnEast, BorderLayout.EAST);
btnWest = new Button("WEST");
add(btnWest, BorderLayout.WEST);
setTitle("BorderLayout Demo"); // "super" Frame sets title
setSize(280, 150); // "super" Frame sets initial size
setVisible(true); // "super" Frame shows
}

// The entry main() method


public static void main(String[] args) {
new AWTBorderLayoutDemo(); // Let the constructor do the job
}
}
Output:
256

11.6.4 Layout Manager : CardLayout


The CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known as
CardLayout.

Constructors of CardLayout class


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal
and vertical gap.

Commonly used methods of CardLayout class


 public void next(Container parent): is used to flip to the next card of the given
container.
 public void previous(Container parent): is used to flip to the previous card of
the given container.
 public void first(Container parent): is used to flip to the first card of the given
container.
 public void last(Container parent): is used to flip to the last card of the given
container.
 public void show(Container parent, String name): is used to flip to the
specified card with the given name.
257

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2); c.add("c",b3);
}
public void actionPerformed(ActionEvent e)
{
card.next(c);
}
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Output:
258

Layout Manager : GridBagLayout

The Java GridBagLayout class is used to align components vertically, horizontally or


along their baseline.The components may not be of same size. Each GridBagLayout object
maintains a dynamic, rectangular grid of cells. Each component occupies one or more cells
known as its display area. Each component associates an instance of GridBagConstraints.
With the help of constraints object we arrange component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in order to
determine component's size.

Method Description

void addLayoutComponent(Component It adds specified component to the layout,


comp, Object constraints) using the specified constraints object.
void addLayoutComponent(String name, It has no effect, since this layout manager
Component comp) does not use a per-component string.
protected void It adjusts the x, y, width, and height fields to
adjustForGravity(GridBagConstraints the correct values depending on the
constraints, Rectangle r) constraint geometry and pads
protected void This method is for backwards compatibility
AdjustForGravity(GridBagConstraint only
s constraints, Rectangle r)
protected void arrangeGrid(Container parent) Lays out the grid

protected void ArrangeGrid(Container This method is obsolete and supplied for


parent) backwards compatibility
GridBagConstraints It is for getting the constraints for the
getConstraints(Component comp) specified component.
float getLayoutAlignmentX(Container It returns the alignment along the x axis.
parent)
259

Example program to demonstrate Java GridBagLayout

import java.awt.*;
public class GridBagLayoutExample extends Frame{

public GridBagLayoutExample()
{
setLayout(new GridBagLayout());
setTitle("GridBag Layout Example");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button three"), gbc);
setSize(300, 300);
setVisible(true);

}
public static void main(String[] args)
{
new GridBagLayoutExample();
}
}

Output:

You might also like