Abstract Window Toolkit
Abstract Window Toolkit
Packet
03 0423
Abstract Window Toolkit: (AWT)
Java AWT is an API to develop GUI or window-
based application in java.
Java AWT provides many of user interface
objects are called “Components” of the Java
AWT.
Java AWT components are platform-dependent
that means components are displayed according
to the view of operating system.
AWT is heavyweight. Its components use the
resources of system.
The java.awt package provides classes for AWT
API such as TextField, Label, TextArea,
RadioButton, CheckBox, List etc.
Frame Window
A Frame provides the “main window” for the GUI application, which has title bar (containing
an icon, a title, minimize, maximize/restore-down and close buttons), an optional menu bar, and
the content display area.
When a frame object is created, by default it is invisible. You must call setVisible() method to
make the frame appear on the screen.
Then, you must set the size of the frame using setSize() or setBound() method.
Creating a Frame
There are two ways to create a Frame. They are,
1) By Instantiating Frame class
2) By extending Frame class
Creating Frame Window by Instantiating
Frame class import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class FrameDemo
{
FrameDemo()
{
Frame fm=new Frame(); //Creating a frame.
Label lb = new Label("welcome to java "); //Creating a label
fm.add(lb); //adding label to the
frame. fm.setSize(300, 300); //setting
frame size. fm.setVisible(true); //set frame
visibilty true. fm.setTitle("Frame Example");
Canvas
Canvas component represents a rectangular area where application can draw something or can
receive inputs created by user.
Drawing is not implemented on the canvas itself, but on the Graphics object provided by the
canvas.
The Canvas is a section of a window to draw graphics or display images.
Constructors of Canvas
Constructor Descriptio
n
Canvas() This constructor creates instance of a Canvas.
Canvas(GraphicsConfiguratio This constructor creates instance of a Canvas with the given
n object
config) of Graphics Configuration.
Methods of Canvas
Metho Descriptio
d n
Paint(Graphics g) Paint the Canvas.
Update(Graphics g) Update the Canvas.
Example:
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
addWindowListener(new WindowAdapter(){
public void
windowClosing(WindowEvent we)
{ System.exit(0);
}
});
}
public static void main(String args[])
{
DemoCanvas dc = new DemoCanvas();
}
}
class Canvascls extends Canvas
{
AWT Controls
AWT provides many ready- made and reusable GUI components.
All the AWT controls inherit from java.awt.* where * represents all class like label, button etc..
The frequently used are: Button, TextField, Label, Checkbox, CheckboxGroup (radio buttons),
List, and Choice, as given below table.
Component Descriptio
n
Label o It is used to display information that should not be modified by users.
o It is useful for obtaining information from users. It considers only
TextField
single
line input.
TextArea o It is a text component that allows for the editing of a multiple lines of
text.
Button o It creates a labeled button.
o It is a graphical component that can be in either an on (true) or off
CheckBox
(false)
state.
CheckboxGroup o It is used to group the set of checkbox.
List o It presents the user with a scrolling list of text items.
o It is used to show drop-down menu of choices. Selected choice is
Choice
shown
on the top of the menu.
o A Scrollbar control represents a scroll bar component in order to
ScrollBar
enable
user to select from range of values.
o It represents a rectangular area where application can draw something
Canvas
or
can receive inputs created by user.
Labels
It is used to display information that should not be modified by users.
Constructor of Label
Constructor Descriptio
n
Label() Create an empty label.
Create a new label with the specified string of text, which is left
Label(String) justified.
Create a label with specified text and alignment indicated by the
Label(String, int)
int
Argument: Label.Right, Label.Left, Label.Center
Method of Label
Metho Descriptio
d n
int getAlignment() Gets the current alignment of the label.
String getText() Gets the text of the label.
Set the alignment for the label to specified alignment. Possible
void setAlignment(int align) values are Label.LEFT, Label.RIGHT and Label.CENTER.
void setText(String label) Sets the text for the label to the specified text.
Syntax:
Label L1 = new
Label(“UserName”); add(L1);
TextField
It is useful for obtaining information from users. It considers only single line input.
Constructor of TextField
Constructor Descriptio
n
TextField() Create a default text field.
Create a new empty text field with the specified number of
TextField(int numChar)
character.
TextField(String text) Create a new text field initialized with the specified text.
Create a new text field initialized with the specified text to be
TextField(String text,
displayed, and wide enough to hold the specified number of
int numChar)
columns.
Method of TextField
Metho Descriptio
d n
getText() Return the text this text field contains (as a string).
setText() Puts the given text string into the field.
getColumns() Returns the width of this text field.
Select the text between the two integer positions (position start
select(int, int) from 0).
getSelectedText( ) Get the currently selected text.
isEditable() Return true or false based on whether the text is editable.
setEditable(boolean) True (the default) enables text to be edited, False not editable.
Syntax:
TextField t1 = new TextField
(12); Add(t1);
TextArea
It is a text component that allows for the editing of a multiple lines of text.
We can set number of rows and columns of the TextArea.
The text in a TextArea appears left justified, and the justification is not customizable.
Constructors of TextArea
Constructor Descriptio
n
TextArea() Creates an empty text area.
Creates an empty text area with the given number of rows and
TextArea(int, int) columns.
TextArea(String) Creates a text area displaying the given string.
Creates a text area displaying the given string and with the given
TextArea(String, int, int) number of rows and columns.
Creates a new text area with the specified text, and with the
TextArea(String, int , rows, columns, and scroll bar visibility as specified.
int , int ) SCROLLBARS_BOTH,
SCROLLBARS_HORIZONTAL_ONLY,
SCROLLBARS_NONE
and
SCROLLBARS_VERTICAL_ONLY.
Method of TextArea
Method Description
getColumns() Returns the number of columns of the text area.
setColumns(int columns) Sets the number of columns for the text area.
getRows() Returns the number of rows in the text area.
setRows(int rows) Sets the number of rows for the text area.
insert(String text, int pos) Inserts the specified text at the specified position in the text area.
append(String str) Appends the given text at the end of the text area's current text.
replaceRange (String text, Replaces text between the indicated start and end positions with
int start, int end) the
specified replacement text.
Syntax :
TextArea T2 = new TextArea
(10,20); add(T2);
Button (Push Button)
The Button component is rectangular button that has label and generate event when pressed.
Constructors of Button
Constructor Descriptio
n
Button() Creates a button with an empty string for its label.
Button(String text) Creates a button with the given string as a label.
Method of Button
Metho Descriptio
d n
getLabel() Get the label of the Button.
setLabel(string text) Set the label of the Button with given text.
setEnable(boolean) Enable or disable this Button. Disabled Button cannot be clicked.
Syntax :
Button b = new Button
(“Hello”); add (b);
CheckBox
The Checkbox class is used to display checkbox controls.
The Checkbox has a label to indicate its meaning. Checkbox component is toggle box that can be
either
selected or deselected indicating presence or absence of choice.
If a Checkbox object is not in a CheckboxGroup object, it is implemented as a simple checkbox.
If a Checkbox object is with a CheckboxGroup object, it is implemented as a radio button.
Constructors of Checkbox
Constructor Description
Checkbox() Creates a check box with an empty string for its label.
Checkbox(String text) Creates a checkbox with the given string as a label.
Checkbox(String text, boolean Creates a check box with the given string as a label and sets
state) the
specified state (Selected/Deselected by True/False).
Checkbox(String text, Creates a check box with the given string as a label, in the
CheckboxGroup group, specified check box group, and set to the specified state. The
boolean state) null is used for a group argument. Only radio button have
groups.
Method of Checkbox
Method Description
getLabel() Returns the label of the check box.
setLabel(String text) Sets the check box's label to by given text.
Returns true or false, based on whether the check box is
getState() selected or not.
Sets the state of the check box to the specified state
setState(boolean) (True/False).
setCheckboxGroup(CheckboxGr
Sets the check box's group to the specified check box
oup
grp) group.
getCheckboxGroup() Return the check box's group.
Syntax :
Checkbox C = new Checkbox
(“Java”); add (C);
CheckboxGroup
To create a group of checkboxes, you use the CheckboxGroup class.
The CheckboxGroup class is used with the Checkbox class to implement radio buttons.
All Checkbox that are associated with a CheckboxGroup are treated as a single radio button.
It allows only one button in group to be set at a time.
Constructors of CheckboxGroup
Constructor Descriptio
n
CheckboxGroup() Creates a new instance of CheckboxGroup.
Method of CheckboxGroup
Metho Descriptio
d n
getSelectedCheckbox() Returns the current choice from the check box group.
setSelectedCheckbox(Checkbo The method of CheckboxGroup is used to make one of the
x box
box) selected among all the check boxes.
Choice
It is used to show drop-down list of choices. Selected choice is shown on the top of the menu
Form this lists a single choice can be selected, similar to a group of checkboxes.
Constructors of Choice
Constructor Descriptio
n
Choice() Creates a new choice List.
Method of ChoiceList
Metho Descriptio
d n
add(String text) Add an item to the choice list.
getItem(int index) Returns the string at the specified index from the Choice list.
getItemCount() Returns the number of items in the choice list.
getSelectedIndex() Return the index of the currently selected item.
getSelectedItem() Returns the currently selected item as a string.
insert(String item,
Inserts the item into the choice list at the specified position.
int index)
remove(int position) Removes an item from the choice list at the specified position.
remove(String item) Removes the first occurrence of item from the Choice list.
removeAll() Removes all items from the choice list.
select(int) Selects the item at the given position.
select(String) Selects the item with the given string.
Lists
The List component is a Scrolling list of string from which one or more string can be selected.
The List class is use for creating single and multiple selection list.
The List class provides facility to set display size (number of elements) and also allow selecting
multiple items from the list.
Constructors of List
Constructor Descriptio
n
List() Metho Creates an empty scrolling list. Descriptio
d n with the specified number of
Creates a new scrolling list initialized
List(int rows)
add() visible
Used to build the scrolling list.
lines.
add(String item) Adds the specified item to the end of scrolling list.
Creates a scrolling list with the given number of visible lines on the
List(int rows, Adds
add(String screen. Thethe specified
Boolean item towhether
indicates the scrolling listenables
this list at the position
multiple
boolean item, int index) indicated by the index.
selection
multipleMode)
getItem(int index) (true)Returns
or not (false).
the item at given index.
Method of List
getItemCount() Returns the number of items in the list.
String[] getItems() Gets the items in the list.
Removes all items from the list.
Gets the index of the selected item on the list (used for lists that
getSelectedIndex() allow only single selections).
Returns a integer array of selected indexes positions (used for
int[] getSelectedIndexes()
lists
that allow multiple selections).
getSelectedItem() Returns the currently selected item on the list.
Returns a string array of selected items on the list. (used for lists
String[] getSelectedItems() that allow multiple selections).
deselect(int index) Deselects the item at the specified index.
remove(int position) Removes an item from the list at the specified position.
remove(String item) Removes the first occurrence of item from the list.
removeAll()
select(int index) Select the item at the given index.
replaceItem(String Replaces the item at the specified index in the list with the new
newValue, string.
int index)
Determines if the specified item in this scrolling list is selected
isIndexSelected(int index)
or
not.
isMultipleMode() Determines whether this list allows multiple selections or not.
Sets the flag that determines whether this list allows multiple
setMultipleMode(boolean b) selections.
Syntax:
List L1 = new
List(2,true);
L1.add(“Java”);
L1.add(“DWSL”);
add(L1);
The MenuBar class provides menu bar bound to a frame and is platform specific.
MenuBar contains one or more Menu objects.
Menu are used to display and control menu items.
Each Menu object contains a list of MenuItem objects.
An ActionListener can be added to a MenuItem object.
First create a menu bar by creating an instance of menuBar.
CheckboxMenuItem
CheckboxMenuItem is checkable menu item, which provides selection (on or off) listed in
menus.
CheckboxMenuItem can be controlled by the ItemListener interface.
Constructor of CheckboxMenuItem
Constructor Descriptio
n
CheckboxMenuItem() To create a default CheckBoxMenuItem.
CheckboxMenuItem(S
Str is the name shown in the menu.
tri ng str)
CheckboxMenuItem(Str
Flag can be set on for the Item to be checkable.
i
ng str, boolean flag)
Method of Menu
Metho Descriptio
d n
setEnabled(boolean flag) To enable or disable menu item
isEnabled() To retrieve the status of the menu item.
setLabel(String str) To change the name of the menu item.
String getLabel() To retrieve the current name of the menu item.
boolean getState() Return true if the item is checked otherwise false.
setState(Boolean flag) To check an item, pass true and to clear an item, pass false.
add (MenuItem m) Used to add menu item in Menu.
add(Menu menu) Add the specified menu to the menu bar.
getItem(int index) Return the menu item at the given index
getItemCount() Return the number of item inside the menu.
remove(MenuComponent Remove menu item from menu.
item)
Remove the menu located at the specified index and remove
remove(int index),
all
removeAll() menu from the menu bar.
Layout Managers **
The Layout Mangers are used to arrange components in particular manner.
Layout Manager is an interface that is implemented by all the classes of layout managers.
The layout manager set by the SetLayout() method. If we don’t use this method then default
layout manager is used.
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
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.
FlowLayout arranges swing component from left to right until there’s no more space available.
Then it begins a new row below it and moves from left to right again.
LEFT, CENTER, RIGHT – these tell it how to align the components in each row.
It can be used like FlowLayout.LEFT.
Constructor of FlowLayout
Constructor Descriptio
n
Create a flow layout with centered alignment and a default 5 unit
FlowLayout() horizontal and vertical gap.
Create a flow layout with the given alignment and a default 5 unit
FlowLayout(int align)
horizontal and vertical gap.
FlowLayout(int align, Create a flow layout with the given alignment and given horizontal
int and
hgap, int vgap) vertical gap.
Border layout
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: NORTH, SOUTH, EAST, WEST,
CENTER.
These constants are used like BorderLayout.NORTH.
While adding the component these constants are used by using following form of add() method.
add (Component compObj, Object
region);
Constructors of BorderLayout
Constructor Descriptio
n
BorderLayout() Creates a border layout with no gaps between the components.
BorderLayout(int hgap, int Creates a border layout with the given horizontal and vertical
vgap) gaps
between the components.
Grid Layout
The GridLayout is used to arrange the components in rectangular grid inside the container.
One component is displayed in each rectangle.
Components added to the container with the GridLayout manager are arranged in order from
left to right.
Constructors of GridLayout
Constructo Descriptio
r n
Creates a grid layout with one column per component
GridLayout ()
in a
row.
Creates a grid layout with the given rows and columns
GridLayout (int rows, int columns)
but
no gaps between the components.
GridLayout (int rows, int columns, Creates a grid layout with the given rows and columns
int along
hgap, int vgap) with given horizontal and vertical gaps.
CardLayout
The CardLayout manager treats each component as a card. Only one card/component visible
at a time. So it is known as CardLayout.
Constructors of CardLayout
Constructor Descriptio
n
CardLayout() Creates a card layout with zero horizontal and vertical gap.
CardLayout(int hgap, int Creates a card layout with the given horizontal and vertical
vgap) gap.
Methods of the CardLayout
Method Descriptio
s n
void first(Container a) It is used to flip to the first card of the given container.
void last(Container a) It is used to flip to the last card of the given container.
void next(Container a) It is used to flip to the next card of the given container.
void previous(Container a) It is used to flip to the previous card of the given container.
void show(Container a, String
cardName) It is used to flip to the specified card with the given name.
‘a’ is a reference to the container (usually a panel) that holds the cards, and cardName is the
name of a card.
package awtmanualcoding;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public AWTManualCoding()
{ //adding objects to frame
myFrame.add(lbl1);
myFrame.add(btnOk);
myFrame.add(txt1);
myFrame.add(dropdown);
myFrame.add(listItem);
myFrame.add(lblsex);
myFrame.add(chk1);
myFrame.add(chk2);
myFrame.add(lblchkSelect);
myFrame.add(txtval1);
myFrame.add(txtval2);
myFrame.add(lblsum);
myFrame.add(btnadd);
myFrame.add(lbldisplay);
}
//method for button
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btnOk)
{
txt1.setText("I am TextField");
}
if(e.getSource()==btnadd)
{
Output:
Navigator for
component
d. Select on the AWT object and drop it to the Frame same as below.
Code:
d.1 Set the value from the List Flavor,Price,Size, Drinks and Size of Drinks.
}
for(int i=0;i<sdrinks.length;i++)
{
cmbSDrink.addItem(String.valueOf(sdrinks[i]));
}
d.2 To add code for Order button click “Order” then go to Events, choose
“mouseClicked” select btnOrderMouseClicked.
1. Create your own AWT program that will uses at least 6 components of AWT (Manually Coding
and Drag and Drop version)
Assessment
1. Create simple application using AWT object.
a. Simple Calculator
b. Login
Ass
1. What is SWING in Java?
2. What are the components and give examples
3. What are the differences between AWT and SWING