0% found this document useful (0 votes)
130 views45 pages

Vayu Sena

The document discusses event handling in Java. It defines an event as a change in state of an object. Events can be foreground events from direct user interaction or background events from system interrupts. Event handling uses the delegation event model where a listener object handles events from a source object. The key steps are: 1) a user interacts with a component and generates an event, 2) an event object is created and passed to the appropriate registered listener's method, 3) the listener method is executed and returns. Common events in Java include action, mouse, and key events. Listeners must implement predefined interfaces to receive events from sources.

Uploaded by

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

Vayu Sena

The document discusses event handling in Java. It defines an event as a change in state of an object. Events can be foreground events from direct user interaction or background events from system interrupts. Event handling uses the delegation event model where a listener object handles events from a source object. The key steps are: 1) a user interacts with a component and generates an event, 2) an event object is created and passed to the appropriate registered listener's method, 3) the listener method is executed and returns. Common events in Java include action, mouse, and key events. Listeners must implement predefined interfaces to receive events from sources.

Uploaded by

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

Event Handling:

What is an Event?
Change in the state of an object is known as event i.e. event describes the
change in state of source. Events are generated as result of user interaction
with the graphical user interface components. For example, clicking on a
button, moving the mouse, entering a character through keyboard,selecting
an item from list, scrolling the page are the activities that causes an event
to happen.

Types of Event
The events can be broadly classified into two categories:

 Foreground Events - Those events which require the direct interaction of


user.They are generated as consequences of a person interacting with the
graphical components in Graphical User Interface. For example, clicking on a
button, moving the mouse, entering a character through keyboard,selecting an
item from list, scrolling the page etc.

 Background Events - Those events that require the interaction of end user are
known as background events. Operating system interrupts, hardware or
software failure, timer expires, an operation completion are the example of
background events.

What is Event Handling?


Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs. This mechanism have the code which is
known as event handler that is executed when an event occurs. Java Uses
the Delegation Event Model to handle the events. This model defines the
standard mechanism to generate and handle the events.Let's have a brief
introduction to this model.

The Delegation Event Model has the following key participants namely:

 Source - The source is an object on which event occurs. Source is responsible


for providing information of the occurred event to it's handler. Java provide as
with classes for source object.
 Listener - It is also known as event handler.Listener is responsible for
generating response to an event. From java implementation point of view the
listener is also an object. Listener waits until it receives an event. Once the
event is received , the listener process the event an then returns.

The benefit of this approach is that the user interface logic is completely
separated from the logic that generates the event. The user interface
element is able to delegate the processing of an event to the separate piece
of code. In this model ,Listener needs to be registered with the source
object so that the listener can receive the event notification. This is an
efficient way of handling the event because the event notifications are sent
only to those listener that want to receive them.

Steps involved in event handling


 The User clicks the button and the event is generated.

 Now the object of concerned event class is created automatically and


information about the source and the event get populated with in same object.

 Event object is forwarded to the method of registered listener class.

 the method is now get executed and returns.

Points to remember about listener


 In order to design a listener class we have to develop some listener
interfaces.These Listener interfaces forecast some public abstract callback
methods which must be implemented by the listener class.

 If you do not implement the any if the predefined interfaces then your class can
not act as a listener class for a source object.

Callback Methods
These are the methods that are provided by API provider and are defined
by the application programmer and invoked by the application developer.
Here the callback methods represents an event method. In response to an
event java jre will fire callback method. All such callback methods are
provided in listener interfaces.

If a component wants some listener will listen to it's events the the source
must register itself to the listener.
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on
button, dragging mouse etc. The java.awt.event package provides many event
classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event handling:

1. Register the component with the Listener


Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java Event Handling Code


We can put the event handling code into one of the following places:

1. Within class
2. Other class
3. Anonymous class

Java event handling by implementing ActionListener

import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);
add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}

public void setBounds(int xaxis, int yaxis, int width, int height); have
been used in the above example that sets the position of the component it may
be button, textfield etc.
2) Java event handling by outer class
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}

3) Java event handling by anonymous class


import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);

b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
new AEvent3();
}
}

AWT Event Adapters


Adapters are abstract classes for receiving various events. The methods in
these classes are empty. These classes exists as convenience for creating
listener objects.

