You are on page 1of 31

AWT in

JAVA
1

UNIT- IV
Introducing AWT working with Graphics: AWT Classes, Working with Graphics.
Event Handling: Two Event Handling Mechanisms, The Delegation Event Model, Event Classes, Source of Events,
Event Listener Interfaces.
AWT Controls: Control Fundamentals, Labels, Using Buttons, Applying Check Boxes, CheckboxGroup, Choice
Controls, Using Lists, Managing Scroll Bars, Using TextField, Using TextArea, Understanding Layout Managers,
Menu bars and Menus, Dialog Boxes, FileDialog, Exploring the controls, Menus ,and Layout Managers.

______________________________________________________________________________________________

Introducing AWT

Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application in java.

Java AWT components are platform-dependent i.e. components are displayed according to the view of operating
system. AWT is heavyweight i.e. its components uses the resources of system.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox,
Choice, List etc.

The hierarchy of Java AWT classes are given below.

Container

The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The
classes that extends Container class are known as container such as Frame, Dialog and Panel.
AWT in
JAVA
2

Window

The window is the container that have no borders and menu bars. You must use frame, dialog or another window
for creating a window.

Panel

The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button,
textfield etc.

Frame

The Frame is the container that contain title bar and can have menu bars. It can have other components like
button, textfield etc.

Useful Methods of Component class

Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component, by default false.

Java AWT Example


To create simple awt example, you need a frame. There are two ways to create a frame in AWT.

o By extending Frame class (inheritance)


o By creating the object of Frame class (association)

Simple example of AWT


import java.awt.*;  
class First extends Frame{  
First(){  
Button b=new Button("click me");  
b.setBounds(30,100,80,30);// setting button position  
  
add(b);//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  
}  
AWT in
JAVA
3

public static void main(String args[]){  
First f=new First();  
}}  

The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that sets the position
of the awt button.

Every user interface considers the following three main aspects:

 UI elements : Thes are the core visual elements the user eventually sees and interacts with. GWT
provides a huge list of widely used and common elements varying from basic to complex which we will cover in this
tutorial.
 Layouts: They define how UI elements should be organized on the screen and provide a final look and
feel to the GUI (Graphical User Interface). This part will be covered in Layout chapter.
 Behavior: These are events which occur when the user interacts with UI elements

AWT Graphics Class


The Graphics class is the abstract super class for all graphics contexts which allow an application to draw onto
components that can be realized on various devices, or onto off-screen images as well.

A Graphics object encapsulates all state information required for the basic rendering operations that Java supports.
State information includes the following properties.

 The Component object on which to draw.


 A translation origin for rendering and clipping coordinates.
 The current clip.
 The current color.
 The current font.
 The current logical pixel operation function.
 The current XOR alternation color

Class declaration
Following is the declaration for java.awt.Graphics class:
public abstract class Graphics
extends Object

Class constructors
S.N Constructor & Description
AWT in
JAVA
4

Graphics() () 
1
Constructs a new Graphics object.

Class methods
S.N
Method & Description
.

abstract void clearRect(int x, int y, int width, int height) 


1 Clears the specified rectangle by filling it with the background color of the
current drawing surface.

abstract void clipRect(int x, int y, int width, int height) 


2
Intersects the current clip with the specified rectangle.

abstract void copyArea(int x, int y, int width, int height, int dx, int dy) 
3
Copies an area of the component by a distance specified by dx and dy.

abstract Graphics create() 


4
Creates a new Graphics object that is a copy of this Graphics object.

Graphics create(int x, int y, int width, int height) 


5 Creates a new Graphics object based on this Graphics object, but with a new
translation and clip area.

abstract void dispose() 


6 Disposes of this graphics context and releases any system resources that it is
using.

void draw3DRect(int x, int y, int width, int height, boolean raised) 


7
Draws a 3-D highlighted outline of the specified rectangle.

abstract void drawArc(int x, int y, int width, int height, int startAngle,
8 int arcAngle) 
Draws the outline of a circular or elliptical arc covering the specified rectangle.

void drawBytes(byte[] data, int offset, int length, int x, int y) 
9 Draws the text given by the specified byte array, using this graphics context's
current font and color.

void drawChars(char[] data, int offset, int length, int x, int y) 
10 Draws the text given by the specified character array, using this graphics
context's current font and color.

abstract boolean drawImage(Image img, int x, int y, Color bgcolor,


11 ImageObserver observer) 
Draws as much of the specified image as is currently available.

