0% found this document useful (0 votes)
18 views

Unit 1

The document discusses the Java Abstract Window Toolkit (AWT) and its core classes and components for building graphical user interfaces. It describes key AWT classes like Component, Container, Frame, Canvas and Applet. It also covers commonly used methods of these classes and the Graphics class for drawing on components.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Unit 1

The document discusses the Java Abstract Window Toolkit (AWT) and its core classes and components for building graphical user interfaces. It describes key AWT classes like Component, Container, Frame, Canvas and Applet. It also covers commonly used methods of these classes and the Graphics class for drawing on components.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

AWT :Abstract Window Toolkit

CO: 22517.a: Develop programs using GUI Framework (AWT and Swing).

Introduction

Java Graphics APIs - AWT and Swing - provide a huge set of reusable GUI components, such as
button, text field, label, choice, panel and frame for building GUI applications. You can simply reuse
these classes for GUI based Application..

AWT Packages:
AWT consists of number of packages.The commonly used packages
are: java.awt and java.awt.event - are commonly-used.
1. The java.awt package contains the core AWT graphics classes:
o GUI Component classes (such as Button, TextField, and Label),
o GUI Container classes (such as Frame, Panel, Dialog and ScrollPane),
o Layout managers (such as FlowLayout, BorderLayout and GridLayout),
o Custom graphics classes (such as Graphics, Color and Font).
2. The java.awt.event package supports event handling:
o Event classes (such as ActionEvent, MouseEvent, KeyEvent and WindowEvent),
o Event Listener Interfaces (such
as ActionListener, MouseListener, KeyListener and WindowListener),
o Event Listener Adapter classes (such as MouseAdapter, KeyAdapter,
and WindowAdapter).
AWT provides a platform-independent and device-independent interface to develop graphic programs
that runs on all platforms, such as Windows, Mac, and Linux.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

Term Description

Prepared by :Vaishali C. Sanap Page 1


AWT :Abstract Window Toolkit

Component Component is an object having a graphical representation that can be displayed on


the screen and that can interact with the user. For examples buttons, checkboxes, list
and scrollbars of a graphical user interface. Components are elementary GUI entities
(such as Button, Label, and TextField.)

Container Container (such as Frame, Panel and Applet) is a component that can contain other
components. Components added to a container are tracked in a list. The order of the
list will define the components' front-to-back stacking order within the container. If
no index is specified when adding a component to a container, it will be added to the
end of the list.

Panel Panel provides space in which an application can attach any other components,
including other panels.

Window Window is a rectangular area which is displayed on the screen. In different window
we can execute different program and display different data. Window provide us with
multitasking environment. A window must have either a frame, dialog, or another
window defined as its owner when it's constructed.

Frame A Frame is a top-level window with a title and a border. The size of the frame
includes any area designated for the border. Frame encapsulates window. It and has a
title bar, menu bar, borders, and resizing corners.

Canvas Canvas component represents a blank rectangular area of the screen onto which the
application can draw. Application can also trap input events from the use from that
blank area of Canvas component.

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by default


false.

Applet class and its methods

To do applet programming we need to extend Applet class.An applet is not a standalone application.
It is a mini program invoked within a larger program, such as an applet viewer or a Java-enabled
WorldWide Web ( WWW) browser. An applet depends on the viewer or browser o provide a context
in which to run.

Prepared by :Vaishali C. Sanap Page 2


AWT :Abstract Window Toolkit

Following are the methods of Applet class.

1. init(): In this method, the applet object is created by the browser. Because this method is
called before all the other methods, programmer can utilize this method to instantiate objects,
initialize variables, setting background and foreground colors in GUI etc.
2. start(): To make the applet active, the init() method calls start() method. In start() method,
applet becomes active and thereby eligible for processor time.
3. paint(): This method takes a java.awt.Graphics object as parameter. This class includes
many methods of drawing necessary to draw on the applet window. This is the place where
the programmer can write his code of what he expects from applet like animation etc
4. stop(): In this method the applet becomes temporarily inactive. An applet can come any
number of times into this method in its life cycle and can go back to the active state (paint()
method) whenever would like. It is the best place to have cleanup code. It is equivalent to
the blocked state of the thread.
5. destroy(): This method is called just before an applet object is garbage collected. This is the
end of the life cycle of applet. It is the best place to have cleanup code. It is equivalent to
the dead state of the thread.

Observe, the init() and destroy() methods are called only once in the life cycle. But, start(), paint() and
stop() methods are called a number of times.

Graphics Class and its methods

The Graphics class is the abstract super class for all graphics contexts which allow an application to
draw onto components that can be realized on various devices, or onto off-screen images as well.

Following table lists the methods of graphics class:

Sr. Methods Description Syntax


No.
1 DrawString Write a string abstract void drawString(String msg,int x,int y)
on applet
2 drawLine Draw a line abstract void drawLine(int x1,int y1,int x2,int y2)
from x1,y1 to
x2,y2
3 drawRect Draw a void drawRect(int x,int y,int width,int height)
rectangle
4 fillRect Draw a filled abstract void fillRect(int x,int y,int width,int height)
rectangle
5 drawOval Draw a oval abstract void drawOval(int x,int y,int width,int height)
6 fillOval Draw a filled abstract void fillOval(int x,int y,int width,int height)

Prepared by :Vaishali C. Sanap Page 3


AWT :Abstract Window Toolkit

