AWT (Abstract Window Toolkit) and Swing

– AWT provides us with very limited set of components because AWT makes native calls to OS to make components. Only those components

which are supported by all the platforms are supported by AWT, so they are very limited. Eg. Button, Text, Scrollbar, Window, Frame, Panel,

Label, Dialog etc.

– Components must be placed in a container. Conatainer class has an add method to place the component inside it.



To create checkbox:

CheckBox cb = new CheckBox("name",null,true);
//null is the group. true specifies whether it should be selected by default

There are no radio buttons in AWT. To create one, you need to create CheckBoxGroup and add checkboxes to it.

CheckBoxGroup cbg = new CheckBoxGroup();

new CheckBox("name",cbg,true)
new CheckBox("name",cbg,false)
new CheckBox("name",cbg,true)

In the above checkbox only the third one will be secleted because in a radio button or checkbox group only one can be selected and that would be

the last one to specify value as true.

How to place components in application program?

public static void main(String args[]){

Button b1 = new Button("Ok");
Button b1 = new Button("Cancel");

//Place the components inside the container

//1. First get the frame. Both diaglog and frame are derived from Window class.
Frame f1 = new Frame("Title");
//in pixels


//Display the frame. This brings out the frame with the components.

//If you need to add components after making the frame visible, then call validate. This method redraws everything.


How to work with Menus?
Assume we are going to put in File and Help Option.
File has Open , Close, Exit
Help has About Status Option (sub options)

Menus are only supported by Frames in AWT. We have a frame that consists of Menu Bar, Menu, Menu Item, Check box Menu Item(Toggle)

You can create objects in whatever sequence but place them in sequence.

public static void main(String args[]){

MenuBar mb = new MenuBar();
Frame fr = new Frame();


Menu f = new Menu("File");
Menu h = new Menu("Help");
Menu op = new Menu("Options");

MenuItem o = new MenuItem("Open");
MenuItem c = new MenuItem("Close");
MenuItem e = new MenuItem("Exit");
MenuItem a = new MenuItem("About");
MenuItem one = new MenuItem("Open");
MenuItem two = new MenuItem("two");

CheckboxMenuItem s = new CheckboxMenuItem("Status");

//Follow the sequence now








What is the size of the component, where am i adding component to, how to interact with the component?

Layout Managers: These tell the container where to have the components. They define how the components will be placed in the contianer.

5 Layouts:

FlowLayout -- Default layout for panel and applet
BorderLayout -- Default for frame and dialog
GridbagConstraints - Helper class for GridbagLayout

Flow Layout: Places components one next to other. It is aligned to center. by default. A container cannot have more than one layout at a time.

You can define the horizontal and vertical distance.

int hgap = 10;
int vgap = 20;
FlowLayout fl = new FlowLayout(FlowLayout.LEFT, FlowLayout, hgap, vgap);
// These values can be specified later as well by using fl object.
new Frame().setLayout(fl);

BorderLayout: Maximum of 5 components in the container. In a BL, there are 5 directions - NEWS and C

size of the component is size of the direction. Center takes all the empty directions if no component is placed there.

container.setLayout(new BorderLayout());

fr.add(b1) -- By default it adds to the center.

CardLayout - The component takes the entire Screen/Container space. Think of tabbed window in browser. Only one component can be

displayed when selected and that takes up the entire screen space. To move from one component to another:

container.setLayout(new CardLayout());

cl.add(b1, "uniquiname");"uniquename")

GridLayout: container is divided into cells.

new GridLayout(rows,cols);

The component will occupy the entire cell. When a new component is added when the grid is full , it extends by the column and rearranges all the

components in order.

new GridLayout(); ---> It is a single cell. When you add components they get added by the column.

GridBagLayout: Like Html - colspan, rowspan , padding . You can give more than one cell space to the component. This is the main difference

between gl and gbl

Properties that are available to work with from GridbagConstraints class are:

gridx (default: 0) top left corner
gridy (default:0) top of the component
gridwidth (default:1) how many rows a component can take up
gridheight (default:1 how many columns a component can take up
anchor (default:center where the component is placed
fill (default:none) - Do you want the component to take the entire Horizontal space or Vertical space or both?
ipadx (default:0 Space padding that should be done between the components
ipady (default:0 )
weightx (default:0)
weighty (default:0)

How to place components in the gbl?

GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();


Button b1 = new Button();
fr.add(b1,gbc); //If you didn't set any values for gbc , it takes all the default values.

Button b2 = new Button();
gbc.gridwidth = 3;
gbc.gridheight = 2;
gbc.gridx = 1;

Button b3 = new Button();
gbc.gridx = 4; // because b2 takes three cells
gbc.gridx = GridbagConstraints.RELATIVE;

// If you want it to take rest of the row space
gbc.gridwidth = GridbagConstraints.REMAINDER

How come the same gbc is used?
It makes clone of the object every time.

What is weightx and weighty?
It places by default to the more center all the components. If you want to spread out the content so that it is more layed out. eg. you specify left

and right margins and write content. Then you do justify
to lay it out/spread it out so that left to right margin is occupied. That is what weightx and weighty does.

weightx spreads out the component horizontally and weighty does it vertically.

You can also define your own layout using the layout manager interface.
fr.setLayout(null) ---> No Layout is used.
In this case you need to specify the position and the size of each component manually and then add it to the frame.

Button b1=new Button();


b1.setBounds(x,y,width,height); --> 50,30,100,80

A container having border layout --> can't specify size because it takes size of the direction
card layout --> can't specify size because it takes size of the entire layout
grid layout --> can't specify size beacause it takes size of the cell.

flow layout --> Can specify size but you need to derive a class from the component class itself and override the setPreferredsize method. You don't

invoke , it will be invoked by the API.
gridbaglayout --> Can specify size but you need to derive a class from the component class itself and override the setPreferredsize method. You

don't invoke , it will be invoked by the API.

// Aplet has a flow layout


public But extends Button(){

public Dimension getPreferredSize(int x, int y){

int x,y;

return newDimension(x, y);


public But(String s, int x, int y){

this.x = x;
this.y = y;

public static void main(String args[]){
But b1 = new But("OK", 70, 90);

Insets: Space between container and component. Like a margin for a word document - top, bottom, left, right

// extend the container and override the getInsets method. This is automatically called

public Insets getInsets(){
return new Insets(top,left,bottm,right);

Handle Events which get raised:

import java.awt.event.*;

This package consists of Event Classes, Interfaces , Adapter Classes (Abstract Classes):

ActionEvent --> Mainly used for Menu, Textfield, Button
AdjustmentEvent --> Scrollbar
TextEvent --> TextArea , Textfield
ItemEvent - MenuItem, CheckboxMenuItem, CheckBox, List, Choice
WindowEvent - whenever we try to close the frame with the close button, minimize, maximize, activate, deactivate
MouseEvent = Mouse Pressed, MouseReleased, MouseDragged
KeyEvent --> KeyPressed , KeyReleased
ContainerEvent --> when you add/remove component from container
ComponentEvent --> relocate or resize compoent
Focus Event --> focus gained or lost on any component

For each event class there exists and Event Interface. They contain event handler methods.

ActionListener, AdjustmentListener, TextListener

There exists an adapter class for listener which have more than one event handler method:
eg for WindowListener there is WindowAdapter
MouseListener there is MouseAdapter
MouseMotionListener there is MouseMotionAdapter

What is the usage of these adapter classes:

interface i1 {



// interface is provided for implementation
class A implements I1{

public void add(){}
public void mod(){ .... }
public void del(){}


// class is provided now to extend
class i1class implemetns i1 {

public void add(){}
public void mod(){}
public void del(){}


Which will you chose? Is there any sense to make instance of i1class? No need of instance. Make it abstract. This is known as an Adapter Class.

// class is provided now to extend
abstract class i1class implemetns i1 {

public void add(){}
public void mod(){}
public void del(){}


Delegation Model:
1. implement the listener or extend the adapter class on the class
2. Implement the event handler methods.
3. Create the instance of the above class which will return the Listener
4. Bind the Component and the Listener by passing the Listener object to the Component. Invoke the method component.addxxxListener

xxx is the appropriate ListenerType . Eg. component.addActionListener
Listener object is placed into the vector of the component class. That is how you register more than one listener. This is like observer pattern.

When a button is clicked , dispatch event of the componet is called which creates ActionEvent object, and goes throgh the vector to find out the

ActionListener object and takes that object and calls the listener methods (actionPerformed) by passing the event object as parameter.

Swing Components: introduced in JDK 1.2

Swing Components are Java Bean Compoents .
These are lightweight Compoents bevauase they are drwan over an OS container.
AWT are heavy Weight Componetns because they call native calls.

There are 4 heighy weight containers in swing:

all siwnf comonet name starts with J.

because swinng compeonts are mere drawings on a container. they support large variety of components - lots of widget - tabls, tees, desktpms.,

icons, borders ect.

Swings started with MVC architecture to decouple the view with the model. Theu clubbed to gether view and the controller classes. so with each

compoent there is a ui and model class. it is now called mui architecture. model+viewcontroller . you can create your own model classes which

represents data for the application. view displays the data, controller

JComponent class is the root of all classes in swing is derived from AWT Compoent class.

New Features:

The layerd pane consists of different layers which gives z-order. smaller the z order number the closer the compoent looks and the higher the z-

order the farther the component.

Swing Containers are directly derived from AWT containers. so these are heavy weight Containers.

You don't directly add the component to the container. You add it to the content pane . call the getContentPane on the container to get

ContentPane and add Compoents to it.

Swing Look and Feel:
Java Look and Feel , now called as Metal Look and Feel

javax.swing.plaf - consists of diff. look and feel classes

UIManager.setLookandFeel(LookAndFeel Class)

Event Handling can be done in two ways:
self contained of event - the component itself handles the event.
delegation of event - make use of listener interface, mostly used.

//Tells which component raised the event
Object o= ActionEvent.getSource();
if(o instanceof Button)
Button tempButton = (Button) o;

String s = tempButton.getLabel();

You can handle multiple events for the component. For example MouseListener and ActionListener for a button. But which one gets executed is

not assured. However if you have the same Listener multiple times for teh component then it is done sequentially.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s