abstract boolean drawImage(Image img, int x, int y, ImageObserver


12 observer) 
Draws as much of the specified image as is currently available.

abstract boolean drawImage(Image img, int x, int y, int width, int


height, Color bgcolor, ImageObserver observer) 
13
Draws as much of the specified image as has already been scaled to fit inside
the specified rectangle.

14 abstract boolean drawImage(Image img, int x, int y, int width, int


AWT in
JAVA
5

height, ImageObserver observer) 


Draws as much of the specified image as has already been scaled to fit inside
the specified rectangle.

abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int
dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver
observer) 
15
Draws as much of the specified area of the specified image as is currently
available, scaling it on the fly to fit inside the specified area of the destination
drawable surface.

abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int
dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) 
16 Draws as much of the specified area of the specified image as is currently
available, scaling it on the fly to fit inside the specified area of the destination
drawable surface.

abstract void drawLine(int x1, int y1, int x2, int y2) 
17 Draws a line, using the current color, between the points (x1, y1) and (x2, y2)
in this graphics context's coordinate system.

abstract void drawOval(int x, int y, int width, int height) 


18
Draws the outline of an oval.

abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) 


19
Draws a closed polygon defined by arrays of x and y coordinates.

void drawPolygon(Polygon p) 


20
Draws the outline of a polygon defined by the specified Polygon object.

abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) 


21
Draws a sequence of connected lines defined by arrays of x and y coordinates.

void drawRect(int x, int y, int width, int height) 


22
Draws the outline of the specified rectangle.

abstract void drawRoundRect(int x, int y, int width, int height, int


arcWidth, int arcHeight) 
23
Draws an outlined round-cornered rectangle using this graphics context's
current color.

abstract void drawString(AttributedCharacterIterator iterator, int x,


int y) 
24
Renders the text of the specified iterator applying its attributes in accordance
with the specification of the TextAttribute class.

abstract void drawString(String str, int x, int y) 


25 Draws the text given by the specified string, using this graphics context's
current font and color.

void fill3DRect(int x, int y, int width, int height, boolean raised) 


26
Paints a 3-D highlighted rectangle filled with the current color.

abstract void fillArc(int x, int y, int width, int height, int startAngle, int
27 arcAngle) 
Fills a circular or elliptical arc covering the specified rectangle.

abstract void fillOval(int x, int y, int width, int height) 


28
Fills an oval bounded by the specified rectangle with the current color.

abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) 


29
Fills a closed polygon defined by arrays of x and y coordinates.

30 void fillPolygon(Polygon p) 


AWT in
JAVA
6

Fills the polygon defined by the specified Polygon object with the graphics
context's current color.

abstract void fillRect(int x, int y, int width, int height) 


31
Fills the specified rectangle.

abstract void fillRoundRect(int x, int y, int width, int height, int


32 arcWidth, int arcHeight) 
Fills the specified rounded corner rectangle with the current color.

void finalize() 
33
Disposes of this graphics context once it is no longer referenced.

abstract Shape getClip() 


34
Gets the current clipping area.

abstract Rectangle getClipBounds() 


35
Returns the bounding rectangle of the current clipping area.

Rectangle getClipBounds(Rectangle r) 


36
Returns the bounding rectangle of the current clipping area.

Rectangle getClipRect() 
37
Deprecated. As of JDK version 1.1, replaced by getClipBounds().

abstract Color getColor() 


38
Gets this graphics context's current color.

abstract Font getFont() 


39
Gets the current font.

FontMetrics getFontMetrics() 
40
Gets the font metrics of the current font.

abstract FontMetrics getFontMetrics(Font f) 


41
Gets the font metrics for the specified font.

boolean hitClip(int x, int y, int width, int height) 


42 Returns true if the specified rectangular area might intersect the current
clipping area.

abstract void setClip(int x, int y, int width, int height) 


43
Sets the current clip to the rectangle specified by the given coordinates.

abstract void setClip(Shape clip) 


44
Sets the current clipping area to an arbitrary clip shape.

abstract void setColor(Color c) 


45
Sets this graphics context's current color to the specified color.

abstract void setFont(Font font) 


46
Sets this graphics context's font to the specified font.

abstract void setPaintMode() 


47 Sets the paint mode of this graphics context to overwrite the destination with
this graphics context's current color.

abstract void setXORMode(Color c1) 


48 Sets the paint mode of this graphics context to alternate between this graphics
context's current color and the new specified color.

String toString() 
49
Returns a String object representing this Graphics object's value.

50 abstract void translate(int x, int y) 


