Professional Documents
Culture Documents
Unit 4
Unit 4
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.
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.
Method Description
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.
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.
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
A Graphics object encapsulates all state information required for the basic rendering operations that Java supports.
State information includes the following properties.
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 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 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 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 fillArc(int x, int y, int width, int height, int startAngle, int
27 arcAngle)
Fills a circular or elliptical arc covering the specified rectangle.
Fills the polygon defined by the specified Polygon object with the graphics
context's current color.
void finalize()
33
Disposes of this graphics context once it is no longer referenced.
Rectangle getClipRect()
37
Deprecated. As of JDK version 1.1, replaced by getClipBounds().
FontMetrics getFontMetrics()
40
Gets the font metrics of the current font.
String toString()
49
Returns a String object representing this Graphics object's value.
coordinate system.
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
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.
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.
Now the object of concerned event class is created automatically and information about the source and
the event get populated with in same object.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
AWT in
JAVA
12
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
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
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);
}
b.setVisible(true);
}
}
Output :
javac checkbox.java
java checkbox
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);
}
Output :
javac choice.java
java choice
AWT in
JAVA
16
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);
}
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('*');
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
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);
}
}
Output :
javac list.java
java list
import java.awt.*;
import java.awt.event.*;
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=" ";
}
Output :
javac scrollbar.java
java scrollbar
AWT in
JAVA
23
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
});
}
Output :
javac keys.java
java keys
AWT in
JAVA
25
import java.awt.*;
import java.awt.event.*;
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();
}
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.
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.
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.
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();
}
}
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();
}
}
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();
}
}