oval
7 drawRoundRect Draw a abstract void drawRoundRect(int x,int y,int width,int
rounded height,int width_of_angle__corner,int
rectangle height_of_angle_of_corner)
8 fillRoundRect Draw a filled abstract void fillRoundRect(int x,int y,int width,int height,int
rounded width_of_angle__corner,int height_of_angle_of_corner)
rectangle
9 drawArc Draw a arc abstract void drawArc(int x,int y,int width,int height,int
starting_angle,int sweep_angle)
10 fillArc Draw a filled abstract void fillArc(int x,int y,int width,int height,int
arc. starting_angle,int sweep_angle)
11 drawPolygon Draw a void drawPolygon(int x[],int y[],int length_of _array)
polygon
12 fillPolygon Draw a filled abstract void fillPolygon(int x[],int y[],int length_of _array)
polygon
13 setColor Set a color abstract void setColor(Color c)
14 setFont Set a font abstract void setFont(Font font)
15 getFont Gets the abstract Font getFont()
current font.

Example : Simple Applet Program

import java.applet.Applet;
import java.awt.*;

public class SimpleApplet extends Applet


{
public void init()
{
setBackground(Color.red);
setForeground(Color.blue);
}
public void paint(Graphics g)
{
g.drawString("hello",100,100);
}
}
/*<applet code=SimpleApplet width=500 height=500></applet> */

Frame Class
Frame is a sub class of Window and have resizing canvas. It is a container that contain several
different components like button, title bar, textfield, label etc. In Java, most of the AWT applications
are created usingFrame window.
Constructors

Frame() Constructs a new instance of Frame that is initially invisible.

Frame(String title) Constructs a new, initially invisible Frame object with the specified title.

Prepared by :Vaishali C. Sanap Page 4


AWT :Abstract Window Toolkit

This class also inherits methods from the following classes:

 java.awt.Window
 java.awt.Container
 java.awt.Component
 java.lang.Object

There are two ways to create a Frame. They are,


1. By Instantiating Frame class
2. By extending Frame class

Example1: By Instantiating Frame class

import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame();
Label lb = new Label("welcome to java graphics");
lb.setBounds(10,10,100,50);
fm.add(lb);
fm.setSize(300, 300);
fm.setVisible(true);
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}

Example2: By extending Frame class

import java.awt.*;

public class SimpleFrame extends Frame


{
SimpleFrame()
{
setLayout(null);
setVisible(true);
setSize(500,500);
setTitle("hello");
}
public void paint(Graphics g)
{
g.drawString("how are you?",100,50);
}
public static void main(String args[])

Prepared by :Vaishali C. Sanap Page 5


AWT :Abstract Window Toolkit

{
SimpleFrame f=new SimpleFrame();
}
}

AWT Component Classes


AWT provides many ready-made and reusable GUI components. The frequently-used
are: Button, TextField, Label, Checkbox, CheckboxGroup (radio buttons), List, and Choice, as
illustrated below.

Label Class
A java.awt.Label provides a text description message. As we know that System.out.println() prints to
the system console, not to the graphics screen. You could use a Label to label another component
(such as text field) or provide a text description.
Constructors and Methods

public Label(String strLabel, int alignment) Construct a Label with the given text String, of the
text alignment.
Three static constants Label.LEFT, Label.RIGHT,
and Label.CENTER are defined in the class for you to
specify the alignment .
public Label(String strLabel) Construct a Label with the given text String in default
of left-aligned
public Label() Construct an initially empty Label
public String getText() The getText() method can be used to read the Label's
text.
public void setText(String strLabel) setText() method can be used to modify the Label's
text.
public int getAlignment() the getAlignment() method can be used to retrieve
the alignment of the text.

public void setAlignment(int alignment) the setAlignment() method can be used to modify the

Prepared by :Vaishali C. Sanap Page 6


AWT :Abstract Window Toolkit

alignment of the text.

Example
Label l=new Label("Enter ID", Label.RIGHT);
add(l);
l.setText("Enter password");
l.getText();

Button Class
A java.awt.Button is a GUI component that triggers a certain programmed action upon clicking.

Constructors and Methods

public Button(String buttonLabel) Construct a Button with the given label


public Button() Construct a Button with empty label
public String getLabel() Get the label of this Button instance
public void setLabel(String buttonLabel) Set the label of this Button instance
public void setEnable(boolean enable) Enable or disable this Button. Disabled Button
cannot be clicked.
void addActionListener(ActionListener l) Adds the specified action listener to receive action
events from this button.
void removeActionListener(ActionListener l) Removes the specified action listener so that it no
longer receives action events from this button.
String getActionCommand() Returns the command name of the action event fired
by this button.
void setActionCommand(String command) Sets the command name for the action event fired by
this button.

Example
Button b = new Button("Red");
add(b);
b.setLabel("green");
b.getLabel();

Example: Button with ActionListener