Translates the origin of the graphics context to the point (x, y) in the current
AWT in
JAVA
7

coordinate system.

sample programs using methods of graphics class:

program-1:

import java.awt.*;
import java.awt.event.*;
class line extends Frame
{
line()
{
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.setColor(Color.blue); output:
g.drawRect(40,40,200,200);
g.drawOval(90,70,80,80);
g.drawOval(110,95,5,5);
g.drawOval(145,95,5,5);
g.drawLine(130,95,130,115);
g.drawArc(113,115,35,20,0,-180);
}
public static void main(String[] args)
{
line l1 = new line();
l1.setSize(400,400);
l1.setTitle("my frame");
l1.setVisible(true);
}
}

program-2:

import java.awt.*;
import java.awt.event.*;
class linee extends Frame
{
linee()
{
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
AWT in
JAVA
8

System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillRect(40,40,200,200);
g.setColor(Color.pink);
g.fillOval(90,70,80,80);
g.setColor(Color.cyan);
g.fillOval(110,95,5,5);
g.fillOval(145,95,5,5);
g.drawLine(130,95,130,115);
g.setColor(Color.green);
g.fillArc(113,115,35,20,0,-180);
}
public static void main(String[] args)
{
linee l1 = new linee();
l1.setSize(400,400);
l1.setTitle("my frame");
l1.setVisible(true);
}
}

output:

program-3:

import java.awt.*;
import java.awt.event.*;
class polygon1 extends Frame
{
polygon1()
{
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
AWT in
JAVA
9

System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillRoundRect(30,30,250,250,30,30);
g.setColor(Color.pink);
int x[]={40,200,40,100};
int y[]={40,40,200,200};
int num=4;
g.fillPolygon(x,y,num);
}
public static void main(String[] args)
{
polygon1 l1 = new polygon1();
l1.setSize(400,400);
l1.setTitle("my frame");
l1.setVisible(true);
}
}

output:

program-4:

import java.awt.*;
import java.awt.event.*;
class home extends Frame
{
home()
{
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
AWT in
JAVA
10

{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
int x[]={375,275,475};
int y[]={125,200,200};
int num=3;
this.setBackground(Color.gray);
g.setColor(Color.yellow);
g.fillRect(300,200,150,100);
g.setColor(Color.blue);
g.fillRect(350,210,50,60);
g.drawLine(350,280,400,280);
g.setColor(Color.darkGray);
g.fillPolygon(x,y,num);
g.setColor(Color.cyan);
g.fillOval(100,100,60,60);
g.setColor(Color.green);
g.drawString("happy home",275,350);
}
public static void main(String[] args)
{
home l1 = new home();
l1.setSize(400,400);
l1.setTitle("my frame");
l1.setVisible(true);
}
}
output:

Event Handling: Two Event Handling Mechanisms, The Delegation Event Model, Event Classes, Source
of Events, Event Listener Interfaces

What is an Event?

Change in the state of an object is known as event i.e. event describes the change in state of source. Events are
generated as result of user interaction with the graphical user interface components. For example, clicking on a
button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page
are the activities that causes an event to happen.
AWT in
JAVA
11

Types of Events

The events can be broadly classified into two categories:

 Foreground Events - Those events which require the direct interaction of user.They are generated as
consequences of a person interacting with the graphical components in Graphical User Interface. For example,
clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list,
scrolling the page etc.
 Background Events - Those events that require the interaction of end user are known as background
events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are the
example of background events.

What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This
mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the
Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle
the events.Let's have a brief introduction to this model.

The Delegation Event Model has the following key participants namely:

 Source - The source is an object on which event occurs. Source is responsible for providing information of
the occurred event to it's handler. Java provide as with classes for source object.
 Listener - It is also known as event handler.Listener is responsible for generating response to an event.
From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once
the event is received , the listener process the event an then returns.

The benefit of this approach is that the user interface logic is completely separated from the logic that generates
the event. The user interface element is able to delegate the processing of an event to the separate piece of code.
In this model ,Listener needs to be registered with the source object so that the listener can receive the event
notification. This is an efficient way of handling the event because the event notifications are sent only to those
listener that want to receive them.

Steps involved in event handling

 The User clicks the button and the event is generated.

 Now the object of concerned event class is created automatically and information about the source and
the event get populated with in same object.

 Event object is forwarded to the method of registered listener class.

