0% found this document useful (0 votes)
59 views41 pages

CH 4 - AWT

Uploaded by

yashsayani1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views41 pages

CH 4 - AWT

Uploaded by

yashsayani1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 41

R.P.

Bhalodia BCA College

CH
4

The Abstract Window Toolkit (AWT)

1
The abstract component class was introduced in applets. This class is important
from user point of view because in each and every user interface we need to have
component

All the components that we have seen the previous figure are must be added to
the container of the applet. For that applet has provided a special class called
container. Various methods of the class are as follows :
Method Description
Component add(Component c) Adds c to the container and returns c
Void Registers cl to receive container events
addContainerListener(ContainerListener cl)
Insets getInsets Returns the insets object for the container

Void remove(Component c) Removes c from the container


Void Unregister cl to receive the container events
removeContainerListener(ContainerListener cl)
void setLayout(LayoutManager lm) Sets lm as the layout manager for the
container
2
Labels
A label is a string that appears on a graphical user interface. It can be
changed by your program but cannot be changed by the user. Labels are very
frequently used in programs. The most common example where we find the
labels is before the text field to inform the user about the input that is expected.
The constructors of the class are as follows :
(1)Label()
(2)Label(String str)
(3)Label(String str, int align)
Here, str is the text for the label. The argument align is a constant that
indicates if the label should be left justified, centered or right justified. The
constants LEFT, CENTER and RIGHT will be used to set the value of the align.
To get the information about the alignment we have two methods
(1) int getAlignment()
(2) void setAlignment(int align)
The methods for reading and writing the text are as follows :
(1) String getText()
(2) void setText(String str)

import java.applet.*;
import java.awt.*;
/*<applet code="Labels" width=200 height=120>
</applet>*/
public class Labels extends Applet
{
public void init()
{
String str = "This is a very Long Label";
Label lbl1 = new Label(str, Label.LEFT);
add(lbl1);
Label lbl2 = new Label(str, Label.CENTER);
add(lbl2);
Label lbl3 = new Label(str, Label.RIGHT);
add(lbl3);
}
}

3
Buttons
A Button is a component that simulates the appearance of a push button on
an electronic instrument. When the user clicks the mouse inside its boundaries,
the button changes appearance to provide feedback for the user.
This class has two constructors are as follows
(1) Button()
(2) Button(String str)
Here the str is the text for the button.
Here str is the string to be used as a label for the button. We have to implement
java.awt.event.ActionListener interface which defines one method i.e.
actionPerformed which is as follows :
void actionPerformed(ActionEvent ae)
Here ae is the action event.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="Buttons" width=200 height=120>
</applet>*/
public class Buttons extends Applet implements ActionListener
{
Label lbl;
public void init()
{
Button btn1 = new Button("Apple");
btn1.addActionListener(this);
add(btn1);
Button btn2 = new Button("Mango");
btn2.addActionListener(this);
add(btn2);
Button btn3 = new Button("Orange");
btn3.addActionListener(this);
add(btn3);
Button btn4 = new Button("Banana");
btn4.addActionListener(this);
add(btn4);
lbl = new Label();
add(lbl);
}
public void actionPerformed(ActionEvent ae)
{
lbl.setText(ae.getActionCommand());
}
}
4
Canvases
A canvas provides a rectangular area on which you can draw. This is valuable
because you can create graphs and other diagrams on the canvas by using all the
methods of Graphics class. This class has only one constructor i.e. canvas()
import java.applet.*;
import java.awt.*;
/*<applet code="CanvasDemo" width=200 height=120>
</applet>*/
class MyCanvas extends Canvas
{
public void paint(Graphics g)
{
//Draw axes
g.setColor(Color.lightGray);
Dimension d = getSize();
g.drawRect(0,0, d.width-1,d.height-1);
g.drawLine(0,d.height/2,d.width,d.height/2);
g.drawLine(d.width/2,0,d.width/2,d.height -1);

//Draw Waveform
g.setColor(Color.blue);
double dx = 4 * Math.PI / d.width;
double x = -2 * Math.PI;
int h = d.height;
for(int i=0; i<d.width -1;i++)
{
int y1 = (int)((h-h * Math.sin(x))/2);
int y2 = (int)((h-h * Math.sin(x + dx))/2);
g.drawLine(i,y1,i+1,y2);
x+= dx;
}
}
}
public class CanvasDemo extends Applet
{
public void init()
{
MyCanvas mycan= new MyCanvas();
mycan.setSize(401,150);
add(mycan);
}
}

5
CheckBoxes
A check box is a component that combines a label and a small box.
Depending on the state of the option represented by that checkbox. There may
be or may not be a check mark in the check box. The state of check box is
changed by clicking the mouse on the box. This class has five constructors as
follows :
(1)Checkbox()
(2)Checkbox(String str)
(3)Checkbox(String str, boolean state)
(4)Checkbox(String str, boolean state, CheckboxGroup grp)
(5)Checkbox(String str, CheckboxGroup grp, boolean state)