AWT Adapters:
Following is the list of commonly used adapters while listening GUI events
in AWT.

Sr. No. Adapter & Description

1 FocusAdapter

An abstract adapter class for receiving focus events.

2 KeyAdapter

An abstract adapter class for receiving key events.

3 MouseAdapter

An abstract adapter class for receiving mouse events.

4 MouseMotionAdapter

An abstract adapter class for receiving mouse motion events.

5 WindowAdapter

An abstract adapter class for receiving window events.


The class FocusAdapter is an abstract (adapter) class for receiving
keyboard focus events. All methods of this class are empty. This class is
convenience class for creating listener objects.

Class constructors
S.N. Constructor & Description

1 FocusAdapter()

Class methods
S.N. Method & Description

1 void focusGained(FocusEvent e)

Invoked when a component gains the keyboard focus.

2 focusLost(FocusEvent e)

Invoked when a component loses the keyboard focus.

Methods inherited
This class inherits methods from the following classes:

 java.lang.Object

FocusAdapter Example
Create the following java program using any editor of your choice in
say D:/ > AWT > com > tutorialspoint > gui >
AwtAdapterDemo.java

package com.tutorialspoint.gui;

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

public class AwtAdapterDemo {


private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtAdapterDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtAdapterDemo awtAdapterDemo = new AwtAdapterDemo();
awtAdapterDemo.showFocusAdapterDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showFocusAdapterDemo(){

headerLabel.setText("Listener in action: FocusAdapter");

Button okButton = new Button("OK");


Button cancelButton = new Button("Cancel");
okButton.addFocusListener(new FocusAdapter(){
public void focusGained(FocusEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName()
+ " gained focus. ");
}
});

cancelButton.addFocusListener(new FocusAdapter(){
public void focusLost(FocusEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName()
+ " lost focus. ");
}
});

controlPanel.add(okButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
}
Java Inner Classes
Java inner class or nested class is a class which is declared inside the class
or interface.

We use inner classes to logically group classes and interfaces in one place
so that it can be more readable and maintainable.

Additionally, it can access all the members of outer class including private
data members and methods.

Syntax of Inner class


class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Advantage of java inner classes

There are basically three advantages of inner classes in java. They are as
follows:
Nested classes represent a special type of relationship that is it can
access all the members (data members and methods) of outer
class including private.

Nested classes are used to develop more readable and


maintainable code because it logically group classes and interfaces
in one place only.

Code Optimization: It requires less code to write.

Difference between nested class and inner class in Java

Inner class is a part of nested class. Non-static nested classes are known as
inner classes.

Types of Nested classes


There are two types of nested classes non-static and static nested
classes.The non-static nested classes are also known as inner classes.

 Non-static nested class (inner class)


 Member inner class
 Anonymous inner class
 Local inner class
 Static nested class

Type Description

Member Inner A class created within class and outside method.


Class

Anonymous A class created for implementing interface or extending


Inner Class class. Its name is decided by the java compiler.

Local Inner Class A class created within method.


Static Nested A static class created within class.
Class

Nested Interface An interface created within class or interface.

Java Member inner class


A non-static class that is created inside a class but outside a method is
called member inner class.

Syntax:

class Outer{
//code
class Inner{
//code
}
}
Java Member inner class example

In this example, we are creating msg() method in member inner class that
is accessing the private data member of outer class.

class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}

Output:

data is 30
Java Anonymous inner class
A class that have no name is known as anonymous inner class in java. It
should be used if you have to override method of class or interface. Java
Anonymous inner class can be created by two ways:

Class (may be abstract or concrete).

Interface

Java anonymous inner class example using class


abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}

Output:

nice fruits

Java Local inner class


A class i.e. created inside a method is called local inner class in java. If you
want to invoke the methods of local inner class, you must instantiate this
class inside the method.

Java local inner class example