 the method is now get executed and returns.

Event classes and Listener interfaces:

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener
AWT in
JAVA
12

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:

1. Implement the Listener interface and overrides its methods


2. Register the component with the Listener

For registering the component with the Listener, many classes provide the registration methods. For example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

EventHandling Codes:

We can put the event handling code into one of the following places:
1. Same class
2. Other class
3. Annonymous class : Anonymous classes enable you to make your code more concise. They enable
you to declare and instantiate a class at the same time. They are like local classes except that they do
not have a name. Use them if you need to use a local class only once.
AWT in
JAVA
13

AWT Controls: Control Fundamentals, Labels, Using Buttons, Applying Check Boxes, CheckboxGroup,
Choice Controls, Using Lists, Managing Scroll Bars, Using TextField, Using TextArea, Understanding
Layout Managers, Menu bars and Menus, Dialog Boxes, FileDialog, Exploring the controls, Menus ,and
Layout Managers

PROGRAM TO DEMONSTRATE CHECK BOX

import java.awt.*;
import java.awt.event.*;
class chekbox extends Frame implements ItemListener
{
String msg=" ";
Checkbox c1,c2,c3;
chekbox()
{
setLayout(new FlowLayout());
c1=new Checkbox("bold");
c2=new Checkbox("italic");
c3=new Checkbox("underline");

add(c1);
add(c2);
add(c3);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString("current state",10,100);
msg="bold"+c1.getState();
g.drawString(msg,10,120);
msg ="italic"+c2.getState();
g.drawString(msg,10,140);
msg ="underline"+c3.getState();
g.drawString(msg,10,160);
}

public static void main(String[] args)


{
chekbox b=new chekbox();
b.setSize(400,400);
b.setTitle("my frame");
AWT in
JAVA
14

b.setVisible(true);
}
}

Output :

javac checkbox.java
java checkbox

PROGRAM TO DEMONSTRATE CHOICE

import java.awt.*;
import java.awt.event.*;
class choice extends Frame implements ItemListener
{
String msg;
Choice ch;
AWT in
JAVA
15

choice()
{
setLayout(new FlowLayout());
ch=new Choice();

ch.add("telugu");
ch.add("english");
ch.add("hindi");
ch.add("Sanskrit");
ch.add("french");

add(ch);

ch.addItemListener(this);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString("selected language is :",10,100);
msg = ch.getSelectedItem();
g.drawString(msg,10,120);
}

public static void main(String[] args)


{
choice b=new choice();
b.setSize(400,400);
b.setTitle("my frame");
b.setVisible(true);
}
}

Output :

javac choice.java
java choice
AWT in
JAVA
16

PROGRAM TO DEMONSTRATE RADIO BUTTON

import java.awt.*;
import java.awt.event.*;
class radiobutton extends Frame implements ItemListener
{
String msg=" ";
CheckboxGroup cbg;
Checkbox y,n;
radiobutton()
{
setLayout(new FlowLayout());
cbg = new CheckboxGroup();

y=new Checkbox("yes",cbg,true);
n=new Checkbox("no",cbg,false);

add(y);
add(n);

y.addItemListener(this);
n.addItemListener(this);
AWT in
JAVA
17

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg = "current selection : ";
msg+=cbg.getSelectedCheckbox().getLabel();
g.drawString(msg,10,100);
}

public static void main(String[] args)


{
radiobutton b=new radiobutton();
b.setSize(400,400);
b.setTitle("my frame");
b.setVisible(true);
}
}

Output :

javac radiobutton.java
java radiobutton
AWT in
JAVA
18

PROGRAM TO CREATE 2 LABELS AND 2 TEXT FIELDS FOR ENTERING NAME AND PASSWORD

import java.awt.*;
import java.awt.event.*;
class mytext extends Frame implements ActionListener
{
TextField name,pass;

mytext()
{
setLayout(new FlowLayout());
Label l1=new Label("NAME :",Label.LEFT);
Label l2=new Label("PASSWORD :", Label.LEFT);

name=new TextField(20);
pass=new TextField(20);

pass.setEchoChar('*');

Font f = new Font("Arial",Font.PLAIN,20);


name.setFont(f);

add(l1);
add(name);
add(l2);
add(pass);

name.addActionListener(this);
pass.addActionListener(this);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
AWT in
JAVA
19

}
});
}
public void actionPerformed(ActionEvent ae)
{
Graphics g= this.getGraphics();
g.drawString("NAME :"+name.getText(),20,200);
g.drawString("PASS WORD :"+pass.getText(),20,220);
}
public static void main(String[] args)
{
mytext b=new mytext();
b.setSize(400,400);
b.setTitle("my frame");
b.setVisible(true);
}
}