Here the str is the text for the check box. If state is true, a check mark
appears in the box. Otherwise the box is cleared. The last two forms of
constructors uses a group of several checkboxes together. The parameter grp is
the reference of the checkbox group.
An item event is generated when the state of a checkbox changes. For that
following are the methods that we have to register
(1)void addItemListener(ItemListener il)
(2)void removedItemListener(ItemListener il)
We can read and write the state of checkbox by using the following methods :
(1) boolean getState()
(2)void setState(boolean value)
here if the value is true, a check mark is placed inside the box. Otherwise
the box will be cleared.
We can read and write the label of checkbox via following methods :
(1)String getLabel()
(2)void setLabel(String str)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="ChechkBoxEvents" width=200 height=120>
</applet>*/
public class ChechkBoxEvents extends Applet implements ItemListener
{
Label lbl;
public void init()
{
Checkbox cb1 = new Checkbox("Cricket");
cb1.addItemListener(this);
add(cb1);
Checkbox cb2 = new Checkbox("Football");
cb2.addItemListener(this);
6
add(cb2);
Checkbox cb3 = new Checkbox("Chess");
cb3.addItemListener(this);
add(cb3);
lbl = new Label(" ");
add(lbl);
}
public void itemStateChanged(ItemEvent ie)
{
Checkbox cb = (Checkbox)ie.getItemSelectable();
lbl.setText(cb.getLabel() + " " +cb.getState());
}
}

CheckBox Groups
A CheckBox group is a set of check boxes. Only one of these may be set
at any time. If the user clicks on one element in a checkbox group, that
checkbox is set. Other members of the same group are automatically cleared.
In otherwords, a checkbox with group is just like a radio button.
We may get the selected member from the group by calling following
method
Checkbox getSelectedCheckbox()
We may also set a particular checkbox in a group via the following method
void setSelectedCheckBox(Checkbox cb)
here cb is the checkbox to be set.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="ChechkBoxGroupEvents" width=200 height=120>
</applet>*/
public class ChechkBoxGroupEvents extends Applet implements ItemListener
{
Label lbl;
public void init()
{
CheckboxGroup cbg = new CheckboxGroup();
Checkbox cb1 = new Checkbox("Cricket",cbg,false);
cb1.addItemListener(this);
add(cb1);
Checkbox cb2 = new Checkbox("Football",cbg,true);
cb2.addItemListener(this);
add(cb2);
Checkbox cb3 = new Checkbox("Chess",cbg,false);
7
cb3.addItemListener(this);
add(cb3);
lbl = new Label(" ");
add(lbl);
}
public void itemStateChanged(ItemEvent ie)
{
Checkbox cb = (Checkbox)ie.getItemSelectable();
lbl.setText(cb.getLabel() + " " +cb.getState());
}
}
Choice
A Choice is a component that provides a type of menu (Combo Box).
When user click on a choice, it displays all of the allowed selections. When the
user selects one of those items, the choice menu will return into normal position
and displays our selected choice.
Choices are valuable because they need minimum amount of space on our
display area. This class has only one constructor i.e.
Choice()
Method Description
void add(String str) Adds str as an item
void addItem(String str) Adds str as an item
void Register il to receive item events generated
addItemListener(ItemListener il) by this choice.
String getIndex(int i) Returns the string at index i in the choice
int getSelectedIndex() Returns the index of the selected item
String getSelectedItem() Returns the selected item
Object[] getSelectedObjects() Returns an array with one object,which is
the selected item.
void insert(String str, int i) Inserts str before the item at index i
void removeAll() Removes all the items from the choice
void Unregister il to receive item events.
removeItemListener(ItemListener
li)
void select(int i) Selects the item at index I
void select(String str) Select the item str.

8
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="ChoiceEvents" width=200 height=120>
</applet>*/
public class ChoiceEvents extends Applet implements ItemListener
{
Label lbl;
public void init()
{
Choice c1 = new Choice();
c1.add("Red");
c1.add("Orange");
c1.add("Yellow");
c1.add("Green");
c1.add("Blue");
c1.add("Indigo");
c1.add("Violet");
add(c1);
c1.addItemListener(this);
Choice c2 = new Choice();
c2.add("North");
c2.add("South");
c2.add("East");
c2.add("West");
add(c2);
c2.addItemListener(this);
lbl = new Label(" ");
add(lbl);
}
public void itemStateChanged(ItemEvent ie)
{
Choice c = (Choice)ie.getItemSelectable();
lbl.setText(c.getSelectedItem());
}
}

9
Lists
List object can be constructed to show any number of choices in the window. It
also allows multiple selections.

Constructors:
1) List() : Select only one item at a time
2) List(int numRows) : number of entries in the list
3) List(int numRows, boolean multiselect) : it can be set as true or false. If true
user can select two or more items at a time.

