0% found this document useful (0 votes)
51 views26 pages

Abstract Window Toolkit

The document discusses the Abstract Window Toolkit (AWT) in Java. It describes AWT as an API that allows developing GUI applications in Java. It provides several AWT components like frames, panels, buttons, text fields etc. that are arranged in a hierarchy with Component as the top level class. It also gives examples of creating frames and using canvases to draw graphics. In the end, it briefly describes commonly used AWT controls like labels, text fields, checkboxes etc.

Uploaded by

Regie Sudoy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
51 views26 pages

Abstract Window Toolkit

The document discusses the Abstract Window Toolkit (AWT) in Java. It describes AWT as an API that allows developing GUI applications in Java. It provides several AWT components like frames, panels, buttons, text fields etc. that are arranged in a hierarchy with Component as the top level class. It also gives examples of creating frames and using canvases to draw graphics. In the end, it briefly describes commonly used AWT controls like labels, text fields, checkboxes etc.

Uploaded by

Regie Sudoy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 26

Course LM01-EMCC

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.

Java AWT Classes Hierarchy *


Class Descripti
on
o Component class is at the top of AWT hierarchy.
o Component is an abstract class that encapsulates all attribute of
visual component.
Component o Component is an object having a graphical representation that can
be displayed on the screen and that can interact with the user.
Examples: buttons, checkboxes, list, scrollbars etc.
o Container is a component that can contain other components like
buttons, textfields, labels etc. in a specific layout.
o It is a subclass of component class.
o It keeps track of components that are added to another component.
Container
o In “Front to back” order components are listed within the container.
o The classes that extend Container class are known as container such
as
Frame, Dialog and Panel.
o Window is the container that has no borders and menu bars.
Window o It is a rectangular area which is displayed on the screen.
o You must use frame, dialog or another window for creating a
window.
o Panel is the container that doesn't contain title bar and menu bars.
o It can have other components like button, textfield etc.
Panel o It is concrete subclass of Container.
o The default LayoutManager of Panel is Flow Layout.
o Frame is the container that has title bar, menu bar, borders, and
resizing corners.
Frame
o It is a top-level window & subclass of the Window class.
o It can have other components like button, textfield etc.
o Dialog is a window that takes input from the user.
Dialog o It is used to display message, list of options etc.

Basic Components available in AWT

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

//To close the window


fm.addWindowListener(new
WindowAdapter(){
public void
windowClosing(WindowEvent we)
{ System.exit(0);
}
});
}
public static void main(String args[])
{
FrameDemo ta = new FrameDemo();
}
}
 Creating Frame window by extending Frame
class import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
class DemoFrameExample extends Frame
{
DemoFrameExample()
{
super("Frame Example");
Label lb = new Label("Welcome to java world");
lb.setBounds(30,100,150,30);// setting button
position add(lb);//adding button into frame
setSize(300,300);//frame size 300 width and 300
height setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
//To close the window
addWindowListener(new
WindowAdapter(){
public void
windowClosing(WindowEvent we)
{ System.exit(0);
}
});
}
public static void main(String args[])
{
DemoFrameExample f = new DemoFrameExample ();
}
}

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;

public class DemoCanvas extends Frame