Output :

javac mytext.java
java mytext
AWT in
JAVA
20

PROGRAM TO DEMONSTRATE LIST CLASS

import java.awt.*;
import java.awt.event.*;
class list extends Frame implements ItemListener
{
int msg[];
List ch;
list()
{
setLayout(new FlowLayout());

ch=new List(4,true);

ch.add("telugu");
ch.add("english");
ch.add("hindi");
ch.add("Sanskrit");
ch.add("french");

add(ch);

ch.addItemListener(this);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
AWT in
JAVA
21

}
public void paint(Graphics g)
{
g.drawString("selected language is :",10,100);
msg = ch.getSelectedIndexes();
for(int i=9;i<msg.length;i++)
{
String item = ch.getItem(msg[i]);
g.drawString(item,10,120);
}
}

public static void main(String[] args)


{
list b=new list();
b.setSize(400,400);
b.setTitle("my frame");
b.setVisible(true);
}
}

Output :

javac list.java
java list

PROGRAM TO DEMONSTRATE SCROLL BAR

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

class scrollbar extends Frame implements AdjustmentListener


{
String msg=" ";
Scrollbar ch;
scrollbar()
{
AWT in
JAVA
22

setLayout(null);
ch=new Scrollbar(Scrollbar.HORIZONTAL,0,50,0,600);
ch.setBounds(50,250,200,30);

add(ch);

ch.addAdjustmentListener(this);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void adjustmentValueChanged(AdjustmentEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString("scrollbar position :",20,150);
msg += ch.getValue();
g.drawString(msg,20,180);
msg=" ";
}

public static void main(String[] args)


{
scrollbar b=new scrollbar();
b.setSize(400,400);
b.setTitle("my frame");
b.setVisible(true);
}
}

Output :

javac scrollbar.java
java scrollbar
AWT in
JAVA
23

PROGRAM TO DEMONSTRATE KEY LISTENER

import java.awt.*;
import java.awt.event.*;
class keys extends Frame implements KeyListener
{
TextArea ta;
String msg=" ";
keys()
{
setLayout(new FlowLayout());
ta=new TextArea(5,25);
Font f= new Font("Arial",Font.BOLD,25);
ta.setFont(f);
ta.setForeground(Color.pink);
add(ta);
ta.addKeyListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
AWT in
JAVA
24

});
}

public void keyPressed(KeyEvent ke)


{
int keycode = ke.getKeyCode();
msg +="\nkey code: "+keycode;
String keyname = ke.getKeyText(keycode);
msg += "\nkey pressed: "+keyname;
ta.setText(msg);
msg=" ";
}
public void keyTyped(KeyEvent ke)
{}
public void keyReleased(KeyEvent ke)
{
int keycode = ke.getKeyCode();
msg +="\nkey code: "+keycode;
String keyname = ke.getKeyText(keycode);
msg += "\nkey released: "+keyname;
ta.setText(msg);
msg=" ";
}

public static void main(String[] args)


{
keys b=new keys();
b.setSize(400,400);
b.setTitle("my frame");
b.setVisible(true);
}
}

Output :

javac keys.java
java keys
AWT in
JAVA
25

PROGRAM TO DEMONSTRATE MOUSE LISTENER

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

public class mouse extends Frame implements MouseListener,MouseMotionListener


{

String msg="";
mouse()
{

this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

addMouseListener(this);
addMouseMotionListener(this);
setSize(400,400);
setVisible(true);
}
public void mouseEntered(MouseEvent m)
{
msg="Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent m)
{
msg="Mouse Exited";
repaint();
}
public void mousePressed(MouseEvent m)
{
msg="Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent m)
{
msg="Mouse Released";
repaint();
}
public void mouseMoved(MouseEvent m)
{
msg="Mouse Moved";
repaint();
}
public void mouseDragged(MouseEvent m)
{
AWT in
JAVA
26

msg="Mouse Dragged";
repaint();
}
public void mouseClicked(MouseEvent m)
{
msg="Mouse Clicked";
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg,100,120);
}
public static void main(String x[])
{
mouse m=new mouse();
}
}

Output : javac mouse.java java mouse

PROGRAM TO DEMONSTRATE THE WORKING WITH SEVERAL FRAMES

import java.awt.*;
import java.awt.event.*;
class frame1 extends Frame implements ActionListener
{
Button b1,b2;
frame1()
{
setLayout(null);
b1 = new Button("next");
b2 = new Button("close");
AWT in
JAVA
27

b1.setBounds(100,100,70,40);
b2.setBounds(100,160,70,40);

add(b1);
add(b2);

b1.addActionListener(this);
b2.addActionListener(this);

}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
frame2 f2 = new frame2();
f2.setTitle("second frame");
f2.setSize(400,400);
f2.setVisible(true);
}
else
System.exit(0);
}
public static void main(String[] args)
{
frame1 b=new frame1();
b.setSize(400,400);
b.setTitle("first frame");
b.setVisible(true);
} }

