Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 60

ADITYA COLLEGE OF ENGINEERING &

TECHNOLOGY

OOPS THROUGH JAVA


UNIT VI - REVISION

By

T. Srinivasulu
Dept of Information Technology
Aditya College of Engineering & Technology
Surampalem.
Aditya College of Engineering & Technology

Unit – 6: Abstract Window Toolkit


SYLLABUS:
• Introduction
• components • Containers
Button, Layouts,
Label, Menu
Checkbox, Scrollbar.
Radio Buttons,
List Boxes,
Choice Boxes,

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Introduction:
• The Java Foundation Classes (JFC) provide two frameworks for building GUI-
based application and interestingly both rely on the same event handling
model:
– Abstract Window Toolkit(AWT)
– Swing
• AWT relies on the underlying operating system on a specific platform to
represent its GUI components ( components in AWT are called Heavyweight),
• Swing implements a new set of lightweight GUI components that are written
in Java and has a pluggable look and feel.
• These lightweight components are not dependent on the underlying window
system.
OOPS THROUGH JAVA T.Srinivasulu 4/9/23
Aditya College of Engineering & Technology
Difference between AWT and Swing :
AWT SWING
AWT components are heavy weight. Swing components are light weight.
AWT components are platform Swing components are platform
dependent so there look and feel independent so there look and feel
changes according to OS. remains constant
AWT provides less components than Swing provides more powerful
swing. components such are tables, scroll panes,
colorchooser, tabbedpane etc.,
AWT does not follow MVC (Model View Swing follows MVC.
Controller) where model represents data,
view represents presentation and
controller acts as an interface between
model and view.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

GUI:
RECAP OF
EVENT
HANDING
5th UNIT

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Elements of GUI Programming:


• Components
… Visual objects that appear on the screen
… Example: Button, Checkbox, List, Text Field
• Containers
… Specific objects which can hold other components
… Example: Frame, Window, Applet
• Layouts
… Control over the positioning of components within a container
… Example: FlowLayout, BorderLayout, CardLayout
• Events
… Responses to user actions
… Example: ActionEvent, MouseEvent, KeyEvent, ItemEvent

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Steps involving in GUI Programming:

 Create object of container


 Set the layout of the container
 Add the objects of components to the container
 Override the event handler methods of event listeners
against the action of the users
 Register the appropriate listener object with the
components

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

AWT Event-Handling or Event Delegation Model:


 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.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

The sequence diagram AWT Event-Handling:

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Different GUI class hierarchy in AWT:

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Different Classes in AWT:

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Different Classes in AWT:

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Components and Containers:

There are two types of GUI elements:


1.Component: Components are elementary GUI entities, such as Button, Label, and TextField.
2.Container: Containers, such as Frame and Panel, are used to hold components in a specific layout (such
as FlowLayout or GridLayout). A container can also hold sub-containers.
 In the above figure, there are three containers: a Frame and two Panels. A Frame is the top-level container of
an AWT program. A Frame has a title bar (containing an icon, a title, and the minimize/maximize/close
buttons) and the content display area. A Panel is a rectangular area used to group related GUI components in
a certain layout. In the above figure, the top-level Frame contains two Panels. There are five components:
a Label (providing description), a TextField (for users to enter text), and three Buttons (for user to trigger
certain programmed actions).
OOPS THROUGH JAVA T.Srinivasulu 4/9/23
Aditya College of Engineering & Technology
 AWT Component Classes:
• The Component class defines data and methods
which are relevant to all Components
 -setBounds(int x, int y, int width, int height) –
both size and origin
 -setSize(int width, int height) – setting the size
 -setLocation(int x, int y) -- setting the position
in container
 -setFont(Font f)
 -setEnabled(boolean b) -- if false, not able to
 AWT provides many ready-made and reusable GUI