Methods
1) void add(String name)
2) void add(String name, int index) : adds item at the specified index.
3) String getSelectedItem() : returns String containing the name of the item.
4) int getSelectedIndex() : It returns the index of the item.
5) getSelectedItems() : returns an array containing the name of currently selected
items.
6) getSelectedIndexes() : returns an array containing the indexes of currently
selected items.
import java.awt.*;
import java.awt.event.*;
public class ListDemo
{
ListDemo()
{
Frame frm = new Frame();
final Label lbl = new Label();
lbl.setAlignment(Label.CENTER);
lbl.setSize(500,100);
Button btn = new Button("Show");
btn.setBounds(250,150,80,30);
final List lt = new List(4,false);
lt.setBounds(100,100,70,70);
lt.add("C");
lt.add("C++");
lt.add("Java");
lt.add("PHP");
final List lt2 = new List(4, true);
lt2.setBounds(100,200,70,70);
lt2.add("Turbo C++");
lt2.add("Spring");
lt2.add("Hibernate");
lt2.add("CodeIgnite");
10
frm.add(lt);
frm.add(lt2);
frm.add(lbl);
frm.add(btn);
frm.setSize(500,500);
frm.setLayout(null);
frm.setVisible(true);

btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String data = "Programing

Language Select:"+lt.getItem(lt.getSelectedIndex());
data +=",Framework Selected:";
for(String

frame:lt2.getSelectedItems())
{
data += frame+" ";
}
lbl.setText(data);
}
}
);
}
public static void main(String args[]) throws Exception
{
new ListDemo();
}
}

11
Scroll Bars
Scrollbars allows users to scroll the components. It can be set horizontally or
vertically. The slider box can be dragged by the user to a new position. Scrollbar
will then reflect this value. They are encapsulated by the Scrollbar class.

Constructors:

1) Scrollbar() : creates vertical scroll bar


2) Scrollbar(int style)
3) Scrollbar(int style, int initialValue, int thumbsize, int min, int max )

Second and third allows to mention the orientation of the scroll bar.
Styles can have values :
Scrollbar.VERTICAL – creates vertical scroll bar
Scrollbar.HORIZONTAL – creates horizontal scroll bar
In third , initial value is the initial value of the scroll bar. ‘thumbsize’ represents
number of units represented by the height of the thumb is passed. ‘min’ and
‘max’ represents minimum and maximum values for the scroll bar.

NOTE:-
In the background space on either size of the thumb, the user can click to cause
the thumb to jump in that direction by some increment larger than one, which
helps to translate the page up and down.

Methods:
1) void setValues(int initialValue, int thumbsize, int min, int max ) : to set the
parameters.
2) void getValue() : to obtain current value of the scroll bar.
3) void setValue(int newValue) : ‘newValue’ specifies new value for scroll bar.
4) int getMinimum():To retrieve minimum value.
5) int getMaximum():To retrieve maximum value.

//Demonstrate Scroll Bar


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

/* <applet code="SBDemo" height=400 width=400>


</applet> */

public class SBDemo extends Applet implements AdjustmentListener,


MouseMotionListener
{
12
String msg = " ";
Scrollbar vsb, hsb;

public void init()


{
int w = Integer.parseInt(getParameter("width"));
int h = Integer.parseInt(getParameter("height"));

vsb = new Scrollbar(Scrollbar.VERTICAL,0,1,0,h);


hsb = new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,w);
add(vsb);
add(hsb);

vsb.addAdjustmentListener(this);
hsb.addAdjustmentListener(this);
addMouseMotionListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ar)
{
repaint();
}

public void mouseDragged(MouseEvent me)


{
int x = me.getX();
int y = me.getY();
vsb.setValue(y);
hsb.setValue(x);
repaint();
}
public void mouseMoved(MouseEvent me)
{

}
public void paint(Graphics g)
{
msg += "Vertical: "+vsb.getValue();
msg += "Horizontal: "+hsb.getValue();
g.drawString(msg,6,160);
g.drawString("******",hsb.getValue(),vsb.getValue());
}
}

13
Text Field

TextField is a class which implements a single line text area usually called and
edit control. We can enter strings to it and also edit the text using the arrow key,
cut ,copy, paste and mouse selections.

Constructors:
1) TextField() : Default text field.
2) TextField(int numChars) : specifies the number of characters it can hold.
3) TextField(String str) : It initializes the textfield with the string specified.
4) TextField(String str, int numChars) : initializes a textfield and sets it width.

Methods:
1) String getText() : to obtain the string currently in the textfield.
2) void setText(String str) : to set the text.
3) select() : you can select portion of text under program control.
4) getSelectedText() : to obtain the currently selected text.
5) setEditable() : allows you to control a textfield may be modified by the user.
void setEditable(Boolean canEdit)
6) isEditable() : to deteremine whether it is editable or not.
Boolean isEditable()
7) setEchoChar() : to set echoing of character as they are typed.
void setEchoChar(char ch)
8) getEchoChar() : to retrieve the echochar
char getEchoChar()

//Demonstrate text field


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

/*<applet code="TextFieldDemo" width=400 height=400>


</applet>*/

public class TextFieldDemo extends Applet implements ActionListener