public class localInner1{
private int data=30;//instance variable
void display(){
class Local{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
obj.display();
}
}

Output:

30

Java static nested class


A static class i.e. created inside a class is called static nested class in java. It
cannot access non-static data members and methods. It can be accessed by
outer class name.

It can access static data members of outer class including private.

Static nested class cannot access non-static (instance) data member or


method.

Java static nested class example with instance method


class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Output:

data is 30

In this example, you need to create the instance of static nested class
because it has instance method msg(). But you don't need to create the
object of Outer class because nested class is static and static properties,
methods or classes can be accessed without object.

Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.

Java AWT components are platform-dependent i.e. components are displayed


according to the view of operating system. AWT is heavyweight i.e. its components
are using the resources of OS.

The java.awt package provides classes for AWT api such


as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.


Container

The Container is a component in AWT that can contain another components


like buttons, textfields, labels etc. The classes that extends Container class are
known as container such as Frame, Dialog and Panel.

Window

The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window.
Panel

The Panel is the container that doesn't contain title bar and menu bars. It can have
other components like button, textfield etc.

Frame

The Frame is the container that contain title bar and can have menu bars. It can
have other components like button, textfield etc.

Useful Methods of Component class

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

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

public void setVisible(boolean status) changes the visibility of the component, by default
false.

Java AWT Example

To create simple awt example, you need a frame. There are two ways to create a
frame in AWT.

 By extending Frame class (inheritance)


 By creating the object of Frame class (association)
AWT Example by Inheritance

Let's see a simple example of AWT where we are inheriting Frame class. Here, we
are showing Button component on the Frame.

import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible

}
public static void main(String args[])
{
First f=new First();
}
}

The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above
example that sets the position of the awt button.
AWT Example by Association
Let's see a simple example of AWT where we are creating instance of Frame class.
Here, we are showing Button component on the Frame.

import java.awt.*;
class First2
{
First2()
{
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
First2 f=new First2();
}
}

Java AWT Label

The object of Label class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but
a user cannot edit it directly.

AWT Label Class Declaration


public class Label extends Component implements Accessible
Java Label Example
import java.awt.*;
class LabelExample{
public static void main(String args[]){
Frame f= new Frame("Label Example");
Label l1,l2;
l1=new Label("First Label.");
l1.setBounds(50,100, 100,30);
l2=new Label("Second Label.");
l2.setBounds(50,150, 100,30);
f.add(l1); f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

Java AWT Button

The button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.

AWT Button Class declaration


public class Button extends Component implements Accessible
Java AWT Button Example
import java.awt.*;
public class ButtonExample {
public static void main(String[] args) {
Frame f=new Frame("Button Example");
Button b=new Button("Click Here");
b.setBounds(50,100,80,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

Java AWT Checkbox

The Checkbox class is used to create a checkbox. It is used to turn an option on


(true) or off (false). Clicking on a Checkbox changes its state from "on" to "off" or
from "off" to "on".

AWT Checkbox Class Declaration


public class Checkbox extends Component implements ItemSelectable, Accessibl
e
Java AWT Checkbox Example
import java.awt.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", 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 CheckboxExample();
}
}

Output:

Java AWT CheckboxGroup


The object of CheckboxGroup class is used to group together a set of Checkbox. At a
time only one check box button is allowed to be in "on" state and remaining check
box button in "off" state. It inherits the object class.

Note: CheckboxGroup enables you to create radio buttons in AWT. There is no


special control for creating radio buttons in AWT.

AWT CheckboxGroup Class Declaration


public class CheckboxGroup extends Object implements Serializable
Java AWT CheckboxGroup Example
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = 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();
}
}

Output:
Java AWT Choice

The object of Choice class is used to show popup menu of choices. Choice selected
by user is shown on the top of a menu. It inherits Component class.

AWT Choice Class Declaration


public class Choice extends Component implements ItemSelectable, Accessible
Java AWT Choice Example
import java.awt.*;
public class ChoiceExample
{
ChoiceExample(){
Frame f= new Frame();
Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceExample();
}
}

Output:

Java AWT TextField

The object of a TextField class is a text component that allows the editing of a single
line text. It inherits TextComponent class.

AWT TextField Class Declaration


public class TextField extends TextComponent
Java AWT TextField Example
import java.awt.*;
class TextFieldExample{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new TextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

Java AWT Scrollbar

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.

AWT Scrollbar class declaration


public class Scrollbar extends Component implements Adjustable, Accessible
Java AWT Scrollbar Example
import java.awt.*;
class ScrollbarExample{
ScrollbarExample(){
Frame f= new Frame("Scrollbar Example");
Scrollbar s=new Scrollbar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
new ScrollbarExample();
}
}

Output:

Java 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
Java AWT 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();
}
}