{
public DemoCanvas()
{
super("Canvas Example");
Canvascls cx = new
Canvascls(); cx.setSize(125,
100);
cx.setBackground(Color.blac
k); add(cx,"North");
setSize(300,
200);
setVisible(true);

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
{

public void paint(Graphics g)


{
g.setColor(Color.blue);
g.fillOval(75, 10, 150,
75);
}

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

Menu and Menu Bar


 The abstract class MenuComponent is the super class of all menu-related components.
 Menu can be added only to a menu container.
 Menu Component hierarchy as given below:

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

Constructor of Menu and Menubar

Constructor To create a default menu.


Description
MenuBar() Creates a new menu bar.
Menu()
Menu(String str) str specifies the name of the Menu selection
Menu(String str, str specifies the name of the Menu selection flag represents the
Boolean popup
flag) menu if set true.
MenuItem() To create a default MenuItem.
MenuItem(String str) Str is the name shown in the Menu.
MenuItem(String str,
MenuShortcut key) Key is the short cut key for that Menu Item.

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

Layout Manager Classes


 Some possible Layout Managers are listed in the table below:
Layout Manager Descriptio Constant
n s
Arranges components to the top, NORTH, SOUTH, EAST, WEST,
BorderLayout bottom, left, right, and center of a CENTER –positions in the
container. container.
It is used to arrange the LEFT, CENTER, RIGHT – these
FlowLayout components in a line, one after tell it how to align the
another (in a flow) components in
from left to right. each row.
Divide the container into equal- GridLayout(int rows, int
GridLayout sized rectangles and arrange each columns) To specify the
component into one of these cells. number of rows and columns
in the grid.
It manages the components in such CardLayout(int hgap, int vgap):
CardLayout a creates a card layout with the
way that only one component is given horizontal and vertical
visible at a time. gap.

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.

Manual Creation of Objects using AWT

package awtmanualcoding;

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

public class AWTManualCoding implements ItemListener, ActionListener{

Frame myFrame = new Frame();


Label lbl1 = new Label("I am Label");
Button btnOk = new Button("Click Me");
TextField txt1 = new TextField("");
Choice dropdown = new Choice();
List listItem = new List();
Label lblsex = new Label("Displaying for Sex");
Checkbox chk1 = new Checkbox("Selection 1");
Checkbox chk2 = new Checkbox("Selection 2");
Label lblchkSelect = new Label("Display the Selection");
TextField txtval1 = new TextField("");
TextField txtval2 = new TextField("");
Label lblsum = new Label("Result");
Button btnadd = new Button("Add");
Label lbldisplay = new Label("Sum of two numbers");

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

//for action of the button


btnOk.addActionListener(this);
//for itemlistener
dropdown.addItemListener(this);
chk1.addItemListener(this);
chk2.addItemListener(this);
btnadd.addActionListener(this);

//adding value to choice object


dropdown.addItem("Male");
dropdown.addItem("Female");
//adding value to list object
listItem.addItem("I am Item1");
listItem.addItem("I am Item2");
listItem.addItem("I am Item3");

//setting the x-(left To right),y-(top to buttom),width,height of an object


lbl1.setBounds(30, 30, 70, 30);
btnOk.setBounds(100, 30, 60, 30);
txt1.setBounds(30, 80, 100, 30);
dropdown.setBounds(30, 120, 70, 30);
lblsex.setBounds(110,120,100,30);
listItem.setBounds(30, 150, 100, 100);
chk1.setBounds(150,150,100,30);
chk2.setBounds(150,180,100,30);
lblchkSelect.setBounds(150,210,130, 30);
txtval1.setBounds(30,280,130, 30);
txtval2.setBounds(30,310,130, 30);
btnadd.setBounds(170, 280, 70, 60);
lbldisplay.setBounds(30,250,130, 30);
lblsum.setBounds(30, 350, 70, 30) ;

//setting the properties of a frame


myFrame.setLayout(null);
myFrame.setSize(300,400);
myFrame.setVisible(true);
myFrame.setTitle("AWT Objects");
myFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

}
//method for button
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btnOk)
{
txt1.setText("I am TextField");
}
if(e.getSource()==btnadd)
{

int val1,val2,sum =0;


val1 = Integer.parseInt(txtval1.getText()); // integer.parseint is to convert the string to number
val2 = Integer.parseInt(txtval2.getText());
sum = val1 + val2;

lblsum.setText(String.valueOf(sum)); //String.valueof is to convert number to string.


}
}
//method for choice and checkbox
public void itemStateChanged(ItemEvent evt)
{
int getIndexdp = dropdown.getSelectedIndex();
if(getIndexdp == 0)
{
lblsex.setText("Male");
}
else
{
lblsex.setText("Female");
}

//to get the value from checkbox


boolean getIndexchk = chk1.getState();
boolean getIndexchk2 = chk2.getState();

if((getIndexchk2==true) && (getIndexchk==true))


{
lblchkSelect.setText(chk1.getLabel()+ " " + chk2.getLabel());
}
else if((getIndexchk2==false) && (getIndexchk==true))
{
lblchkSelect.setText(chk1.getLabel());
}
else if((getIndexchk2==true) && (getIndexchk==false))
{
lblchkSelect.setText(chk2.getLabel());
}
else
{
lblchkSelect.setText("Nothing to display");
}
}
public static void main(String[] args) {
// TODO code application logic here
new AWTManualCoding();
}
}

Output:

Drag and Drop the Object


Frame
a. Select file package (“dndobjectawt”) right click > New>select “Frame form”.
b. Set Class name for the frame and click “Finish”.

Project File Properties on an


Default frame object AWT object
c. Go to Navigator and select Frame then right click > Set Layout>”Free Deign”.

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.

String flavor[] = {"Hawaiian","Ham and Cheese","Pepperoni","Bacon and


Cheese","Hotsilog"};
int Price[] = {79,69,450,550,999};
String Fsize[] = {"small","medium","Large","X-Large","Family"};
String Drinks[]={"sprite","royal","coke","Ice tea","Water"};
String sdrinks[]={"Regular","Large"};
for(int i=0;i<flavor.length;i++)
{
listFlavor.addItem(String.valueOf(flavor[i]));
listPrice.addItem(String.valueOf(Price[i]));
cmbSize.addItem(String.valueOf(Fsize[i]));
cmbDrinks.addItem(String.valueOf(Drinks[i]));

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

//type this following code.


listOrder.addItem(listFlavor.getSelectedItem());
OPrice.addItem(listPrice.getSelectedItem());

// to automatic get the total amount.


int sum=0;
for(int i=0;i<OPrice.getItemCount();i++)
{
sum = sum+(Integer.parseInt(OPrice.getItem(i)));
lblTotal.setText(String.valueOf(sum));
}
d.3
b. The output should be the same as below:
Activity

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

You might also like