=| Syllabus :
= Component, container, window, frame, panel.
Creating windowed programs and applets.
scroll
— WT controls and layout managers : use of AWT controls - labels, buttons, checkbox, checkbox BrOUPy
E bars, textfield, text area,
= Use of layout managers : flowLayout, borderLayout, gridLayout, cardLayout, gridbagLayout, menubars, menus,
a dialog boxes, file dialog,
1.1 _Introduction
[AWT (Abstract Window Toolkit) contains large number of built-in classes, interfaces and methods which allows
‘creating and managing GUI applications. The AWT classes and interfaces are actually component classes which are helpful
to design a standalone desktop application and a web application as well. Using AWT classes we can design windows
Controls such as textbox, label, button, lit, menu, choice radio button, checkbox, dialog boxes, etc.
In this chapter we will cover the most commonly used component classes and its methods along with setting fonts
and colors. We will also discuss on thelr alignment by using different layout managers and also their manual alignment by
using alignment methods, Along with these AWT component classes, we will also study creation of menubar and dialog
boxes,
1.2 Component Class Hierarchy
All the components are called as AWT components, achieved by creating object of associated component class. To
start with this discussion, refer following hierarchy Fig. 1.2.1, which describes the relation and functionality of each class
with each level.
Fig. 1.2.1
@ scanned with OKEN Scanner0)
Te OOD mee
Advance =
Let us discuss about these built-in classes in brief,
Component
Component class is the hierarchy class for all the AWT component This
lasses and methods of windows component. This class also defines £
responsible for managing different events (such 3
components, setting colors and fonts, etc. This class has important methods like setLocation{ } to
component, setSize( } to set the size/dimension of comp
nent and setBounds( ) for positioning and
components, after they are added. These methods are defined as
1.
¢ window, mouse, Key, input, etc.) Pl
void setLocation(int x_position, int y_position)
void setSize(int width, int height)
3. void setBounds(int x position, int y_position int width, int height)
Remember, these methods will work after a component is added into the window and Layout is set to be null
Container
‘This class is a subclass of Component cass. Container class is mainly responsible for positioning components on a
window by using different layout managers. This class provides the facility of nesting of one object into another
Container class has addi ) method to add components in a window and remove( ) method to remove components
from a window. These methods are defined as
1. void add(Component object)
2. void remove(Component object)
Window
‘This class is base class for two window classes; Panel and Frame. We cannot place any component objects into
Window class, Generally, we create Panel or Frame class’ objects as top-level-window and place different
‘components into them.
Panel
Thi A panel is group of components which is used recursively and nested inside
FramerorAppleticiass; A panel! This is where it differs from 2
Frame, We simply add components into a panel and then add this panel into a Frame or Applet by using adab
method. >
Frame
Frame Is the actual stand-alone-window that has berdet titlebat menubar and Fesling COMETS! It is 2 toP er
window that has component objects in it. Role of a Frame is same as Forms in VB.
re
@ scanned with OKEN ScannerAbstract Windo
ramming (MSBTE)
1.3.1 Creating Windowed Programs using Frame a
which we can add component objects to rea
Sai owt, Frame,
As discussed earller, Frame is
ame is created by extending a normal class with built-in class Java.
alone applications. A F
For example
r
class MyFrame extends Frame
An instance of class will create a frame whichis used as window for standalone desktop application.
Here are the COnStrURterS 6 FSRRG USI
1. Frame()
2. Frame(String title)
First form creates a Frame without any ttle and second form creates a Frame with specified stras its ttle. There are
Several methods which are useful while working with a Frame. They are discussed here in brief.
() setSize() method
't sid Holset the dimensions ba Window. These dimensions should be its width and height. General form of this
‘method is:
4. void setSize(int width, int height)
2. void setSize(Dimension obj)
New width and height is specified as two int-type arguments or it can be specified by providing object of Dimension
lass. Remember, the dinihsions Should Belin pixels)
(Ml) setTitle( ) Method
SRE E! mi methods tnd:
@ scanned with OKEN Scanneror]
|
il
ae
method to begin execution and to make a frame visible wit
y that we did with a consol
@ scanned with OKEN ScannerIt we deci
Component objects in start) then it willbe re-created on every loading of applet. Hence, prefer to use
lare and add component objects
init() method to
Program 1.8.2: Write a program to demonstrate checkbox using init() method in an applet.
import java.awt.*;
import javacapplet Applet:
|
ipublic class MyApplet extends Applet
f |
public void init()
{
Button binl = new Button'Submi’);
“Checkbox chl = new Checkbox( Pizza"
‘ch = new Checkbox("Burger"};
© scanned with OKEN Scanneradd(ch2);
Fiza F eurget
{Submit}
vided components in Frame and Applet. In following sections, we yy
In Program 1.3.2 we have declared and at
.ded constructors and methods.
discussing more on these AWT component classes with their overlo
1.4 __AWT Conirols
i ‘Allthe AWT classes and interfaces are defined in java.awt package. The Table 1.4.1 shows list of AWT classes py,
‘we are going to study in this chapter.
E rae |
@ scanned with OKEN Scannerdowing Toolkit (AWT)
Adh 2d Java Programming (MSBTE) z ==
Class
| Dialog | Creates a window dialogue box.
Font Deals
a ‘and white work area.
[Frame _| Creates a window that can have menu-bar, ttle-bar, sizing corners, and white wort
Panel uns ene
‘A subclass of Container which forms a group of components for multiple uses
Flowlayout _| The default Layout. This arranges the components from left to right, top to boHOr
Cardtayout _| This layout emulates index cards, ie only one on the top will be shown.
BorderLayout | This layout arranges the layout on five positions: East, West, North, South and Center.
Gridtayout
‘Arrange the components in two dimensional grid.
1.4.1 Button
‘The most widely used component is Button. A button is aso called as push button. The button class defines
following two constructors,
1. Button)
2. Button(string str)
First constructor creates a button without any label on it. Second constructor creates a button with a label on it.
For example
Button bil = new Bation(); [See
Button bi2 = new Button(“Click Me"; 5
In first example, button object btt is creates a push button without any label and second object bt2 creates a push
button with “Click Me” as label on it.
‘The Button class has following methods which are helpful while handling events of button.
1 void setLabel(String str)
‘2. String getLabel( )
setLabel{ ) method sets the specified label on the button object used. getLabel{ ) method returns the label of button
@ scanned with OKEN ScannerProgramming (MSBTE) = a
[Public class button_demo extends Applet
Xt
public void init()
ib
Button bt1 = new Button();
Button bi2 = new Button("Click Me");
add(btl);
add(bt2);,
Output :
Explanation :
First button bt! is without any label and second button has a label “Click Me” on it. Here add{ ) method is used to
‘and bt2 in the applet. sis
@ scanned with OKEN ScannerToolkit (AWT)
Advanced Java P
Abstract Windo
wning (MSBTE) 19
SetAlignmentfint how)
‘int getAlignment{)
object. getText{ )
2 ia telt names suggest, setTent{ ) method is used to set ot modify the text of see es ee
Fre oF itt retrieve tert of invoking label object setAlgnmen{ method is uted 95 ner
‘one of the above mentioned static constants. getAlignment{ ) method is used to retrieve the type
invoking label object. Here is a Program 1.4. 2 demonstrating label.
@ scanned with OKEN Scanner"applicable for setState( ) method.
2 checkboxtstring 17)
‘a. Cheekboustring #7 poolean state) oe
4 ceria beeen yxGrouP 1 and whose iniiat state is false Le. uncheck
without a tially unchecked. Third for . }
A cnr ti i raga ny apres eked a
fom fs sits abe! 2 fed ate “ oh kor whose label (S specified wy, ‘
state(s false then It pet ee ee Sepak {checkboxGrouP
howe state is mentioned 2d er
the events
otowng ace te methods of CrectBOn 2s! which are neler aur ee
1. void settabel(string tr)
2. String gettabel()
2 void setState(boolean state)
4, boolean getstatel )
setLabel{ ) method is used to set the label of checkbox specified by str- getLabel{ ) method returns the label of
Shing, setstatel ) method is used 0 Set the state of checkbox by specifying st
e ) iB state
boolean value.
1.4.
woking object of checkbox as
retrieve the current state of checkbox,
Ifa eneckbox saready with label, then setLabel{) wil ove
call getState{ ) method that returns!
write its older label with new st
ring passed. Same is
@ scanned with OKEN Scanneradd(chb3);
add(chb4):
F hep Veer cesivoc enact
1.4.4 CheckboxGroup
‘CheckboxGroup
CChecboxGroup converts @ checkbox into radio-button. Fourth constructor of Checkbox class uses
‘object. This class has only one constructor which is its default constructor le.
‘CheckboxGroup class has a method, used to determine which checkbox is currently checked.
@ scanned with OKEN Scannera Programming (MSBTEL
“new Checkbox
Advanced Jav :
fot-Dog' truer?
false,ch8):
Checkbox ehb?2
= new Cheekbox("Bu
Checkbox ehb3 :
astry
7 se,cbe):
Checkbox chb4 = new Checkbox! Pi alse,ché)
add(chbl);
add(chb2);
add(chb3);
add(chb4);
‘Aa
pagal @ HotDog © BNO ¢ Pasty
[pple stated
1.4.5 Choice
t and only one item ofthe lis can
items to be selected. Choice islike a pop-UP Is
choice class object provides a list of
It constructor ie.
be selected. This class has only one constructor ‘which is its default
[Gheicet) zs ane
When user clicks on the choice control, the whole list of choices Pops UP and user can select one item among the
list. Each item in the list isa string, added by add{ ) method. Itis ‘defined as,
ToidaddGeingiiem) ]
‘The items are added and appear in the choice list as the add{ ) method is called. To determine which item is
currently selected, we have
4, String getSelecteditem( )
2. int getSelectedindex{ )
t The eth item’ it
oo 1a ‘method returns selected items name as a string, getSelectedindex( ) method returns the
‘Other useful methods of Choice class areas follows :
@ scanned with OKEN Scanner3. void select(String item)
4, String getitem{int index)
1s of items added in the
the total number
stent
‘The getitemCount{ ) method returns
index or string, item. Bet!
method sets the initial selected item by specifying
specified index.
pplet
Write a program to demonstrate use of choices in an 2
Program 1.4.
© scanned with OKEN ScannerAdvanced Jav
Output :
fe rs. List class has f
‘option and serolloa! following
ith multiple selection
ven-visible block.
1.4.6 List
- in an oP
an object of this class provides 2 list wl
bers of items as choi
constructors. Alist contra shows any num
1 Uist)
2. Ustlint visible_rows)
‘4 Ustlinevisible_rows, boolean mutt_select
selec only one item at a time. Second construct
be visible and other items
alist control that allow to
imbers of entries
specified visible rows and
then only one item can be selected.
‘or list, add) method is overloaded and has following two
in the list that will always
First form of constructor creates
‘multiple selections option. If boolean value
creates alist control in which visible_rows specified nu
can be viewed by scrolling. Third form of constructor 5
is true then user can select multiple options andi its false
This class has add{ ) method to add items into the ist. F
forms.
4. void ada(string item)
2 void add{string item. int at_index)
First form adds ir
‘adds specified item into the list and second form adds specified item into the list at specified index. Here
isa list of methods related with List lass.
@ scanned with OKEN ScannerAdvanced Java Pr
Abstrac
ramming (MSBTE) 415
san integer
String array and getSelectedindexes{ } returns indexes of all the selected items 2 an er ger pected
‘method returns total numbers of items in the lst. The select{) method sets the currently 5@
ettem( ) method obtains the item name present at specified index.
Program 1.4.6:
‘Write a program to demonstrate List control in an applet
“S00” height= “500” >
@ scanned with OKEN Scannerin output contains two list boxes
14.7 Scrollbar
a eae sserrane ot a compen etox wredon ScToAbaTS ay De crlenay
‘Scrollbar provides horizontal and ver f
horizontally or vertically. Scrolibar class defines following three constructors :
1 Serolibart)
2 Serolibartint ype)
3. Serolbar(nt type, int iital_value, int thumb_size, int min_value, Int max_value)
First form of constructor creates vertical scrollbar only. Second and third form of constructor allows to speciy the
type of scrollbar by using Scrollbar. VERTICAL and Scrollbar. HORIZONTAL. The initial value of scrollbar Is passed through
intiol_value. The number of units of height of the thumb is specified by thumb_size. The minimum and maximum value for
the scrollbar is specified by min_value and max_volue. All the values can also be set by using.
‘Minimum and maximum values can be retrieved by using getMinimum( ) and laxit
ue a getMaximum( ) methods,
@ scanned with OKEN Scannera
Program 1.4.7: Write a program to demonstrate use of Serolibars in an applet
import javaawt.*,
jpublic class scroll_demo extends Applet
Ht
public void init( )
{
Scrollbar sb:
new Scrollbar(Scrollbar: VERTICAL,0,1,0,50);
Scrollbar sb2 = new Scrollbar(Scrollbar. HORIZONTAL,0,1,0,50);
TextField
object of TextField class provides a single line textbox control, generally used to take input value from the user.
defines following constructors :
@ scanned with OKEN Scanner‘second constructor
‘constructor creates
SBTE)
ent
1d without any intl
; by max_chors. ‘Third form race
1d with nil text 292
‘Advanced Java Pr.
First constructor creates a Text
have maximum numbers of characters specified by mor
text specified by str. Fourth constructor creates 2 Terie
‘maxchars
TextField isa derived cass of TextComponent cass. Fol
sings ast of member functions of TEtFeld ly
4. String getText{)
2 void setText(String str)
3 String getselectedText()
4. void select{int start_index, int end_index)
5. boolean istditable()
6. void setEditable(boolean editable)
7 void setEchochar(chor ch)
% boolean echocharsset{)
9% char getéchochar{ )
The getText( ) method returns the text currently present in invoking TextField object. setText( ) method sets i,
text in the TextField specified by str. getSelectedText{ ) method returns selected text of TextField a5 a string, sel.
i
‘method selects the characters beginning at stort index and ends at end_index-1. Modification of contents of a Tex
‘depends on value of setEditable( ), We can determine whether a TextField is editable or not by using IsEditable( ) met.
‘The TextField used for taking password, should be defined by calling setEchoChar{ ) method which disables,
g ofthe characters as they are typed. This method requires a character which will be displayed as @ mask on
ters, We can also determine whether echo characteris set or not by calling echoCharsSet{ ) method. We car
the echo character by calling getEchoChar).
8: Write a program to demonstrate use of TextField in an applet
@ scanned with OKEN ScannerWW avanced Java Programing (MSE
Output :
14.9 Textarea
input. Textarea has
TextArea is a multiline TextField. A Textarea is used to provide a paragraph or multiple ines a5 Input Te
following constructors
1. TextArea()
2. TextArea{int max_lines, int max_rows)
3. TextArea(String str)
4. TextArea(String str, int max_lines, int max_rows)
5. TextArea(String str, int max lines, int max_rows, int crollbar_type)
First constructor creates a TextArea without any initial string and with default settings. Second. constructor creates
a TextArea specifying maximum numbers of lines and maximum numbers of characters in each line. Third constructor
initializes a TextArea with specified string str. Fourth constructor specifies initial string, maximum numbers of lines and
maximum numbers of characters in each line. Fifth constructor allows adding scrollbar type. The values for scrolibar type
are static constants. They are,
| ‘SCROLLBARS_BOTH ‘SCROLLBARS_NONE
‘SCROLLBARS_VERTICAL_ ONLY | SCROLLBARS_HORIZONTAL_ONLY
TextArea is also another derived class of TextComponent class; therefore the following methods are common :
1. String getText()
2 void setText(String str)
String getSelectedText()
void select{int start_index, Int end_index)
@ scanned with OKEN ScannerAdvanced Java Programming (MSBTE)
pr at the en
st
append) method appends the sti S28 ers
specified index. replaceRanget ) method replac
Remember that TextArea class do not de
allowed with this.
Program 1.4.9: Write a program to
import jaya.awt.*;
{import java.applet.*;
ye
*) é
Iclass MyPanel extends Panel
it
public pnl()
{
“Label Ib] = new Label( "This s fom Panel)
Button bil = new Button("Panel”):
add(lbl); s
u
@ scanned with OKEN ScannerFl setVisible(true):
lass MyFrame extends Frame
ig
public ‘MyFrame()
(
‘setLayout(aull):
MyPanel p2 = new MyPanel .
Checkbox chl = ne Check From Fran
add(p2);
add(ch});
p2serBound(50.50200.50)
setounds(20020010020),
en ; : pe appiet'sinit() method we mate
Py enecting Program 14.1095 applet, wine SIN and from! } thes
a vl. noie tha, both he el aten asses Fame and APpIEt HAS rrjared object of panel lass pn .°
the contents of eass pi can be seen in bth the windows:
Output :
B sone ewe pl oct
eran fo] Front
@ scanned with OKEN ScannerToolkit
rc Wei
Wy svenced dave Programing MSBTE: —
1.5__Layout Managers ae
1d so far
default
rich we have studie
yy using
on screen BI
algorithms
It is very tedious job to align all the components on a window. All the components
appears on the screen by using add{ ) method, These components are by default postione
layout manager. Role of layout manager i to postion these components using different alignment t aligned
nts are not al
IT You have observed each output screenshots carefully, you can see that all the compan! Sort
Properly. If we are programming for a GUI application then itis essential to align al the compan
success of an application depends on its easy and eye-catching design. Hence it is necessary
‘managers and align the components property,
ents, becaus
to understand layout
is method 15
The layout manager is set by using settayout{) method, comes under LayoutManager interface. Mis
defined as: za
void setLayout(LayoutManager obj)
“ setLayout( )
Here ob] i an object of desired layout manager. To disable the layout manager then pass “null” Seta
f
method and align the components manually by using setBounds| ) method. Normally to avold headache 0
d here in
Components manually, we use layout managers. Java has four built-in LayoutManager classes. They are discusses
brief,
1.5.1 FlowLayout
FlowLayout isthe default layout manager. ll the previous examples have used ths layout. Tisis the simple layout
which arranges the components as they are added, When no more components ft ona line, it begins with next line, BY
default it keeps space of S pixels between vertical and horizontal components. To create an object ofthis layout manager,
we have following constructors :
1. Flowtayout( )
2 FlowLayout(int alignment)
3 FlowLayout{int alignment, int horizontal gop, int vertcal_gop) ee
First constructor creates an object which by default leaves gap of S pixels and aligns center. Second constructor
__ fequires to specify alignment of each line. It is done by using three static constants: FlowLayout.LEFT, FlowLayout. RIGHT,
‘FlowLayout.CENTER, Third constructor requires alignment and horizontal and vertical ap between components.
+ Write a program to demonstrate FlowLayout manager in an appletAdvanced Java Programming (MSBTE)
FlowLayout fl = new FlowLayout()s
setLayout(l);
Label IL = new Label(Enter User ID 2")
Checkbox chl = new Checkbox("Pizza")s
‘TextField tf = new TextField( "This is textbox’):
Label 12 = new Label("Enter Password :");
add);
add(ch1);,
add);
add(2);
@ scanned with OKEN ScannerHere is alist of constructors of BorderLayout.
1. Bordertayout( )
2. Bordertayout(int horizontal_gap, int vertical_gop)
allows us t©
fond constructor :
First constructor creates a default BorderLayout object with default setings: Sec Tayout, use followin
using Border
specify horizontal and vertical space between components. While adding components using
add( ) method. fo
on related
NORTH,
[[-cda(Component object, int region)
Here, region specifies where the components are to be placed. Bordertayout species these Net
constants: BorderLayout.CENTER, BorderLayout SOUTH, BorderLayout EAST, Bordertayout. WEST:
Program 1.5.2: Write a program to demonstrate BorderLayout in an applet
import java.aw.*;
import java.applet.*;
@ scanned with OKEN Scannerructors of GridLayoue,
15.3. GridLayout
Gridtayout postion the components in two di
1. Gridtoyout()
= aa hana epi reo I) 7
aaa structor al
‘ Se st with ingle row ane COUT oan penal ae :
First constructor creates a default GridLayout rows and cowumns 25 Wel retical sy
‘numbers of rows and columns. Tid form requires numbers
‘between components.
Program 1.5.3: Write a program to create &
‘mobile keypad in an applet
@ scanned with OKEN Scanneroutput : ae
bpplet Viewer gfidinyout dom NE
3
ale
|
1
5
Leas —_|—
6
8
15.4 CardLayout
ses, Different Cardlayout object can have
multiple Panel objects
ager clas
ject of Panel. We can have
invisible as per user's input. Here are
‘The card layout is a unique layout among other layout man:
different layouts. A CardLayout manger object should be held in an ol
rand any one object can be on the top. Other Panel objects can be made visible and it
the constructors of CardLayout.
4. Cardtayout( }
2. CardLayout{int horizontal_gap, int vertical_gap)
We must create a Panel that contains the deck
1s components. Then add these
itbecomes 2
Use of CardLayout requires more work than other layout managers.
| and a Panel for each card in the deck. Then you add to the appropriate panel that contain
| panels to the main panel to which CardLayout is set. ‘This looks a bit complicated but when you practice thi
‘To add cards to the panel, add( ) method is used. Its general form is:
normal process for you.
This method adds specified component abject into specified panel object. CardLayout has following methods which
We attaemtetas
@ scanned with OKEN Scannerthat holds the cards
Here deck is a Panel able
tin an applet oe
jemonstrate CardLayou
Program 1.5.4: Write a program to 4
impor java.awtevent.*;
1
@ scanned with OKEN Scanner‘Advanced Java Programm.
Output :
Note:
ve can also try another program by creating an component object and USS
1. obj.setForeground(ct);
2 obj setBackground(c2);
4.10 Setting Font
am application more attractive To deal with fonts, java provides @ built-in daz
style. To select 2rex
able arguments. They are; font name, font size and font
parameters. Is constructor is =
Java supports different fonts to make
Font. This Font class has three important var
font, we must create an object of Font cass with al requres
FoutSiingfont_name, iat fomt_style, int font size)
specifies name ofthe desired font, Remember before applying any font, check whether that forts
“font_sice desrbes size of font in points. The ste of font is specified by usieg
Font.ITALIC. To combine styles, use single pipe (|)-
Here font_name
‘available with your operating system or not.
three static constants: Font.PLAIN, Font.BOLD,
For example, Font.BOLD | Font.ITALIC.
“after defining spectfied Font object, apply the font by using setFont{) method. tis defined as,
@ scanned with OKEN Scannerabstract Window
am 1.10.1: Write a pr in system.
Program 1.10.1: Write program to show al the avaliable fonts according to users operatin SYS
nt javaawt aa eee Te
import java.applet.*;
le
Jcappet code “color_demol” width= “500 height= “500” >
I)
lpublic class font_demol extends Applet
{
public void paint(Graphies g)
{
String list =";
String {1};
GraphiesEnvironment ge = GraphiesEnvironment.getLocalGraphiesEnvironment( };
‘ge.getAllFonts( );_ ae.
i= 051