Output:
Java AWT MenuItem and Menu

The object of MenuItem class adds a simple labeled menu item on menu. The items
used in a menu must belong to the MenuItem or any of its subclass.

The object of Menu class is a pull down menu component which is displayed on the
menu bar. It inherits the MenuItem class.

AWT MenuItem class declaration


public class MenuItem extends MenuComponent implements Accessible
AWT Menu class declaration
public class Menu extends MenuItem implements MenuContainer, Accessible
Java AWT MenuItem and Menu Example
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);
}
public static void main(String args[])
{
new MenuExample();
}
}

Output:
Java AWT Canvas

The Canvas control 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


public class Canvas extends Component implements Accessible
Java AWT Canvas Example
import java.awt.*;
public class CanvasExample
{
public CanvasExample()
{
Frame f= new Frame("Canvas Example");
f.add(new MyCanvas());
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
}
public static void main(String args[])
{
new CanvasExample();
}
}
class MyCanvas extends Canvas
{
public MyCanvas() {
setBackground (Color.GRAY);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}

Output:

Layouts
Flow Layout, Grid Layout, Border Layout, Card Layout.

Java LayoutManagers

Layout means the arrangement of components within the container. In other


way we can say that placing the components at a particular position within
the container. The task of layouting the controls is done automatically by the
Layout Manager.

The LayoutManagers are used to arrange components in a particular manner.


LayoutManager is an interface that is implemented by all the classes of layout
managers. There are following classes that represents the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout

Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north,


south, east, west and center. Each region (area) may contain one component
only. It is the default layout of frame or window. The BorderLayout provides
five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


o BorderLayout(): creates a border layout but with no gaps between the
components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the
given horizontal and vertical gaps between the components.

Example of BorderLayout class:


Example:

import java.awt.*;

public class Border {


Border(){
Frame f=new Frame();

Button b1=new Button("NORTH");;


Button b2=new Button("SOUTH");;
Button b3=new Button("EAST");;
Button b4=new Button("WEST");;
Button b5=new Button("CENTER");;

f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
Border b = new Border();
}
}

Output:

GridLayout

The GridLayout is used to arrange the components in rectangular grid. One


component is displayed in each rectangle.

Constructors of GridLayout class


1. GridLayout(): creates a grid layout with one column per component in
a row.
2. GridLayout(int rows, int columns): creates a grid layout with the
given rows and columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid
layout with the given rows and columns alongwith given horizontal and
vertical gaps.
Example of GridLayout class

Example:

import java.awt.*;

public class MyGridLayout


{
MyGridLayout()
{
Frame f=new Frame();

Button b1=new Button("1");


Button b2=new Button("2");
Button b3=new Button("3");
Button b4=new Button("4");
Button b5=new Button("5");
Button b6=new Button("6");
Button b7=new Button("7");
Button b8=new Button("8");
Button b9=new Button("9");

f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.add(b9);

f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
MyGridLayout m=new MyGridLayout();
}
}

Output:
FlowLayout

The FlowLayout is used to arrange the components in a line, one after another
(in a flow). It is the default layout of applet or panel.

Fields of FlowLayout class


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class


1. FlowLayout(): creates a flow layout with centered alignment and a
default 5 unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment
and a default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with
the given alignment and the given horizontal and vertical gap.

Example of FlowLayout class


Example:

import java.awt.*;

public class MyFlowLayout{


MyFlowLayout(){
Frame f=new Frame();

Button b1=new Button("1");


Button b2=new Button("2");
Button b3=new Button("3");
Button b4=new Button("4");
Button b5=new Button("5");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
MyFlowLayout m=new MyFlowLayout();
}
}

CardLayout

The CardLayout class manages the components in such a way that only one
component is visible at a time. It treats each component as a card in the
container. Only one card is visible at a time, and the container acts as a stack
of cards. The first component added to a CardLayout object is the visible
component when the container is first displayed.

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


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

Example:

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);
}
}

You might also like