{
TextField name,pass;
public void init()
{
Label namep = new Label("Name:", Label.RIGHT);
Label passp = new Label("Password:",Label.RIGHT);

name = new TextField(12);


14
pass = new TextField(8);
pass.setEchoChar('*');

add(namep);
add(name);
add(passp);
add(pass);

name.addActionListener(this);
pass.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString("Name: "+name.getText(),6,60);
g.drawString("Selected text in name:
"+name.getSelectedText(),6,80);
g.drawString("Password: "+pass.getText(),6,100);
}
}

15
Text Area

It is a multi line editor by AWT.

Constructors:

1) TextArea() : default.
2) TextArea(int numlines, int numchars) : specifies the height and number of
characters.
3) TextArea(String str):sets the default string.
4) TextArea(String str, int numlines, int numchars):specifies width and
characters.
5) TextArea(String str, int numlines, int numchars,int sBars):specifies the scroll
bars that you want to control.

Possible values for sBars:


SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY

Methods:
1) getText()
2) setText()
3) getSelectedText()
4) select()
5) isEditable()
6) setEditable()
7) void append(String str):appends a string to the end of current text.
8) void insert(String str,int index):insert the string passed.
9) void replaceRange(String str,int startIndex,int endIndex):it replaces the
characters from the index specified.
//Demonstrate TextArea
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

/*<applet code="TextAreaDemo" width=250 height=50></applet>*/

public class TextAreaDemo extends Applet


{
public void init()
{
16
String val =
"Javal SE 6 is the lastese version of the most \n"+
"widely-used computer language for internet programming."+
"Building on a rich heritage, java have advanced both\n"+
"the art and science of computer language design.\n\n"+
"One of the reasons for java's ongoing success is its\n"+
"constant, steadly rate of evolution. Java has never stood"+
"repidly changing landscape of the networked world.\n"+
"Moreover, java has often led the way, charting the \n"+
"course for others to follow.";

TextArea txtArea = new TextArea(val,10,30);


add(txtArea);
}
}

17
Layout Managers
Layout means the arrangement of components within the container. In other way
we can say that placing the components at a particular position within the
container. The task of layouting the control is done automatically by the Layout
Manager.

Layout Manager
The layout manager automatically positions all the components within the
container. If we do not use layout manager then also the components are
positioned by the default layout manager. It is possible to layout the controls by
hand but it becomes very difficult because of the following two reasons.
 It is very tedious to handle a large number of controls within the container.
 Often the width and height information of a component is not given when
we need to arrange them.
Java provides us with various layout managers to position the controls. The
properties like size shape and arrangement varies from one layout manager to
other layout manager. When the size of the applet or the application window
changes the size, shape and arrangement of the components also changes in
response i.e. the layout managers adapt to the dimensions of appletviewer or the
application window.

18
FlowLayout
FlowLayout is the default layout manager for an applet. This class places
the components in a row that is centered in the available space. If the
components cannot fit in the current row, another row will be started.
This class has three constructors which are as follows:
(1) FlowLayout()
(2) FlowLayout(int align)
(3) FlowLayout(int align, int hgap, int vgap)
Here, the align indicates how the components are aligned in a row. The
horizontal and vertical gap in pixels between will be set through hgap and vgap
The FlowLayout class also defines three constants that can be used as
alignment i.e. LEFT, CENTER and RIGHT.
Methods
int getAlignment():-Gets the alignment for this layout.
int getHgap():-Gets the horizontal gap between components.
int getVgap():-Gets the vertical gap between components.
void layoutContainer(Container target):- Lays out the container.
import java.applet.*;
import java.awt.*;
/*
<applet code="FlowLayoutDemo" width=650 height=350>
</applet>
*/
public class FlowLayoutDemo extends Applet
{
public void init()
{
setLayout(new FlowLayout(FlowLayout.RIGHT,50,50));
for(int i=0;i<20;i++)
{
if(i<9)
add(new Button("Button 0"+(i+1)));
else
add(new Button("Button "+(i+1)));
}
}
}
BorderLayout
The BorderLayout class allows a programmer to specify the placement of a
component. This is done by using geographic terms i.e. “North”, “South”,
19
“East”, “West” or “Center”. The components are placed around the periphery
with the sizes they require. The components in the center uses the remaining
space.
This class has two constructors are as follows :
(1) BorderLayout()
(2) BorderLayout(int hgap, int vgap)

The first form uses no gaps between the components. The second form
allows you to set the horizontal and vertical gaps between the components with
the help of hgap and vgap.
With BorderLayout class gives a different form of add method used which
is as follows :

void addLayoutComponent(Component comp, Object constraints)


Adds the specified component to the layout, using the specified constraint object.
int getHgap()
Returns the horizontal gap between components.
float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
void removeLayoutComponent(Component comp)
Removes the specified component from this border layout.

import java.applet.*;
import java.awt.*;
/*
<applet code="BorderLayoutApplet" width=300 height=300></applet>
*/
public class BorderLayoutApplet extends Applet
{
public void init()
{
setLayout(new BorderLayout(20,20));
Button b1 = new Button("North");
Button b2 = new Button("South");
Button b3 = new Button("East");
Button b4 = new Button("West");
Button b5 = new Button("Center");
add(b1,"North");
add(b2,"South");
add(b3,"East");
add(b4,"West");
add(b5,"Center");
}
}
20
CardLayout
The class CardLayout arranges each component in the container as a card.
Only one card is visible at a time, and the container acts as a stack of cards.
Constructors
CardLayout():-Creates a new card layout with gaps of size zero.
CardLayout(int hgap, int vgap):-Creates a new card layout with the
specified horizontal and vertical gaps.