import java.awt.*;
import java.awt.event.*;
public class Frame_Button extends Frame implements ActionListener
{

String msg=" ";


Button b;
Label l;

Prepared by :Vaishali C. Sanap Page 7


AWT :Abstract Window Toolkit

Frame_Button()
{
setLayout(null);
setSize(500,500);
setVisible(true);
b=new Button("Show");
b.setBounds(100,100,200,100);
add(b);

l=new Label();
l.setBounds(100,400,200,100);
add(l);

public void paint(Graphics g)


{
l.setText(msg);
}
public static void main(String args[])
{
Frame_Button f=new Frame_Button();
}
}

TextField

A java.awt.TextField is single-line text box for users to enter texts. (There is a multiple-line text box
called TextArea.) .Hitting the "ENTER" key on a TextField object triggers an action-event.

Constructors and Methods

public TextField(String strInitialText, int Construct a TextField instance with the given initial
columns) text string with the number of columns.
public TextField(String strInitialText) Construct a TextField instance with the given initial
text string.
public TextField(int columns) Construct a TextField instance with the number of
columns.
public String getText() Get the current text on this TextField instance

public void setText(String strText) Set the display text on this TextField instance. Take
note that getText()/SetText() operates on String.
public void setEditable(boolean editable) Set this TextField to editable (read/write) or non-
editable (read-only)
void addActionListener(ActionListener l) Adds the specified action listener to receive action
events from this text field.
void removeActionListener(ActionListener l) Removes the specified action listener so that it no
longer receives action events from this text field.

Prepared by :Vaishali C. Sanap Page 8


AWT :Abstract Window Toolkit

Example
TextField t = new TextField(30);
add(t);
TextField t1 = new TextField();
t1.setEditable(false) ;
add(t1);
int number = Integer.parseInt(tfInput.getText());
number *= number;
t1.setText(number + "");

Example : TextField with ActionListener

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

public class Frame_TextField extends Frame implements ActionListener


{
String msg="hello";
TextField t1,t2;
Label l;
Frame_TextField()
{
setLayout(null);
setSize(500,500);
setVisible(true);
t1=new TextField(12);
t1.setBounds(50,100,100,100);
add(t1);
t2=new TextField(8);
t2.setBounds(300,100,100,100);
t2.setEchoChar('*');
add(t2);

public void paint(Graphics g)


{
g.drawString("name="+ t1.getText(),100,400);
g.drawString("password="+ t2.getText(),100,450);
}
public static void main(String args[])
{
Frame_TextField f=new Frame_TextField();
}
}

Prepared by :Vaishali C. Sanap Page 9


AWT :Abstract Window Toolkit

TextArea
The TextArea control in AWT provide us multiline editor area. The user can type here as much as he
wants. When the text in the text area become larger than the viewable area the scroll bar is
automatically appears which help us to scroll the text up & down and right & left.

Constructors and Methods

TextArea() Constructs a new text area with the empty string as


text.
TextArea(int rows, int columns) Constructs a new text area with the specified number
of rows and columns and the empty string as text.
TextArea(String text) Constructs a new text area with the specified text.

TextArea(String text, int rows, int columns) Constructs a new text area with the specified text, and
with the specified number of rows and columns.
TextArea(String text, int rows, int columns, Constructs a new text area with the specified text, and
int scrollbars) with the rows, columns, and scroll bar visibility as
specified below:

SCROLLBARS_BOTH -- Create and display both


vertical and horizontal scrollbars.

SCROLLBARS_HORIZONTAL_ONLY -- Create
and display horizontal scrollbar only.

SCROLLBARS_NONE -- Do not create or display


any scrollbars for the text area.

SCROLLBARS_VERTICAL_ONLY -- Create and


display vertical scrollbar only.
void setColumns(int columns) Sets the number of columns for this text area.
int getColumns() Returns the number of columns in this text area.
int getRows() Returns the number of rows in the text area.
insert(String str, int pos) Inserts the specified text at the specified position in
this text area.
append(String str) Appends the given text to the text area's current text.
replaceRange(String str, int start, int end) Replaces text between the indicated start and end
positions with the specified replacement text.

Example:

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

public class Frame_TextArea extends Frame


{
String msg="hello everyone,This unit is introduction about AWT and its components.";
TextArea t1;
Frame_TextArea()

Prepared by :Vaishali C. Sanap Page 10


AWT :Abstract Window Toolkit

{
setLayout(null);
setSize(500,500);
setVisible(true);
t1=new TextArea(msg);
t1.setBounds(50,100,100,100);
add(t1);
}

public static void main(String args[])


{
Frame_TextArea f=new Frame_TextArea();
}
}

Checkbox Class
Checkbox control is used to turn an option on(true) or off(false). There is label for each checkbox
representing what the checkbox does.The state of a checkbox can be changed by clicking on it.

Constructors and Methods

Checkbox() Creates a check box with an empty string for its label.

Checkbox(String label) Creates a check box with the specified label.

Checkbox(String label, boolean state) Creates a check box with the specified label and sets
the specified state.
Checkbox(String label, boolean state, Constructs a Checkbox with the specified label, set to
CheckboxGroup group) the specified state, and in the specified check box
group.
Checkbox(String label, CheckboxGroup Creates a check box with the specified label, in the
group, boolean state) specified check box group, and set to the specified
state.
String getLabel() Gets the label of this check box.

boolean getState() Determines whether this check box is in


the on or off state.

void setLabel(String label) Sets this check box's label to be the string argument.

void setState(boolean state) Sets the state of this check box to the specified state.

void addItemListener(ItemListener l) Adds the specified item listener to receive item events
from this check box.

void removeItemListener(ItemListener l) Removes the specified item listener so that the item
listener no longer receives item events from this check
box.

Prepared by :Vaishali C. Sanap Page 11


AWT :Abstract Window Toolkit

Example: checkbox with ItemListener

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

public class Frame_CheckBox extends Frame implements ItemListener


{
Checkbox cb1,cb2;
String msg="";
Frame_CheckBox()
{
setLayout(null);
setVisible(true) ;
setSize(1000,1000);
setTitle("hello");

cb1=new Checkbox("Java",false);
cb1.setBounds(100,200,50,50);
add(cb1);

cb2=new Checkbox("C++",false);
cb2.setBounds(100,300,50,50);
add(cb2);

public void paint(Graphics g)


{
g.drawString(" U have Selected "+ msg,100,200 );
}
public static void main(String args[])
{
Frame_CheckBox f=new Frame_CheckBox();
}
}

CheckboxGroup Class(Radiobutton)
A check box group is a set of checkboxes in which one and only one checkbox can be checked at
anyone time. Any other previously selected checkbox in the group is unchecked. These checkboxes
are sometimes called radio buttons.A "CheckboxGroup" differs from a "Checkbox" in that only one
item in the "CheckboxGroup" can be selected at a time.

Constructors and Methods

Prepared by :Vaishali C. Sanap Page 12


AWT :Abstract Window Toolkit

CheckboxGroup() Creates a new instance of CheckboxGroup.

getSelectedCheckbox () Gets the Checkbox component group currentlyselected.


setSelectedCheckbox (Checkbox) Determines which Checkbox component selected group.

Example:
import java.awt.*;
import java.awt.event.*;

public class Frame_RadioButton extends Frame implements ItemListener


{
Checkbox cb1,cb2;
CheckboxGroup cbg;
String msg="";
Frame_RadioButton()
{
setLayout(null);
setVisible(true) ;
setSize(1000,1000);
setTitle("hello");
cbg=new CheckboxGroup();
cb1=new Checkbox("Java",false,cbg);
cb1.setBounds(100,200,50,50);
add(cb1);
cb2=new Checkbox("C++",false,cbg);
cb2.setBounds(100,300,50,50);
add(cb2);

public void paint(Graphics g)


{
g.drawString(" U have Selected "+ msg,100,200 );
}
public static void main(String args[])
{
Frame_RadioButton f=new Frame_RadioButton();
}
}
Choice Class
The Choice component is a combination of textfield and drop down list of items. User can make
selection by clicking at an item from the list or by typing into the box. Note that you cannot select
multiple items from the list.

Constructors and Methods

Choice() Creates an empty choice box;


void addItem(String item) use addItem() to populate
int countItems() Useful for interrogating the Choice contents
String getItem(int index) From 0 to countItems() -1

Prepared by :Vaishali C. Sanap Page 13


AWT :Abstract Window Toolkit

int getSelectedIndex() Tells which item is selected by number


String getSelectedItem() Returns the selected item’s text
void select(int pos) Make a particular cell the default
void select(String str) Highlight the first cell with text equal to str

Example

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

public class Frame_Choice extends Frame implements ItemListener


{
String msg="";
Choice c;
Frame_Choice()
{
setLayout(null);
setVisible(true);
setSize(1000,1000);
setTitle("hello");
c=new Choice();
c.add("Sunday");
c.add("Monday");
c.add("Tuesday");
c.add("Wednesday");
c.setBounds(100,100,100,100);
add(c);

public void paint(Graphics g)


{
g.drawString(" U have Selected "+ msg,100,200 );
}
public static void main(String args[])
{
Frame_Choice f=new Frame_Choice();
}}

List Class
The java.awt.List component , known as a listbox or list box, is similar to the Choice component,
except it shows multiple items at a time and user is allowed to select either one or multiple items at a
time. When the numbers of items in the list exceed the available space, the scrollbar will be displayed
automatically.

Constructors and Methods

List() Creates a new scrolling list.


List(int rows) Creates a new scrolling list initialized with the specified

Prepared by :Vaishali C. Sanap Page 14


AWT :Abstract Window Toolkit

number of visible lines.


List(int rows, boolean multipleMode) Creates a new scrolling list initialized to display the
specified number of rows.
void add(String item) Adds the specified item to the end of scrolling list
void add(String item, int index) Adds the specified item to the the scrolling list at the
position indicated by the index.
void addActionListener(ActionListener l) Adds the specified action listener to receive action events
from this list.
void addItemListener(ItemListener l) Adds the specified item listener to receive item events
from this list.
int[] getSelectedIndexes() Gets the selected indexes on the list.
int getSelectedIndex() Gets the index of the selected item on the list,
String getSelectedItem() Gets the selected item on this scrolling list.
String[] getSelectedItems() Gets the selected items on this scrolling list.
Void clear() Empty the list

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

public class Frame_List extends Frame implements ItemListener


{
String msg="";
List l;
Frame_List()
{
setLayout(null);
setVisible(true);
setSize(1000,1000);
setTitle("hello");
l=new List(5,true);
l.add("Sunday");
l.add("Monday");

l.add("Tuesday");
l.add("Wednesday");

l.setBounds(100,100,100,100);
add(l);
}

public static void main(String args[])


{
Frame_List f=new Frame_List();
}
}

ScrollBar

Prepared by :Vaishali C. Sanap Page 15


AWT :Abstract Window Toolkit

A scrollbar is a component that allows a user to select any numeric value by dragging a slider within a
range defined by a minimum and maximum. A scrollbar may be oriented horizontally or vertically. A
scrollbar consists of several individual parts: arrows (the buttons at each end of the scrollbar), a slider
box or thumb (scrollable box you slide) and a track (part of the scrollbar you slide the thumb in).

Constructors and Methods

Scrollbar() Creates a new scrollbar.

Scrollbar(int style) creates a scroll bar with specified orientation, that is,
Scrollbar.HORIZONTAL or Scrollbar.VERTICAL.
Scrollbar(int style, int initialvalue, int specifies the initial value and the maximal value along with
thumbsize,int min, int max) the thumb size.
int getMaximum() What is the largest value the scrollbar will report?
int getMiniimum() What is the smallest value the scrollbar will report?
void setValue(int value) Set the handle at this value
void setValues(int value, int visible, Reset the scrollbar to reflect the bounds passed in
int minimum, int maximum)
int getValue() What is the current value of the bar?

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

public class Frame_Scroll extends Frame implements AdjustmentListener


{
String msg="";
Scrollbar s;
Frame_Scroll()
{
setLayout(null);
setVisible(true);
setSize(1000,1000);
setTitle("hello");
s=new Scrollbar(Scrollbar.VERTICAL,0,1,0,100);

s.setBounds(100,100,50,100);
add(s);
s.addAdjustmentListener(this);
}

public static void main(String args[])


{
Frame_Scroll f=new Frame_Scroll();
}
}

Layout Managers and Panel

Prepared by :Vaishali C. Sanap Page 16


AWT :Abstract Window Toolkit

A layout manager is an object that controls the size and position of components inside a container
object. A container has a 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. It is easy to use the container.setLayout method to change the the layout
manager and you can define your own layout by implementing java.awt.LayoutManager interface.
AWT provides the following layout managers (in package java.awt):

1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridBagLayout

Container's setLayout()
A 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.
For example,
Frame f= new Frame();
f.setLayout(new FlowLayout());
f.add(new Label("One"));
f.add(new Label("Two"));
f.add(new Label("Three"));

Container's getLayout()
You can get the current layout via Container's getLayout().
Frame f = new Frame();
System.out.println(f.getLayout());

1. FlowLayout
In the java.awt.FlowLayout, components are arranged from left-to-right inside the container in the
order that they are added (via methodaContainer.add(aComponent)). When one row is filled, a new
row will be started. The actual appearance depends on the width of the display window.

Prepared by :Vaishali C. Sanap Page 17


AWT :Abstract Window Toolkit

Constructors
public FlowLayout(); Constructs a new FlowLayout with a centered alignment
and a default 5-unit horizontal and vertical gap.
public FlowLayout(int align); Constructs a new FlowLayout with the specified
alignment and a default 5-unit horizontal and vertical gap.
We can use one of the followings alligment constants.
FlowLayout.LEFT (or LEADING), FlowLayout.RIGHT
(or TRAILING), or FlowLayout.CENTER

public FlowLayout(int align, int hgap, int Creates a new flow layout manager with the indicated
vgap); alignment and the indicated horizontal and vertical gaps.

getAlignment () Gets the alignment of this layout.

getHgap () Gets the horizontal spacing.

getVgap () Gets the vertical spacing.

setAlignment (int) Specifies the alignmentof this layout.

setHgap (int) Specifies the horizontal spacing.

setVgap (int) Specifies the vertical spacing.

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

public class FlowLayoutDemo extends Frame


{
private Button btn1, btn2, btn3, btn4, btn5, btn6;

public FlowLayoutDemo ()
{
setLayout(new FlowLayout());

btn1 = new Button("Button 1");


add(btn1);
btn2 = new Button("This is Button 2");
add(btn2);
btn3 = new Button("3");
add(btn3);
btn4 = new Button("Another Button 4");
add(btn4);
btn5 = new Button("Button 5");
add(btn5);

Prepared by :Vaishali C. Sanap Page 18


AWT :Abstract Window Toolkit

btn6 = new Button("One More Button 6");


add(btn6);

setTitle("FlowLayout Demo");
setSize(280, 150);
setVisible(true);
}

public static void main(String[] args)


{
new FlowLayoutDemo();
}

2. BorderLayout
In java.awt.BorderLayout, the container is divided into 5 zones: EAST, WEST, SOUTH, NORTH,
and CENTER. Components are added using method
aContainer.add(aComponent)
aContainer.add(acomponent, aZone),
First method adds the components without specifying the zone.
Second method add components on specified zone which could be one of the followings:
1. BorderLayout.NORTH ,
2. BorderLayout.SOUTH ,
3. BorderLayout.WEST
4. BorderLayout.EAST,
5. BorderLayout.CENTER.
You need not add 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.

Method Description
BorderLayout () Creates a new layout manager without spacing between regions.
BorderLayout (int, int) Creates a new layout manager with the spacing horizontaland
vertical specified. By default hgap=0, vgap=0
getHgap () Gets the horizontal spacing.

Prepared by :Vaishali C. Sanap Page 19


AWT :Abstract Window Toolkit

getVgap () Gets the vertical spacing.


setHgap (int) Specifies the horizontal spacing.
setVgap (int) Specifies the vertical spacing.

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

public class BorderLayoutDemo extends Frame


{
private Button btnNorth, btnSouth, btnCenter, btnEast, btnWest;

public BorderLayoutDemo ()
{
setLayout(new BorderLayout(3, 3));

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");
setSize(280, 150);
setVisible(true);
}

public static void main(String[] args)


{
new BorderLayoutDemo();
}

3. 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)).

Prepared by :Vaishali C. Sanap Page 20


AWT :Abstract Window Toolkit

GridLayout () Creates a GridLayoutmanager with


a defaultrow and a column.
GridLayout (int, int) Creates a GridLayoutmanager with the number
of rows and columnsspecified.
GridLayout (int, int, int,int) Creates a GridLayout manager with the number
of specified rows
andcolumns and alignment,horizontal and
verticalspacing data. By default: rows=1,
cols=0, hgap=0, vgap=0
getColumns () Gets the number of columns in the layout.
getHgap () Gets the horizontal spacing.
getRows () Gets the number of rowsof the layout.
getVgap () Gets the vertical spacing.
SetColumns () Specifies the number of columns in the layout.
setHgap (int) Specifies the horizontal spacing.
SetRows () Specifies the number of rows of the layout.
setVgap (int) Specifies the vertical spacing.

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

public class GridLayoutDemo extends Frame


{
private Button btn1, btn2, btn3, btn4, btn5, btn6;

public GridLayoutDemo ()
{
setLayout(new GridLayout(3, 2, 3, 3));

btn1 = new Button("Button 1");


add(btn1);
btn2 = new Button("This is Button 2");
add(btn2);
btn3 = new Button("3");
add(btn3);
btn4 = new Button("Another Button 4");
add(btn4);
btn5 = new Button("Button 5");
add(btn5);

Prepared by :Vaishali C. Sanap Page 21


AWT :Abstract Window Toolkit

btn6 = new Button("One More Button 6");


add(btn6);

setTitle("GridLayout Demo");
setSize(280, 150);
setVisible(true);
}

public static void main(String[] args)


{
new GridLayoutDemo();
}

}
If rows or cols is 0, but not both, then any number of components can be placed in that column or
row. If both the rows and cols are specified, the cols value is ignored. The actual cols is determined by
the actual number of components and rows.

4. CardLayout
The java.awt.CardLayout layout manager is significantly different from the other layout managers.
Unlike other layout managers, that display all the components within the container at once, a
CardLayout layout manager displays only one component at a time (The component could be a
component or another container). Each component in a container with this layout fills the entire
container. The name cardlayout evolves from a stack of cards where one card is piled upon another
and only one of them is shown. In this layout, the first component that you add to the container will be
at the top of stack and therefore visible and the last one will be at the bottom.

Java.awt.CardLayout the class selected thefollowing constructors and methods:


Method Description
CardLayout () Creates a new layout manager without spacing between
regions.
CardLayout (int, int) Creates a new layout manager with the
spacing horizontal and vertical specified.
first (Container) Displays the first component added to the
layout container specified
getHgap () Gets the horizontal spacing.
getVgap () Gets the vertical spacing.
last (Container) Returns the last component added to the
layout container specified
next (Container) Returns the next component added to the
layout container specified
previous (Container) Displays the previous component added
to the layout container specified
setHgap (int) Specifies the horizontal spacing.
setVgap (int) Specifies the vertical spacing.

Prepared by :Vaishali C. Sanap Page 22


AWT :Abstract Window Toolkit

Example:
import java.awt.*;
import java.awt.event.*;
class CardLayoutDemo extends Frame implements ActionListener
{
CardLayout card = new CardLayout(20,20);
CardLayoutDemo()
{

setTitle("CardLayout in Java Example");


setSize(220,150);
setVisible(true);

setLayout(card);
Button Btnfirst = new Button("First ");
Button BtnSecond = new Button ("Second");
Button BtnThird = new Button("Third");
add(Btnfirst,"Card1");
add(BtnSecond,"Card2");
add(BtnThird,"Card3");
Btnfirst.addActionListener(this);
BtnSecond.addActionListener (this);
BtnThird.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
card.next(this);
}

public static void main(String args[])


{
CardLayoutDemo frame = new CardLayoutDemo();

}
}

5. GridBagLayout
The java.awt.GridBagLayout layout manager is the most powerful and flexible of all the predefined
layout managers but more complicated to use. Unlike GridLayout where the component are arranged
in a rectangular grid and each component in the container is forced to be the same size, in
GridBagLayout, components are also arranged in rectangular grid but can have different sizes and can
occupy multiple rows or columns.

In order to create GridBagLayout, we first instantiate the GridBagLayout class by using its only no-
arg constructor

Prepared by :Vaishali C. Sanap Page 23


AWT :Abstract Window Toolkit

public GridLayout();

and defining it as the current layout manager. The following statements accomplish this task;

GridBagLayout layout = new GridBagLayout();

setLayout(layout);

A GridBagLayout layout manager requires a lot of information to know where to put a component in
a container. A helper class called GridBagConstraints provides all this information. It specifies
constraints on how to position a component, how to distribute the component and how to resize and
align them. Each component in a GridBagLayout has its own set of constraints, so you have to
associate an object of type GridBagConstraints with each component before adding component to the
container.

Instance variables to manipulate the GridBagLayout object Constraints are:


Variable Role
gridx and These contain the coordinates of the origin of the grid. They allow at specific position of
gridy a component positioning. By default, they have GrigBagConstraint.
RELATIVE value which indicates that a component can be stored to the right of
previous
gridwidth Define how many cells will occupy component (height and width). By default
, is 1. The indication is relative to the other components of the line or the column. The
gridheigh GridBagConstraints.REMAINDER value specifies that the next component inserted will
t be the last of the line or the current column. the
value GridBagConstraints.RELATIVE up the component after the last component of
a row or column.
fill Defines the fate of a component smaller than the grid cell.
GridBagConstraints.NONE retains the original size: Default
GridBagConstraints.HORIZONTAL expanded horizontally
GridBagConstraints.VERTICAL GridBagConstraints.BOTHexpanded vertically expande
d to the dimensions of the cell
ipadx, Used to define the horizontal and vertical expansion of components. not works
ipady if expansion is required by fill. The default value is (0,0).
anchor When a component is smaller than the cell in which it is inserted, it can be
positioned using this variable to define theside from which the control
should be aligned within the
cell.Possible variables NORTH, NORTHWEST, NORTHEAST,
SOUTH, SOUTHWEST, SOUTHEAST, WEST and EAST
weightx, Used to define the distribution of space in case of change of dimension
weighty

Example:
import java.awt.*;
class GridBagLayoutDemo extends Frame
{
GridBagLayoutDemo()
{

Prepared by :Vaishali C. Sanap Page 24


AWT :Abstract Window Toolkit

Label lblName = new Label("Name");


TextField txtName =new TextField(10);
Label lblcomments = new Label("Comments");
TextArea TAreaComments=new TextArea(6,15);
Button btnSubmit = new Button("Submit");
setLayout(new GridBagLayout());
GridBagConstraints gc =new GridBagConstraints();
add(lblName,gc,0,0,1,1,0,0);
add(txtName,gc,1,0,1,1,0,20);
add(lblcomments,gc,0,1,1,1,0,0);
add(TAreaComments,gc,1,1,1,1,0,60);
add(btnSubmit,gc,0,2,2,1,0,20);
}
void add(Component comp,GridBagConstraints gc,int x,int y,int w,int h,int wx,int wy)
{
gc.gridx = x;
gc.gridy = y;
gc.gridwidth = w;
gc.gridheight= h;
gc.weightx = wx;
gc.weighty = wy;
add(comp,gc);
}
}
class GridBagLayoutJavaExample
{
public static void main(String args[])
{
GridBagLayoutDemo frame = new GridBagLayoutDemo();
frame.setTitle("GridBagLayout in Java Example");
frame.setSize(300,200);
frame.setVisible(true);
}
}

Menu Bars and Menus:


Menus are very familiar to a programmer in Windows environment. A menu comes with a
pull-down list of menu items from which user can select one at a time. When a lot of options
in different categories exist to be opted by the user, menus are the best choice as they take
less space on the frame. A click on the MenuItem generates ActionEvent and is handled by
ActionListener. Java AWT Menu and MenuItem are not components as they are not
subclasses of java.awt.Component class. They are derived from MenuComponent class.
Following hierarchy illustrates.

Java AWT Menu Hierarchy

Prepared by :Vaishali C. Sanap Page 25


AWT :Abstract Window Toolkit

Menus creation involves lot of classes like MenuBar, Menu and MenuItem and one is
added to the other.

MenuComponent is the super most class of all menu classes; like Component is the super
most class for all component classes like Button, Frame etc. MenuBar is capable to hold the
menus and Menu can hold menu items. Menus are placed on menu bar.

Steps of Creating Java AWT Menu

Creation of menus involves many steps to be followed in an order. Following are the steps.

1. Create menu bar


2. Add menu bar to the frame
3. Create menus
4. Add menus to menu bar
5. Create menu items
6. Add menu items to menus
7. Event handling

In the following program, three menus are created and populated with menu items. User's
selected menu item information is displayed in the text area.

Constructors and Methods

MenuBar() Create Menubar


Menu() To create a default menu.
Menu(String name) To create a menu with name
Menu(String name, Boolean tearoff) removable is true means menu can be torn off
MenuItem( ) To create a default menu item.
MenuItem(String itemname) Create Menu item by using name of menu item.
MenuItem(String itemname, MenuShortcut Create Menu item by using name of menu item and
shortcut) shortcut.
MenuItem add(MenuItem mi) Adds the specified menu item to this menu.
void add(String label) Adds an item with the specified label to this menu.
void addSeparator() Adds a separator line, or a hypen, to the menu at the

Prepared by :Vaishali C. Sanap Page 26


AWT :Abstract Window Toolkit

current position.
MenuItem getItem(int index) Gets the item located at the specified index of this
menu.
int getItemCount() Get the number of items in this menu.
void insert(MenuItem menuitem, int index) Inserts a menu item into this menu at the specified
position.
void insert(String label, int index) Inserts a menu item with the specified label into this
menu at the specified position.
void insertSeparator(int index) Inserts a separator at the specified position.
Boolean isTearOff() Indicates whether this menu is a tear-off menu.
void remove(int index) Removes the menu item at the specified index from
this menu.
void remove(MenuComponent item) Removes the specified menu item from this menu.
void removeAll(). Removes all items from this menu

You can create checkable menu item by using a class CheckboxMenuItem, which is a subclass of
menu item. It has the following constructors.