components in package java.awt. The frequently-used interact with control
are: Button, TextField, Label, Checkbox, CheckboxGrou  -setVisible(boolean b) -- if false, control will
p (radio buttons), List, and Choice, as illustrated below. not display
 -setForeground(Color c) -- text colour
 -setBackground(Color c) -- background colour

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Components as Event Generator:


 Each component is source of event and generates different types of events.
 Event listener class works like representative to generate response against users action
 The relation between component and event and event listener is tabulated as below:

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Button control:
The Button class belongs to java.awt package
public class Button extends Component implements Accessible
This class creates a button in which when pushed or pressed generates an event.
The two constructors belonging to this Button class are:
Button()
Button(String str)
To create a button
Button buttonName = new Button(Str);
‘buttonname’ is the name you give to the button object and ‘Str’ is the text you want to appear on the
button.
Once the object for Button is created, it needs to be added to the applet or any other
container using
add(buttonname);
void setLabel(String str); for changing the button’s label
String getLabel(); for getting the Buttons label’s text

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Program to demonstrate Button class with Action Event:


import java.awt.*; public void actionPerformed(ActionEvent ae) {
import java.applet.*; if(ae.getSource()==b1){
import java.awt.event.*; showStatus("You clicked Button 1");
/* <applet code="ButtonTest.class" width="400" height="150"> }else if(ae.getSource()==b2){
</applet> */ showStatus("You clicked Button 2");
public class ButtonTest extends Applet implements ActionListener }
{ }
Button b1,b2; }
public void start() {
b1 = new Button("Button 1");
b2 = new Button("Button 2");
b1.addActionListener(this);
b2.addActionListener(this);
add(b1);
add(b2);
}
OOPS THROUGH JAVA T.Srinivasulu 4/9/23
Aditya College of Engineering & Technology

Label control:
 Label is passive components used to display some text to guide user with showing some information.
 This is the simplest component of Java AbstractWindowToolkit.
 This component is generally used to show the text or string in your application and label never perform any
type of action.
 Syntax for defining the label only and with justification:
Label label_name = new Label ("This is the label text.");
 above code simply represents the text for the label.