Methods
void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to this card layout's internal table of names.
float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<applet code="CardLayoutDemo" width=500 height=500>


</applet>*/

public class CardLayoutDemo extends Applet implements ActionListener,


MouseListener
{
Checkbox Win98, winNT, solaris, mac;
Panel osCards;
CardLayout cardLO;
Button Win, Other;
public void init()
{
Win = new Button("Windows");
Other = new Button("Other");
add(Win);
add(Other);

cardLO = new CardLayout();


osCards = new Panel();
osCards.setLayout(cardLO);//set panel layout ot card layout
21
Win98 = new Checkbox("Windows 98",null,true);
winNT = new Checkbox("Windows NT/2000");
solaris = new Checkbox("Solaris");
mac = new Checkbox("MacOS");

//add Window checkbox to a panel


Panel winPan = new Panel();
winPan.add(Win98);
winPan.add(winNT);

//add other Os checkbox to a panel


Panel otherPan = new Panel();
otherPan.add(solaris);
otherPan.add(mac);

//add panels to card deck panel


osCards.add(winPan, "Windows");
osCards.add(otherPan,"Other");

//add cards tp main applet panel


add(osCards);

//register to receiver action events


Win.addActionListener(this);
Other.addActionListener(this);
addMouseListener(this);
}
public void mousePressed(MouseEvent me)
{
cardLO.next(osCards);
}
public void mouseClicked(MouseEvent me)
{}
public void mouseEntered(MouseEvent me)
{}
public void mouseExited(MouseEvent me)
{}
public void mouseReleased(MouseEvent me)
{}

public void actionPerformed(ActionEvent ae)


{
if(ae.getSource() == Win)
{
22
cardLO.show(osCards,"Windows");
}
else
{
cardLO.show(osCards,"Windows");
}
}
}

23
GridLayout
GrideLayout lays out components in a 2d grid. When you instantiate a
GridLayout, you define the number of rows and columns. The constructors
supported by GridLayout are shown here:
GridLayout()
GridLayout(int rows,int cols)
GridLayout(int rows, int cols, int horz, int vets)
import java.awt.*;
import java.applet.*;

/*<applet code="GridlayoutDemo" width=500 height=500></applet>*/

public class GridlayoutDemo extends Applet


{
static final int n = 4;
public void init()
{
setLayout(new GridLayout(n,n));
setFont(new Font("Monotype Corsiva",Font.BOLD,24));
for(int i=0;i<n;i++)
{
for(int j=0; j<n; j++)
{
int k=i * n +j;
if(k>0)
{
add(new Button(" "+k));
}
}
}
}
}

24
GridBagLayout with GridBagConstraints
GridBagLayout makes the grid bag useful is that you can specify the relative
placement of components by specifying their position within cell inside a grid.
The key to the grid bag is that each component can be different size and each
row in the fird can have a different number of liked to it.
This is why the layout is called gridbaglayout. It’s collection of small girds
joined together.
The location and size of each component in a grid bag are determined by a set
constraints linked to it.
The constraints are contained in an object of type GridBagConstrains.
Constraints include the height and width of a cell, and the placement of a
component, its alignment and its anchor point within the cell.
The general procedure for using a grid bag is to first create a new
GridBagLayout object and to make it the current layout mananger.
Then, set the constraints that apply to each component that will be added to the
grid bag.
Finally, add the components to the layout manager. Although GridBagLayout is
a bit more complicated than the other layout managers, it is still quite easy to use
once you understand how it works.
GridBagLayout define only one constructor, which is shown here:
GridBagLayout( )
GridBagLayout defines several methods, of which are protected and not for
general use. There is one method, however that you must use: setConstraints( ).
It is shown here: void setConstraints(Component obj, GridBagLayout cons)
The key to successfukky using GridBagLayout is the proper setting of the
constraints, which are stored in a GridBagConstraints object.
GridBagConstraints defines several fields that you can set to govern the size, placement and spacing
of a component. These are shown in table. Several are describe in greater detail in the following
discussion.
Field Purpose
int anchor specifies the location of a component
within a cell. The default is
GridBagConstraints.CENTER
int fill Specifies how a component is resized if
the component is small than its cell.
Valid values are
GridBagConstraints.NONE,
GridBagConstraints.HORIZONTAL,
GridBagConstraints.VERTICAL,
GridBagConstraints.BOTH.
int gridheight specifies the height of component in
terms of cells. The default is 1.
int gridwidth specifies the width of component in
25
terms of cells. The default is 1.
int gridx specifies the X coordinate of the cell to
which the component will be added. The
default value is
GridBagConstraints.RELATIVE
int gridy specifies the Y coordinate of the cell to
which the component will be added. The
default value is
GridBagConstraints.RELATIVE
Insets insets This field specifies the external padding
of the component, the minimum amount
of space between the component and the
edges of its display area.
int ipadx Specific extra horizontal space that
surrounds a component within a cell. The
default size 0.
int ipady Specific extra vertical space that
surrounds a component within a cell. The
default size 0.
double weightx Specific a weight value that determines
the horizontal spacing between cells and
the edge of the container that holds them.
The default value is 0.0. the greater the
weight, the more space that is allocated if
all values are 0.0, extra space is
distributed evenly between the edges of
the window.
double weighty Specific a weight value that determines
the vertical spacing between cells and the
edge of the container that holds them.
The default value is 0.0. the greater the
weight, the more space that is allocated if
all values are 0.0, extra space is
distributed evenly between the edges of
the window.
GridBagConstraints also defines several static fields that contain standard
constraint values, such as GridBagConstraints.CENTER and
GridBagConstraints.VERTICAL.
When a component is smaller than its cell, you can use the anchor field to specify where within the
cell the component’s top-left corner will be located. There are three types of values that you can give
to anchor.
GridBagConstraints.CENTER GridBagConstraints..SOUTH
GridBagConstraints.EAST GridBagConstraints.SOUTHEAST
GridBagConstraints.NORTH GridBagConstraints.SOUTHWEST
26
GridBagConstraints.NORTHEAST GridBagConstraints.WEST
GridBagConstraints.NORTHWEST
As their names imply, these values cause the component to be placed at the
specific locations.
//USE gribagLayout
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<applet code="GridBagDemo" width=250 height=250>