 CheckboxMenuItem()
 CheckboxMenuItem(String itemname)
 CheckboxMenuItem(String itemname, Boolean on)

Example :

import java.awt.*;
import java.awt.event.*;
public class MenuDemo extends Frame implements ActionListener
{

public MenuDemo()
{
MenuBar mBar = new MenuBar();
setMenuBar(mBar); // add menu bar to frame

Menu files = new Menu("Colors");


Menu exit = new Menu("Exit");

mBar.add(files); // add menus to menu bar


mBar.add(exit);

MenuItem mi1 = new MenuItem("RED");


files.add(mi1); //add menuitem in menu
files.add(new MenuItem("GREEN"));
files.addSeparator();
files.add(new MenuItem("BLUE"));

exit.add(new MenuItem("Close"));

Prepared by :Vaishali C. Sanap Page 27


AWT :Abstract Window Toolkit

setTitle("Menu Demo");
setSize(400, 400);
setVisible(true);
}
public static void main(String args[])
{
new MenuDemo();
}
}

Dialog

Dialog boxes are pop-up windows on the screen that appear for a small time to take either input or
display output while a main application is running. Dialog boxes are generally used to draw special
attention of the user like displaying warnings. Dialog box is a top-level window that comes with a
border including a title bar.

Two types of dialog boxes exist – modal and modeless. Modal dialog box does not allow the user to
do any activity without dismissing (closing) it; example is File Deletion Confirmation dialog box.
Modeless dialog box permits the user to do any activity without closing it; example is Find and
Replace dialog box of MS Word. Java supports both styles of dialog boxes.

Following is the class signature

public class Dialog extends Window

Constructors

If any constructor is passed a null parent, the constructor throws the run-time
exception IllegalArgumentException.

1. Dialog (Frame parent): This constructor creates an instance of Dialog with no title and
with parent as the Frame owning it. It is not modal and is initially resizable.

2. Dialog (Frame parent, boolean modal): This constructor creates an instance of Dialog with
no title and with parent as the Frame owning it. If modal is true, the Dialog grabs all the user
input of the program until it is closed. If modal is false, there is no special behavior associated
with the Dialog.

3. Dialog (Frame parent, String title): This version of the constructor creates an instance
of Dialog with parent as the Frame owning it and a window title of title. It is not modal and is
initially resizable.

Prepared by :Vaishali C. Sanap Page 28


AWT :Abstract Window Toolkit

4. Dialog (Frame parent, String title, boolean modal):This version of the constructor creates an
instance of Dialog with parent as the Frame owning it and a window title of title.
If mode is true, the Dialog grabs all the user input of the program until it is closed.
If modal is false, there is no special behavior associated with the Dialog.

Example:

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

public class DialogDemo extends Dialog implements ActionListener


{
DialogDemo(Frame parent,String title)
{
super(parent,title,false);
setLayout(new FlowLayout());
setSize(300,200);

Button b=new Button("cancel");;


add(b);
b.addActionListener(this);

}
public void actionPerformed(ActionEvent ae)
{
dispose();
}
public void paint(Graphics g)
{
g.drawString("this is in the dialogbox",10,70);
}
public static void main(String args[])
{
Frame f1=new Frame();
DialogDemo dd=new DialogDemo(f1,"hello");
dd.setVisible(true);
}
}

File dialog:

The FileDialog class provides a File Open or Save dialog box enabling us to access the local file
system. The FileDialog class of Java is OS dependent and calls operating system's specificOpen File
dialog box or Save dialog box. The advantage of this is that the users of Java program will see
familiar screens.Following is the class signature
public class FileDialog extends Dialog

Prepared by :Vaishali C. Sanap Page 29


AWT :Abstract Window Toolkit

Constructor:

a. FileDialog(Frame):Creates a file dialog for loading a file.


b. FileDialog(Frame, String):Creates a file dialog window with the specified title for loading a file.
c. FileDialog(Frame, String, int):Creates a file dialog window with the specified title for loading or
saving a file.

Example:

import java.awt.*;
import java.awt.event.*;
public class DialogDemo
{
public static void main(String args[])
{
Frame f1=new Frame();
FileDialog fd=new FileDialog(f1,"File dialog");
fd.setVisible(true);

}
}

Closing of Java Frame


The frame created by the programmer and displayed on the monitor comes with a title bar and three
icons (buttons) on the title bar – Minimize, Maximize and Close. The first two works implicitly and
the Close does not work and requires extra code to close the frame.

Four styles exists to close the frame are

1. Using WindowListener
2. Using WindowAdapter
3. Using Component
4. Using Anonymous inner class

Java Frame Close using WindowListener


In the following program, WindowListener interface is implemented to close the frame. The seven
abstract methods of WindowListener interface are overridden.

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

public class FrameClosing1 extends Frame implements WindowListener


{
public FrameClosing1()
{
setTitle("Frame closing Style 1");

Prepared by :Vaishali C. Sanap Page 30


AWT :Abstract Window Toolkit

setSize(300, 300);
setVisible(true);
addWindowListener(this);
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowOpened(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowActivated(WindowEvent e) { }
public void windowDeactivated(WindowEvent e) { }
public void windowIconified(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { }

public static void main(String args[])


{
FrameClosing1 fc=new FrameClosing1();
}
}
Java Frame Close using WindowAdapter
Using an adapter class is advantageous over a listener that allows us to override only one or two
abstract methods we require and not compulsorily all the abstract methods of a listener. Adapter
classes are discussed elaborately later. But the problem with adapters is they are designed as abstract
classes and thereby we cannot extend to our class as the class extends already Frame (Java does not
support multiple inheritance). To overcome this problem, we created one more class CloseMe and
extended WindowAdapter to it.

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class FrameClosing2 extends Frame


{
public FrameClosing2()
{
setTitle("Frame closing Style 2");
setSize(300, 300);
setVisible(true);

CloseMe cm = new CloseMe();


addWindowListener(cm);

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

Prepared by :Vaishali C. Sanap Page 31


AWT :Abstract Window Toolkit

class CloseMe extends WindowAdapter


{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}

Prepared by :Vaishali C. Sanap Page 32

You might also like