import java.awt.*;
import java.awt.event.*;
class frame2 extends Frame implements ActionListener
{
Button b3;
frame2()
{
setLayout(null);
b3 = new Button("back");
b3.setBounds(100,100,70,40);
add(b3);
b3.addActionListener(this);

}
public void actionPerformed(ActionEvent ae)
{
this.dispose();
}

Output :
AWT in
JAVA
28

javac frame2.java
javac frame1.java
java frame1

Layout Manager
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 controls is done automatically by
the 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.

 Oftenly the width and height information of a component is not given when we need to arrange them.

Java provide us with various layout manager 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.

The layout manager is associated with every Container object. Each layout manager is an object of the class that
implements the LayoutManager interface.

AWT Layout Manager Classes:

Following is the list of commonly used controls while designed GUI using AWT.

Sr.
LayoutManager & Description
No.

Border Layout
1 The borderlayout arranges the components to fit in the five regions: east,
west, north, south and center.
AWT in
JAVA
29

Card Layout
2 The CardLayout object treats each component in the container as a card. Only
one card is visible at a time.

Flow Layout
3 The FlowLayout is the default layout.It layouts the components in a directional
flow.

Grid Layout
4
The GridLayout manages the components in form of a rectangular grid.

GridBag Layout
This is the most flexible layout manager class.The object of GridBagLayout
5
aligns the component vertically,horizontally or along their baseline without
requiring the components of same size.

Example of BorderLayout class:

import java.awt.*;  
import javax.swing.*;  
  
public class Border {  
JFrame f;  
Border(){  
    f=new JFrame();  
      
    JButton b1=new JButton("NORTH");;  
    JButton b2=new JButton("SOUTH");;  
    JButton b3=new JButton("EAST");;  
    JButton b4=new JButton("WEST");;  
    JButton b5=new JButton("CENTER");;  
      
    f.add(b1,BorderLayout.NORTH);  
    f.add(b2,BorderLayout.SOUTH);  
    f.add(b3,BorderLayout.EAST);  
    f.add(b4,BorderLayout.WEST);  
    f.add(b5,BorderLayout.CENTER);  
AWT in
JAVA
30

      
    f.setSize(300,300);  
    f.setVisible(true);  
}  
public static void main(String[] args) {  
    new Border();  
}  
}  

Example of GridLayout class:

import java.awt.*;  
import javax.swing.*;  
  
public class MyGridLayout{  
JFrame f;  
MyGridLayout(){  
    f=new JFrame();  
      
    JButton b1=new JButton("1");  
    JButton b2=new JButton("2");  
    JButton b3=new JButton("3");  
    JButton b4=new JButton("4");  
    JButton b5=new JButton("5");  
        JButton b6=new JButton("6");  
        JButton b7=new JButton("7");  
    JButton b8=new JButton("8");  
        JButton b9=new JButton("9");  
          
    f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);  
    f.add(b6);f.add(b7);f.add(b8);f.add(b9);  
  
    f.setLayout(new GridLayout(3,3));  
    //setting grid layout of 3 rows and 3 columns  
  
    f.setSize(300,300);  
    f.setVisible(true);  
}  
public static void main(String[] args) {  
    new MyGridLayout();  
}  
}  

Example of FlowLayout class:


AWT in
JAVA
31

import java.awt.*;  
import javax.swing.*;  
  
public class MyFlowLayout{  
JFrame f;  
MyFlowLayout(){  
    f=new JFrame();  
      
    JButton b1=new JButton("1");  
    JButton b2=new JButton("2");  
    JButton b3=new JButton("3");  
    JButton b4=new JButton("4");  
    JButton b5=new JButton("5");  
              
    f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);  
      
    f.setLayout(new FlowLayout(FlowLayout.RIGHT));  
    //setting flow layout of right alignment  
  
    f.setSize(300,300);  
    f.setVisible(true);  
}  
public static void main(String[] args) {  
    new MyFlowLayout();  
}  
}  

You might also like