</applet>*/

public class GridBagDemo extends Applet implements ItemListener


{
String msg=" ";
Checkbox winXP, winVista, solaris, mac;
public void init()
{
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbag);

//Define the grid box


winXP = new Checkbox("Window XP",null,true);
winVista = new Checkbox("Window Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");

//Define the grid bag.


//Use default row weight of 0 for first row.
gbc.weightx = 1.0; //use a column weight of 1
gbc.ipadx = 200; //pad by 200 unit
gbc.insets = new Insets(4,4,0,0);//inset slightly from top left
gbc.anchor = GridBagConstraints.NORTHEAST;

gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(winXP,gbc);

gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(winVista,gbc);

//give second row a weight of 1


gbc.weighty = 1.0;

27
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(solaris,gbc);

gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(mac,gbc);

//add the components.


add(winXP);
add(winVista);
add(solaris);
add(mac);

//Register to receive item events.


winXP.addItemListener(this);
winVista.addItemListener(this);
mac.addItemListener(this);
}
//Repaint when status of a check obx changes.
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
//display current state of the check boxes
public void paint(Graphics g)
{
msg = "Current State: ";
g.drawString(msg,6,80);
msg = " Window XP: "+winXP.getState();
g.drawString(msg,6,100);
msg = " Window Vista: "+winVista.getState();
g.drawString(msg,6,120);
msg = " Solaris: "+solaris.getState();
g.drawString(msg,6,140);
msg = " Mac: "+mac.getState();
g.drawString(msg,6,160);
}
}

28
Panels
The Panel class extends Container. It appears as a rectangular area in
which other components are arranged. A layout manager is associated with a
panel and determines the placement of those components. You can set the
layout manager that is used for a panel.
It is also possible to nest the panel within other panels. This can be done
because a Panel object is also a Component. Here we can use different layout
managers to arrange different areas of the display.