Label label_name = new Label ("This is the label text. ” , Label.CENTER);
 Justification of label can be left, right or centered. Above declaration used the center justification of the label
using the Label.CENTER.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Example program to demonstrate Label :


import java.awt.*;
import java.applet.Applet;
/*
<applet code="LabelTest.class" width="200" height="100">
</applet>
*/
public class LabelTest extends Applet
{
public void init()
{
add(new Label("A label"));
// right justify next label
add(new Label("Another label", Label.RIGHT));
}
}

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Checkbox control:
 Checkboxes are used as on-off or yes-no switches
 if you click on an unchecked checkbox, it will get checked and vice versa.
 Constructors of Checkbox
– Checkbox()
– Checkbox(String str) // constructor with label of chechbox
– Checkbox(String str, boolean on) // constructor with label and initial state of checkbox
– Checkbox(String str, CheckBoxGroup cbg, boolean on) // creating radio button

 Methods of Checkbox
– boolean getState() // returns state of the checkbox true / false
– String getLabel() // returns label of chechbox
– CheckboxGroup getCheckboxGroup() // returns checkbox group obj. of radiobutton

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Program to demonstrate Checkbox control with ItemEvent:


import java.awt.*; public void itemStateChanged(ItemEvent ie) {
import java.awt.event.*; repaint();
import java.applet.*; }
/* <applet code="CheckboxDemo.class" width="250" height="180"> public void paint(Graphics g) {
</applet> */ msg = "Current state: ";
public class CheckboxDemo extends Applet g.drawString(msg,6,80);
implements ItemListener { msg = " ECE :" + cb1.getState();
String msg = ""; g.drawString(msg,6,100);
Checkbox cb1,cb2; msg = " CSE " + cb2.getState();
public void init() { g.drawString(msg,6,120);
// creating checkbox controls }
cb1 = new Checkbox(“ECE",null,true); }
cb2 = new Checkbox(“CSE");
// adding to applet
add(cb1);
add(cb2);
// registered with item listener
cb1.addItemListener(this);
cb2.addItemListener(this);
}

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Radio Button control:


 are special kind of checkboxes where only one box can be selected at a time.
 The CheckboxGroup class is used to group together a set of checkboxes
– CheckboxGroup fruits = new CheckboxGroup();
 After creating checkbox group, the individual checkboxes are added to that group.
– add(new Checkbox(“mango”, fruits, false));
– add(new Checkbox(“papaya”, fruits, false));
– add(new Checkbox(“guava”, fruits, false));
– add(new Checkbox(“apple”, fruits, true));

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Program to demonstrate Radio buttons with itemevent:


// adding to the container through layout manager.
add(c1);
import java.awt.*;
add(c2);
import java.awt.event.*;
add(c3);
import java.applet.*;
add(c4);
/*
// registering the controls with listener
<applet code="RadioButtonsTest.class" width="250" height="200">
c1.addItemListener(this);
</applet>
c2.addItemListener(this);
*/
c3.addItemListener(this);
public class RadioButtonsTest extends Applet implements ItemListener {
c4.addItemListener(this);
String msg = "";
}
Checkbox c1,c2,c3,c4;
//overriding the event-handler method of listener interface
CheckboxGroup cbg;
public void itemStateChanged(ItemEvent ie) {
 
repaint();
public void init() {
}
cbg = new CheckboxGroup();
 
// creating objects of controls
public void paint(Graphics g) {
c1 = new Checkbox(“ECE",cbg,true);
msg = "Current selection: ";
c2 = new Checkbox(“EEE",cbg,false);
msg += cbg.getSelectedCheckbox().getLabel();
c3 = new Checkbox(“CSE",cbg,false);
g.drawString(msg,6,100);
c4 = new Checkbox("MECH",cbg,false);
}
}
OOPS THROUGH JAVA T.Srinivasulu 4/9/23
Aditya College of Engineering & Technology

Output:

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

TextField control:
• The TextField class implements a single-line text-entry area.
• Textfields 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.
• TextField defines the following Constructors:
o TextField( ) -used to create default text editor
o TextField(int numChars) -used to create a text filed with some number of characters length.
o TextField(String str) -used to create a text field with string in it.
o TextField(String str, int numChars) -used to create text filed with string in it and also specified number o
characters length.
• Methods:
o String getText( ) -used to get the text from the text field
o void setText(String str) -used to set the text to the text field
o String getSelectedText( ) -used to get the selected text
o void select(int startIndex, int endIndex) -used to select the characters starting from startindex to the
endindex.
o void setEchoChar(char ch) -used to create passwords. Actual characters are not shown.
o char getEchoChar( ) -used to obtain the echo characters.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Program demonstrate Textfield and Action event:


import java.awt.*;
add(pass);
import java.awt.event.*;
// registering the controls with listener
import java.applet.*;
name.addActionListener(this);
/* <applet code="TextFieldDemo.class" width="200" height="200">
pass.addActionListener(this);
</applet> */
}
public class TextFieldDemo extends Applet implements ActionListener
public void actionPerformed(ActionEvent ae) {
{
repaint();
TextField name,pass;
}
public void init() {
public void paint(Graphics g) {
// creating controls
g.drawString("Name: " + name.getText(),6,80);
Label lname = new Label("Name: ",Label.RIGHT);
g.drawString("Password: " + pass.getText(),6,100);
Label lpass = new Label("Password: ",Label.RIGHT);
}
name = new TextField(12);
}
pass = new TextField(8);
pass.setEchoChar('*');
// adding controls to applet
add(lname);
add(name);
add(lpass);
OOPS THROUGH JAVA T.Srinivasulu 4/9/23
Aditya College of Engineering & Technology

Output:

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Choice control:
• provides a pop-up menu of text string choices
• current choice is displayed on top.
– Choice c = new Choice();
• the add method enables you to add new entries.
– c.add(“Red”);
– c.add(“Green”);
• The currently selected item can be changed by using select() method.
• The selection can be made based on name or index. For e.g.
– c.select(“Red”);
– c.select(0);
– getSelectedIndex() - return the position of the selected item
– getSelectedItem() - returns the name of the selected item
• The Listener for handling Choice change events is ItemListener.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Program to demonstrate Choice class with Item Event:


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="ChoiceDemo.class" width="250" height="150"> </applet> */
public class ChoiceDemo extends Applet
implements ItemListener {
Choice os; // overridng event handler
String msg = ""; public void itemStateChanged(ItemEvent ie) {
repaint();
public void init() { }
// creating object of choice control  
os = new Choice(); public void paint(Graphics g) {
// adding items to choice control msg = "Current OS: ";
os.add(“ECE"); msg += os.getSelectedItem();
os.add(“EEE"); g.drawString(msg,6,120);
os.add(“CSE"); }
os.add("MECH"); }
// adding choice control to container
add(os);
// registering with item listener
os.addItemListener(this);
}
OOPS THROUGH JAVA T.Srinivasulu 4/9/23
Aditya College of Engineering & Technology

Output:

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


List control: Aditya College of Engineering & Technology

• The List class provides a compact, multiple-choice, scrolling selection list.


• Unlike the Choice 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.
• Constructors:
o List( ) -used to create List control that allows only one item to be selected at any time.
o List(int numRows) - the value of numRows specifies the number of entries in the list that will always be visible.
• Methods:
o To add a selection to the list, call add( ). It has the following two forms:
o void add(String name) -Used to add an item to the list at the end.
o void add(String name, int index) – used to add an item to the list at the specified index.
o String getSelectedItem( ) -used to get the item that is selected
o int getSelectedIndex( ) -used to get the index of the item selected.
o String[] getSelectedItems() -used to get all the selected items.
o int[] getSelectedIndexes() -used to get all the indexes of the selected items
o int getItemCount( ) -used to get number of the items
o void select(int index) -used to set the current item as selected item.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Program to demonstrate List control with action event:
import java.awt.*; // registering the list with
import java.awt.event.*; // action listener
import java.applet.*; os.addActionListener(this);
/* <applet code="ListDemo.class" width="300" height="180"> }
</applet> */ public void actionPerformed(ActionEvent ae) {
public class ListDemo extends Applet implements ActionListener { repaint();
List os; }
String msg = ""; public void paint(Graphics g) {
public void init() { int idx[];
// creating list control msg = "Current OS: ";
os = new List(4,true); idx = os.getSelectedIndexes();
// adding items to list for(int i=0;i<idx.length;i++)
os.add(“ECE"); msg += os.getItem(idx[i]) + " ";
os.add(“EEE"); g.drawString(msg,6,100);
os.add(“CSE"); }
os.add(“MECH"); }
// adding list to applet
add(os);

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Output:

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
AWT Container Classes:
 A Container is an object used to group Components.
 For a component to be placed on the screen, it must be placed within a Container
 Every Container has its own Layout Manager which determines how Components
will be arranged.
 The Container class has the following predefined methods necessary for managing
groups of Components
void add(Component c) – adding control to the container
Component getComponent() – returns the object of control
Dimension getMaximumSize()
Dimension getMinimumSize()
void remove(Component c) – remove the control
void removeAll() – remove all controls

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Hierarchy of the AWT Container Classes
• Window
– The class Window is a top level window with no border and no menubar. It uses
Border Layout as default layout manager.
• Frame
– Frame is a top-level window with a border and title. An instance of the Frame
class may have a menu bar, title bar and borders. It uses Border Layout as
default layout manager.
• Dialog
– Dialog is top-level window with a border and title. An object of the Dialog class
cannot exist without an associated object of the Frame class. It uses Border
• Panel Layout as default layout manager..
– Panel is generic container for holding components. An instance of the Panel class provides a container to which
components can be added. It uses Flow Layout as default layout manager.
• Applet
– Applet is a special type of Container that is embedded in the webpage to generate the dynamic content. It runs inside the
browser. It uses Flow Layout as default layout manager.
• ScrollPane
─ A container class which implements automatic horizontal and/or vertical scrolling for a single child component.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Frame:

 A Frame provides the "main window" for your GUI application. It has a title bar (containing an icon, a
title, the minimize, maximize/restore-down and close buttons), an optional menu bar, and the content
display area.
 To create a Frame:
Frame frameName = new Frame();
 Constructors of Frame
public Frame() Creates a Frame window with no name.
public Frame(String name) Creates a Frame window with a name.
 Methods of Frame
public void add(Component comp) This method adds the component, to the Frame.
public void setLayout(LayoutManager object) This method sets the layout of the components
public void remove(Component comp) This method removes a component
public void setSize(int widthPixel, int heightPixel) This method sets the size of a Frame in terms of pixels.
public void setVisible(boolean status) changes the visibility of the frame

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Program to demonstrate Frame:
button.addActionListener(this);
import java.awt.*; jf.addWindowListener(this);
import java.awt.event.*;
jf.setLayout(new FlowLayout());
public class TextAreaEx2 implements ActionListener, WindowListener jf.setSize(375,250);
{ jf.setVisible(true);
Frame jf; }
TextArea textArea1; public void actionPerformed(ActionEvent ae)
Label label1, label2; {
Button button; if(ae.getActionCommand().equals("Submit"))
{
TextAreaEx2() label2.setText(" Your Details are : " + textArea1.getText());
{ jf.setVisible(true);
jf= new Frame("Demo on frames"); }
label1 = new Label("tell me about yourself"); }
button = new Button("Submit"); public static void main(String args[])
label2 = new Label(); {
textArea1 = new TextArea(5,45); new TextAreaEx2();
}
jf.add(label1); public void windowClosing(WindowEvent we)
jf.add(textArea1); {
jf.add(button); jf.dispose();
jf.add(label2); }
}

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Output:

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Dialog:
 An AWT Dialog is a "pop-up window" used for interacting with the users. A Dialog has a title-bar (containing an icon, a title and a close button) and a
content display area
 An object of the Dialog class cannot exist without an associated object of the Frame class
 Unlike Frame, it doesn't have maximize and minimize buttons.
 There are two kinds of Dialog windows
 Modal Dialog window
When a modal dialog window is active, all the user inputs are directed to it and all the other parts of application are inaccessible until this model
dialog is closed.
 Modeless Dialog window
When a modeless dialog window is active, the other parts of application are still accessible as normal and inputs can be directed to them, without
needing to close this modeless dialog window.
 Constructors:
1. Dialog(Frame, boolean) - Constructs an initially invisible Dialog.
2. Dialog(Frame parent, String title, boolean modal) - parent - the owner of the dialog, title - the title of the dialog modal - if true, dialog blocks
input to other windows when shown
 Methods:
1. getTitle() - Gets the title of the Dialog.
 2. isModal() - Returns true if the Dialog is modal.
 3. isResizable() - Returns true if the user can resize the frame.
 4. paramString() - Returns the parameter String of this Dialog.
 5. setResizable(boolean) - Sets the resizable flag.
  6. setTitle(String) - Sets the title of the Dialog.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


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

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Panel:

 The class Panel is the simplest container class. It provides space in which an


application can attach any other component, including other panels. It uses
FlowLayout as default layout manager. It doesn't have title bar.
 Constructors:
Panel () Constructs a panel with the default alignment (FlowLayout).
Panel (LayoutManager) Constructs a panel with the specified alignment.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Program to demonstrate Panel:
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();
}
}
OOPS THROUGH JAVA T.Srinivasulu 4/9/23
Aditya College of Engineering & Technology

Layout Managers:
 Each container has a layout manager, which controls the way the components are positioned in the
container.
 One of the advantages of using layout managers is that there is no need for absolute coordinates where
each component is to be placed or the dimensions of the component.
 Whenever the dimensions of the container change (e.g. user resizes the window), layout manager
recalculates the coordinates of components for them to fit the new container size.
 There are four basic layout managers are available in java.awt.package:
1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridbagLayout

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

FlowLayout:
 The Flow Layout manager arranges the components left-to-right, top-to-bottom in the order they
were inserted into the container.
 Components are added to the container first come first basis.
 When the container is not wide enough to display all the components, the remaining components
are placed in the next row, etc.
 Each row is centered. And all components are sized to preferred size and maintains a gap of 5
pixels.
 This layout is default layout for Panel, Applet.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Program to demonstrate FlowLayout:

package examples;
import java.awt.*;
import java.applet.*;
/*
<applet code="FlowLayoutDemo.class" width="300" height="200">
</applet>
*/
public class FlowLayoutDemo extends Applet {
public void init() {
setLayout(new FlowLayout());
CheckboxGroup cp = new CheckboxGroup();
Checkbox cb1 = new Checkbox("Large",cp,true);
Checkbox cb2 = new Checkbox("Medium",cp,false);
Checkbox cb3 = new Checkbox("Small",cp,false);
add(cb1);
add(cb2);
add(cb3);
}
}

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

Grid Layout:

 The Grid Layout manager lays out all the components in a rectangular grid.
 All the components have identical sizes, since the manager automatically stretches or compresses
the components as to fill the entire space of the container.
 Constructors are:
 GridLayout(r, c, hgap, vgap)
 r – number of rows in the layout
 c – number of columns in the layout
 hgap – horizontal gaps between components
 vgap – vertical gaps between components
 GridLayout(r, c)
 r – number of rows in the layout
 c – number of columns in the layout
 No vertical or horizontal gaps.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Program to demonstrate GridLayout:
import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo.class" width="300"
height="300">
</applet>
*/
public class GridLayoutDemo extends Applet {
public void init() {
setLayout(new GridLayout(2,2,10,10));
//setFont(new Font("Arial",Font.BOLD,18));
String[] labels = {"ECE","EEE", "CSE", "MECH"};
for(int i=0;i<4;++i) {
add(new Button(labels[i]));
}
}
}

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

BorderLayout:

 The Border Layout manager arranges components into five regions: (4 borders + center)
 Top border – BorderLayout.NORTH
 Left border – BorderLayout.WEST
 Right border – BorderLayout.EAST
 Bottom border – BorderLayout.SOUTH
 This layout is so useful to arrange menubar at top, vertical scrollbar at right border, and horizontal scrollbar at
bottom border.
 Components in the North and South are set to their natural heights and horizontally stretched to fill the entire
width of the container.
 Components in the East and West are set to their natural widths and stretched vertically to fill the entire width
of the container.
 The Center component fills the space left in the center of the container.
 This layout is default layout for Frame and dialog.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Program to demonstrate BorderLayout:
import java.awt.*;
import java.applet.*;
/* <applet code="BorderLayoutDemo.class" width="400"
height="300">
</applet> */
public class BorderLayoutDemo extends Applet{
public void init() {
setLayout(new BorderLayout());
Button b1 = new Button("TOP");
Button b2 = new Button("LEFT");
Button b3 = new Button("RIGHT");
Button b4 = new Button("BOTTOM");
TextArea ta = new TextArea(15,10);
add(b1,BorderLayout.NORTH);
add(b2,BorderLayout.WEST);
add(b3,BorderLayout.EAST);
add(b4,BorderLayout.SOUTH);
add(ta,BorderLayout.CENTER);
}
}
OOPS THROUGH JAVA T.Srinivasulu 4/9/23
Aditya College of Engineering & Technology

CardLayout:

 In card layout, components are added in layers.(one component is on the top of another
components, like pack of cards)
 Using this layout, we can hide components which are necessary to display.
 Cardlayout has different methods to switch from one card to another card.
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.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Program to demonstrate CardLayout:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code="CardLayoutDemo.class" width="300" height="300">
</applet> */
public class CardLayoutDemo extends Applet implements ActionListener{
CardLayout card = new CardLayout(20,20);
public void init() {
setLayout(card);
setFont(new Font("Arial",Font.BOLD,24));
Button b1 = new Button("First");
Button b2 = new Button("Second");
Button b3 = new Button("Third");
add(b1); add(b2); add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
card.next(this);
}
}
OOPS THROUGH JAVA T.Srinivasulu 4/9/23
Aditya College of Engineering & Technology

GridBagLayout:

 We can arrange components in horizontal as well in vertical direction or by positioning them within a cell of a grid
 Components need not be of same size in a row. Each row can contain dissimilar number of columns.
 Customization of a GridBagConstraints object can be done by setting one or more of its instance variables.
 gridx & gridy
 The initial address of cell of a grid is gridx = 0 and gridy = 0.
 gridwidth & gridheight
 gridwidth constraint specifies the number of cells in a row and gridheight specifies number of columns in
display area of the components. The default value is 1.
 fill
 GridBagConstraints.NONE (default value–does not grow when the window is resized)
 GridBagConstraints.HORIZONTAL (this value fills all the horizontal display area of a component, but it
does not change height).
 GridBagConstraints.VERTICAL (it changes the height of a component, but does not change its width)
 GridBagConstraints.BOTH (makes the component fill its display area horizontally and vertically, both).

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Program to demonstrate GridBagLayout:
import java.awt.*;
import java.applet.*;
/* <applet code="GridBagLayoutDemo.class" width="400" height="250">
</applet> */
public class GridBagLayoutDemo extends Applet{
public void init() {
GridBagLayout grid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
add(new Button("Button 1"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
add(new Button("Button 2"), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 2;
add(new Button("Button 3"), gbc);
}
public static void main(String[] args) {
GridBagLayoutDemo a = new GridBagLayoutDemo();
}
}
OOPS THROUGH JAVA T.Srinivasulu 4/9/23
Aditya College of Engineering & Technology

MenuBar, Menu, MenuItem:


• A top-level window can have a menu bar associated with it. A menu bar displays a list of top-level menu choices.
• Each choice is associated with a drop-down menu. This concept is implemented in the AWT by the following classes: MenuBar, Menu,
and MenuItem.
• In general, a menu bar contains one or more Menu objects. Each Menu object contains a list of MenuItem objects.
• Each MenuItem object represents something that can be selected by the user.
• Constructors:
o Menu( ) - creates an empty menu
o Menu(String optionName) - creates a menu with some string
o MenuItem( ) –Creates an empty item
o MenuItem(String itemName) -creates an item specified by the string .
• Once you have created a menu item, you must add the item to a Menu object by using add( ), which has the following general form:
o add(MenuItem item)
 Here, item is the item being added. Items are added to a menu in the order in which the calls to add( ) take place. The item is
returned. Once you have added all items to a Menu object, you can add that object to the menu bar by using this version of
add( ) defined by MenuBar:
o add(Menu menu)
 Here, menu is the menu being added. The menu is returned.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Program to demonstrate MenuBar:
MenuBar mb = new MenuBar();
import java.awt.event.*; // adding menu to menu bar
import java.awt.*; mb.add(m1);
public class MenuDemo extends Frame implements ActionListener // adding menu bar to container
{ setMenuBar(mb);
MenuItem mi1,mi2,mi3; }
public MenuDemo() public void actionPerformed(ActionEvent ae)
{ {
setTitle("Sample Menu"); if(ae.getSource() == mi3)
setSize(250,350); {
// creating menu items System.exit(0);
mi1 = new MenuItem("New"); }
mi2 = new MenuItem("Open"); }
mi3 = new MenuItem("Exit"); public static void main(String args[])
// registering menu item with listener {
mi3.addActionListener(this); MenuDemo md1 = new MenuDemo();
// creating menu object md1.setVisible(true);
Menu m1 = new Menu("File"); }
// adding menu items to menu object }
m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
// creating menu bar object

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

ScrollBar :

 Scrollbars are used to select continuous values through a range of integer values (the range set between maximum
and minimum).
 These scrollbars can either be set horizontally or vertically.
 The scrollbar’s maximum and minimum values can be set along with line increments and page increments.
– Scrollbar()
– Scrollbar(int direction)

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology
Program to demonstrate ScrollBar:
import java.awt.*;
public class ScrollEx1
{
Frame frame;
Label label1;
ScrollEx1()
{
frame = new Frame("Scrollbar");
label1 = new Label("Displaying a horizontal and verticial Scrollbar in the
Frame",Label.CENTER);
Scrollbar scrollB1 = new Scrollbar(Scrollbar.HORIZONTAL, 10, 40, 0, 100);
Scrollbar scrollB2 = new Scrollbar(Scrollbar.VERTICAL, 10, 60, 0, 100);
frame.add(label1,BorderLayout.CENTER);
frame.add(scrollB2,BorderLayout.EAST);
frame.add(scrollB1,BorderLayout.SOUTH);
frame.setSize(370,270);
frame.setVisible(true);
}
public static void main(String args[])
{
new ScrollEx1();
}
}

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

PYQs:
1. What are the different types of controls available in AWT?
2. What is the role of layout manager in AWT or Swing?
3. List out the differences between AWT and Swings.
4. Differentiate between swing components and AWT components.
5. Differentiate between grid layout and gridbag layout managers.
6. Differentiate between Text field and Text area.
7. Why layouts are needed?
8. Discuss in detail Menu bars and menus in Java with examples.
9. Explain about any two Layout Managers with example programs.
10. Explain any two AWT controls in java with suitable examples.
11. Discuss about different layouts in AWT?
12. What is the significance of Layout managers? Discuss briefly various layout managers.
13. Write a note on dialog box usage in user interfaces.
14. Explain about the components and containers of AWT.

OOPS THROUGH JAVA T.Srinivasulu 4/9/23


Aditya College of Engineering & Technology

OOPS THROUGH JAVA T.Srinivasulu 4/9/23

You might also like