import java.applet.*;
import java.awt.*;
/*
<applet code="PanelDemo" width=200 height=300>
</applet>
*/
public class PanelDemo extends Applet
{
public void init()
{
setLayout(new BorderLayout());
Panel pn=new Panel();
Checkbox cb1=new Checkbox("Red",true);
pn.add(cb1);
Checkbox cb2=new Checkbox("Green",false);
pn.add(cb2);
Checkbox cb3=new Checkbox("Blue",false);
pn.add(cb3);
add(pn,"North");
Panel pc=new Panel();
pc.setLayout(new GridLayout(3,2));
for(int i=1;i<=6;i++)
pc.add(new Button("Button "+i));
add(pc,"Center");
Panel ps=new Panel();
Label l=new Label("This is the south panel");
ps.add(l);
add(ps,"South");
}
}
Windows and Frames
The window class extends Container and provides a separate window
without a tile or menu bar. This class has two subclasses, Frame and Dialog,
that are commonly used in applets and windows based applications.
29
This class has only one constructor i.e.
Window(Frame parent)
Here the parent is the owner of this window.
We have register / unregister various window events via this method.
void addWindowListener(WindowListener wl)
void removeWindowListener(WindowListener wl)
Here the wl is the window listener object
A new window is initially invisible. To make it appear, invoke the show()
method as follows :
void show()
Finally when you finish using a window, you should relinquish (hand over) its
resources by calling dispose( ) like void dispose( )
A window object generates events when a window is activated, closed,
closing, deactivated, deiconified (invoked when a window is changed from a
minimized to a normal state), iconified (invoked when a window is changed
from a normal to a minimized state), or opened.
A java.awt.event.WindowEvent object is created to describe this event.
The WindowListener interface provides us various methods to handle window
events which are as follows :
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivted(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
Here the we is the WindowEvent objecte generated by the source. The
windowActivated() and windowDeactivated() methods are called when the
window is activated or deactivated.
The windowClosing() method is called when a user requests that a window
to be closed. The windowClosed() method is called after a Window object has
been closed through setVisible() or destroy() methods.
The windowDeiconified() and windowIconified() methods are called after
a window is deiconified or iconified. The windowOpened() method is called
when a window is initially opened.
The Frame class extends Window and provids title and menu bar. This is
equivalent to what you have seen as a standard window in graphical user
interface. It has following constructors
(1) Frame()
(2) Frame(String title)
Here title is the string to be displayed in the title bar. We can also have menubar
with following methods
(1) MenuBar getMenuBar()
(2) void setMenuBar(MenuBar mb)
30
We may get and set the title with the help of following methods.
(1) String getTitle()
(2) void setTitle(String str)
here, str is the string that is used in the title bar of the frame.
import java.awt.*;
import java.awt.event.*;
class FrameApp extends Frame
{
FrameApp(String title)
{
super(title);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}
public class FrameApplicationDemo
{
public static void main(String args[])
{
FrameApp frm=new FrameApp("Welcome to frame");
Button b=new Button("Ashish");
frm.add(b);
frm.show();
frm.setSize(200,200);
}
}
Menus and MenuBars
A Frame may contain a menu bar. This represents a set of options for the
user. When the mouse is clicked on an option a drop down list of sub options
appears. Each of these sub options may also have sub options associated with it.
Some sub options may be checkable. i.e. a check mark will be appeared when we
select that particular option.
In the following figure we can see the actual relationship among the
classes that provides this functionality.

31
Here, the MenuComponent class is the superclass of all other classes. The
Font used for a menu-related string may be set via its setFont() method as
below :
void setFont(Font f)
here f is the font to be used.
The MenuBar class encapsulates the functionality of a menu bar. It has this
constructor : Menubar()

There is one method called add() which allows the Menu objectes to be added to
the menu bar.
Menu add(Menu m)
Here m is the Menu to be added to the MenuBar.

The Menu class encapsulates the functionality of a drop-down set of menu items.
Its constructor is :
Menu (String str)
Here str is the string to be displayd.

In MenuItem also we have one method called add() to add MenuItems to the
menu
MenuItem add(MenuItem mi)
void add(String str)
Here mi is the MenuItem to be added to the menu and str is a string to be
added to the menu.

The MenuItem class encapsulates an item in a menu. Its constructor is


MenuItem(String str)
here str is the string to be displayed.

All the menu items will generate actions events when they are selected or
deselected for that we need to register ActionListener like :
void addActionListener(ActionListener al)
32
void removeActionListener(ActionListener al)
here al is the action listener.

We can also enable or disable any menuitem with the help of following method
void setEnabled(boolean flag)
if the flag is true then menu item is enabled otherwise disabled.

The CheckBoxMenuItem class allows us to create Menu Item with checkbox for
that constructors are :
CheckboxMenuItem(String str)
CheckboxMenuItem(String str, boolean flag)
Here str is the string to be displayed for the checkbox menu item. If flag is
true, the item is checked otherwise not checked.

CheckboxMenuItem will generate item events when they are selected or


deselected.
We have two methods to register and unregister listener like :
(1) void addItemListener(ItemListener il)
(2) void removeItemListener(ItemListener il)
here il is the item listener
To find / replace the state of the check box menu item we have two methods
like :
boolean getState()
void setState(boolean flag)
if flag is true then checkbox menu item is set otherwise it is cleared.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="MenuDemo" width=400 height=200></applet>
*/
class MenuFrame extends Frame implements
ActionListener,ItemListener,WindowListener
{
MenuDemo mainapp;

MenuFrame(String title,MenuDemo mainapp)


{
super(title);
this.mainapp=mainapp;
addWindowListener(this);
MenuBar mb=new MenuBar();
setMenuBar(mb);
33
//a
Menu a=new Menu("a");
mb.add(a);
MenuItem a1=new MenuItem("a1");
a1.addActionListener(this);
a.add(a1);
MenuItem a2=new MenuItem("a2");
a2.addActionListener(this);
a.add(a2);
MenuItem a3=new MenuItem("a3");
a3.addActionListener(this);
a.add(a3);

//b
Menu b=new Menu("b");
mb.add(b);
MenuItem b1=new MenuItem("b1");
b1.addActionListener(this);
b.add(b1);
MenuItem b2=new MenuItem("b2");
b2.addActionListener(this);
b.add(b2);

//b sub
Menu b3=new Menu("b3");
b.add(b3);
MenuItem b31=new MenuItem("b31");
b31.addActionListener(this);
b3.add(b31);
MenuItem b32=new MenuItem("b32");
b32.addActionListener(this);
b3.add(b32);

//c
Menu c=new Menu("c");
mb.add(c);
MenuItem c1=new MenuItem("c1");
c1.addActionListener(this);
c.add(c1);
MenuItem c2=new MenuItem("c2");
c2.addActionListener(this);
c.add(c2);

34
//d with checkbox
Menu d=new Menu("d");
mb.add(d);
CheckboxMenuItem d1=new CheckboxMenuItem("d1");
d1.addItemListener(this);
d.add(d1);
CheckboxMenuItem d2=new CheckboxMenuItem("d2");
d2.addItemListener(this);
d.add(d2);
}
public void actionPerformed(ActionEvent ae)
{
mainapp.ta.append("ActionEvent "+ae.getActionCommand()+"\n");
}
public void itemStateChanged(ItemEvent ie)
{
CheckboxMenuItem cmi=(CheckboxMenuItem)ie.getSource();
mainapp.ta.append("ItemEvent "+cmi.getLabel()+" State
"+cmi.getState()+"\n");
}
public void windowActivated(WindowEvent we)
{
}
public void windowClosed(WindowEvent we)
{
}
public void windowClosing(WindowEvent we)
{
dispose();
}
public void windowDeactivated(WindowEvent we)
{
}
public void windowIconified(WindowEvent we)
{
}
public void windowDeiconified(WindowEvent we)
{
}
public void windowOpened(WindowEvent we)
{
}
}
public class MenuDemo extends Applet
35
{
TextArea ta;
public void init()
{
MenuFrame mf=new MenuFrame("My Frame",this);
mf.show();
mf.setSize(200,200);
ta=new TextArea(10,20);
add(ta);
}
}

36
Dialog and FileDialog
Dialogs are commonly presented in graphic user interface to display
information or obtain input.
A model dialog does not permit a user to make another window in the
application active until it has been closed.
A modeless dialog allows a user to switch to another window in the
application before closing the dialog.
The Dialog class extends Window. It provides a window in which all of
the user interface components will be used as it is. This class has four
constructors :
(1)Dialog(Frame parent)
(2)Dialog(Frame parent, boolean flag)
(3) Dialog(Frame parent, String title)
(4) Dialog(Frame parent, String title, boolean flag)
Here the parent is the reference to the owner of the dialog. The dialog is
model if the flag is true `otherwise it is modeless.
The show() method of the class is useful to make a dialog visible.
void show()

The FileDialog class extends Dialog and provides a dialog that allows a user to
select a file for reading and writing. This is very useful for applications that
need to save data to a file and later retrieve that data.
This class defines two int constants named LOAD and SAVE. These will
determine that the file dialog is used to select a file for reading or writing.
This class has three constructors :
(1) FileDialog(Frame parent)
(2) FileDialog(Frame parent, String str)
(3) FileDialog(Frame parent, String str, int rw)
Here parent is the frame that creates this dialog. The title bar will be
defined by the str. The final argument indicates if this file dialog identifies a file
for loading or saving. if rw is LOAD, a file will be identified for reading. If rw
is SAVE, a file is for writing. The first two forms will create a file dialog for
LOAD a file.
import java.awt.*;
import java.awt.event.*;
public class MessageDialog extends Frame implements ActionListener
{
Button b;
public static void main(String args[])
{
MessageDialog md=new MessageDialog();
md.setVisible(true);
md.setSize(200,100);
37
}
MessageDialog()
{
super("Message Dialog Demo");
setLayout(new FlowLayout());
b=new Button("Click me");
b.addActionListener(this);
add(b);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
String message="This is the message";
messageDialogExample mde=new
messageDialogExample(this,"Message Dialog",true,message);
mde.show();
}
}
class messageDialogExample extends Dialog implements ActionListener
{
Button ok;
messageDialogExample(Frame parent,String title,boolean mode,String
msg)
{
super(parent,title,mode);
Panel pc=new Panel();
Label l=new Label(msg);
pc.add(l);
add(pc,"Center");

Panel ps=new Panel();


ok=new Button("ok");
ok.addActionListener(this);
ps.add(ok);
add(ps,"South");

pack();

addWindowListener(new WindowAdapter(){
38
public void windowClosing(WindowEvent we)
{
dispose();
}
});
}
public Insets getInsets()
{
return new Insets(40,40,40,40);
}
public void actionPerformed(ActionEvent ae)
{
dispose();
}
}

39
Example of File Dialog
import java.awt.*;
import java.awt.event.*;
public class FileDialogApplication extends Frame implements
ActionListener,WindowListener
{
Button load,save;
TextField tf;
public static void main(String args[])
{
FileDialogApplication fda=new FileDialogApplication();
fda.setVisible(true);
fda.setSize(400,100);
}
FileDialogApplication()
{
super("Dialog Application");
setLayout(new FlowLayout());
load=new Button("Load");
load.addActionListener(this);
add(load);
save=new Button("Save");
save.addActionListener(this);
add(save);
tf=new TextField(20);
add(tf);
addWindowListener(this);
}
public void actionPerformed(ActionEvent ae)
{
FileDialog FD;
if(ae.getSource()==load)
{
FD=new FileDialog(this,"Load File",FileDialog.LOAD);
}
else
{
FD=new FileDialog(this,"Save File",FileDialog.SAVE);
}
FD.show();
String fnm=FD.getDirectory()+FD.getFile();
if(fnm!=null)
{
40
tf.setText(fnm);
}
}
public void windowActivated(WindowEvent we)
{}
public void windowDeactivated(WindowEvent we)
{}
public void windowIconified(WindowEvent we)
{}
public void windowDeiconified(WindowEvent we)
{}
public void windowClosed(WindowEvent we)
{}
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
public void windowOpened(WindowEvent we)
{}
}

41

You might also like