0% found this document useful (0 votes)
149 views296 pages

Advanve Java Book

The document discusses applets in Java, including what applets are, the different types of applets, the applet lifecycle and methods, how to run applets, and examples of simple applets that display text, use colors, and get user input.

Uploaded by

bhuvnesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
149 views296 pages

Advanve Java Book

The document discusses applets in Java, including what applets are, the different types of applets, the applet lifecycle and methods, how to run applets, and examples of simple applets that display text, use colors, and get user input.

Uploaded by

bhuvnesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 296

Applet

Introduction: Applets are small java graphical programs that are used in internet
computing. They can be transported over the internet from one computer to another and
run using the Applet viewer or any web browser that supports java. An applet can
perform arithmetic calculation, display graphics, play sounds, accept user input, create
animation, and play interactive games.
Applets are mainly used to add multimedia effects on web page.
Types of Applets: Applets are of two types. Local Applets and Remote Applets.
Local Applet: The Applet that developed locally and stored in the local system is known
as local applet. When we want to embedded a local applet into a web page then it does
not need to use the internet and therefore the local system does not require the internet
connection.
Remote Applet: A remote applet is that which is developed by someone else and stored
on a remote computer. If our system is connected to the internet, we can download the
remote applet onto our system via internet and run it locally. In order to locate and load a
remote applet, we must know the applet’s address i.e URL on the web.

Difference between Applets and Applications: Applets are not full featured application
program. They are useful to perform small task. Since they are designed for use on the
internet, they impose some limitations and restrictions in their design.
1. Applet does not use the main ( ) method for executing the code. Applets when
loaded, automatically call certain methods of applet class to start and execute the
applet code.
2. Like stand alone application applet can not run independently. They run from
inside a web page using a special feature known as HTML tag.
3. Applets can’t read from or write to the files in the local computer.
4. Applets can’t communicate with other sever on the network.
5. Applets are restricted from using libraries from other languages such as C and C+
+.
All these restriction are due to security purpose.

The Applet Class: The Applet class is an extension of the super class Panel in the AWT
(Abstract Window Toolkit). The Panel class is a sub class of the Container class. The
Container class contains Components such as buttons, menus, scroll etc.
java.lang.Object

1
java.awt.Component

java.awt.Container

java.awt.Panel

java.applet.Applet

The java class hierarchies

Applet Skeleton: Applet has four distinct stages in their lifetime. Each of these stages
includes methods which are as follow:
a. Initialization state: Applet enters in this stage when it is first loaded. This is
achieved by calling init ( ) method. The init ( ) method is the first method that is
called when an applet is loaded. At this stage we may do the following if required.
1. Create objects needed by the applet.
2. Setup initial values.
3. Load images or fonts.
4. setup colors.
Public void init ()
{

-------------
}
b. Running state: Applet enters the running state when the system calls the start ( )
method of Applet Class. This occurs automatically after the applet is initialized.
Starting can also occur if applet is stopped state already. For example we can
leave the web page containing the applet temporarily to another page and return
back to the page. We can call it more than once.
Public void start ()
{
---------------
}
c. Idle or stopped state: An applet becomes idle when it is stopped from running.
Stopping occurs automatically when we leave the page containing the currently
running applet. We can also do so by calling the stop ( ) method. If we want a
thread to terminate then we can use stop method for that.
Public void stop ( )
{
----------------
}

2
d. Dead state: An applet is said to be dead when it is removed from memory. This
occurs automatically by invoking destroy ( ) method. This method performs any
memory cleanup or garbage collection. This needs to be done when an applet is
destroyed. The destroyed method is called automatically when you quit a browser.
Destroying stage occurs only once in the applet’s life cycle.
Public void destroy ()
{
----------------------
}

Display State: Applet move to the display state whenever it has to perform some
output operations on the screen. This happens immediately after the applet enters into
the running state. The paint ( ) method is called to accomplish this task. Almost every
applet has a paint method.
Public void paint (Graphics g)
{
-------------------------
}
(It is to be noted display state is not considered as a part of applet’s life cycle.)

Applet Tag: This tag supplies the name of the applet to be loaded and tells the
browser how much space the applet requires. The ellipsis in the tag <applet…>
indicates that it contains certain attributes that must specify. Applet tag contain
application name, width and height attributes of web page. In case of param
application it contains param name and value.
Example: <center><Applet code=hellojava.class width=400 height
=200></applet></center>
In this example HTML code tells the browser to load the compiled java applet
hellojava.class, which is in the same directory as the HTML file. And also specifies
the display area for the applet output as 400 pixels width and 200 pixels height. We
can make this display area appear in the center of the screen by using the Center tag.

Running the Applet: To run an applet we require one of the following tools.
1. java-enbabled web browser (such as Hotjava or Netscape)
2. java appletviewer.
If we use a java enabled web browser, we will be able to see the entire web page
containing the applet. But html file containing applet tag must be in the bin of the jdk.
If we use applet viewer tool, we will only see the applet output. Applet viewer is not a
full fledged web browser and therefore it ignores all of the HTML tags except the part
pertaining to the running of the applet. Applet viewer is the part of jdk.

Compilation : javac filename.java<-|


Run: appletviewer filename.java<-|

/***************A simple applet program*******************/


import java.awt.*;

3
import java.applet.*;
public class hellojava extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello java",50,50);
}
}
/* <applet><applet code=hellojava.class width=400 height=200></applet>*/

/*use of Background and foreground color*/


import java.awt.*;
import java.applet.*;
public class hellojava2 extends Applet
{
public void init()
{
setBackground(Color.yellow);
setForeground(Color.red);
}
public void paint(Graphics g)
{
g.drawString("Hello java",150,350);
}
}
/*<applet>
<applet code=hellojava2.class width=500 height=500>
</applet>*/

/***initialization termination (use of run, start, stope methods)****/


import java.applet.*;
import java.awt.*;
/*<applet code="myapplet" width=300 height=100></applet>*/
public class myapplet extends Applet
{
String msg;
public void init()
{
setBackground(Color.yellow);
setForeground(Color.red);
msg="init() method-->";
}

public void start()


{
msg=msg+"start() method-->";

4
}
public void stop()
{
msg=msg+" stop()-->";
}
public void paint(Graphics g)
{
msg=msg+"paint() method ";
g.drawString(msg,20,50);
}
}

Different color classes: Color.black, Color.blue, Color.cyan,


Color.yellow, Color.pink, Color.orange, Color.magenta,
Color.gray, Color.darkGray, Color.green, Color.lightGray,
Color.white, Color.red,

Status window: we can display information on the status window or status bar of the
browser or applet viewer window. To do This call showStatus() method.
/************status bar demo******/
import java.awt.*;
import java.applet.*;
public class statusbar extends Applet
{
public void paint(Graphics g)
{
showStatus("I am the status window ");
}
}
/*
<applet> <applet code=statusbar.class width=200 height=200>
</applet>*/

/*************display numeric values*******/


import java.awt.*;
import java.applet.*;
public class numvalue extends Applet
{
public void paint(Graphics g)
{
int value1=10;
int value2=20;
int sum=value1+value2;
String s=" sum : "+String.valueOf(sum);
g.drawString(s,100,100);
}

5
}
/*<applet><applet code="numvalue.class" width=400 height=400>
</applet>*/
/*****************getting input from user******************/
import java.awt.*;
import java.applet.*;
public class userin extends Applet
{
TextField t1,t2;
public void init()
{
t1=new TextField(8);
t2=new TextField(8);
add(t1);
add(t2);
t1.setText("");
t2.setText("");
}
public void paint(Graphics g)
{
int x=0,y=0,z=0;
String s1, s2, s;
g.drawString("input a number in each box ",10,50);
try
{
s1=t1.getText();
x=Integer.parseInt(s1);
s2=t2.getText();
y=Integer.parseInt(s2);
}
catch(Exception e){}
z=x+y;
s=String.valueOf(z);
g.drawString("The sum is : ",10,75);
g.drawString(s,100,75);
}

public boolean action (Event e, Object o)


{
repaint();
return true;
}
}
/*<applet><applet code=userin.class width=400 height=400></applet>*/

/****************passing parameter to an applet using param*********/

6
import java.awt.*;
import java.applet.*;
public class useparam extends Applet
{
String str;
public void init()
{
str=getParameter("message");
}
public void paint(Graphics g)
{
g.drawString(str,25,25);
}
}
/*
<applet>
<applet code=useparam.class width=200 height=2500>
<param name=message value="The message to be displayed">
</applet>*/

/*****passing parameters to an applet using Param Application***/


import java.awt.*;
import java.applet.*;
public class hellojavaparam extends Applet
{
String str;
public void init()
{
str=getParameter("string");
if(str==null)
str="java";
str="hello"+str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
/*<applet>
<applet code=hellojavaparam.class width=400 height=400>
<param name="string" value="Applet! ">
</applet>*/

/********Passing Parameters to Applets using param*********/

7
import java.awt.*;
import java.applet.*;

/*<applet code="paramdemo" width=300 height=300>


<param name=fontName value=Arial Black>
<param name=fontSize value=44>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>*/

public class paramdemo extends Applet


{
String fontName;
int fontSize;
float leading;
boolean active;

public void start()


{
String param;
fontName=getParameter("fontName");
if(fontName==null)
fontName="Not found";

param=getParameter("fontSize");
if(param!=null)
fontSize=Integer.parseInt(param);
else
fontSize=0;

param=getParameter("leading");
if(param!=null)
leading=Float.valueOf(param).floatValue();
else
leading=0;

param=getParameter("accountEnabled");
if(param!=null)
active=Boolean.valueOf(param).booleanValue();
}

public void paint(Graphics g)


{
g.drawString("Fontname : "+fontName,0,10);
g.drawString("Fontsize : "+fontSize,0,26);
g.drawString("Leading : "+leading,0,42);

8
g.drawString("Account Active : "+active,0,58);
}
}

/*bar chart application*/


import java.awt.*;
import java.applet.*;
public class barchart extends Applet
{
int n=0;
String label[];
int value[];

public void init()


{
try
{
n=Integer.parseInt(getParameter("columns"));
label=new String[n];
value =new int[n];

label[0]=getParameter("label1");
label[1]=getParameter("label2");
label[2]=getParameter("label3");
label[3]=getParameter("label4");

value[0]=Integer.parseInt(getParameter("c1"));
value[1]=Integer.parseInt(getParameter("c2"));
value[2]=Integer.parseInt(getParameter("c3"));
value[3]=Integer.parseInt(getParameter("c4"));
}
catch(NumberFormatException e){}
}

public void paint(Graphics g)


{
for(int i=0;i<n;i++)
{
g.setColor(Color.red);
g.drawString(label[i],20,i*50+30);
g.fillRect(50,i*50+10,value[i],40);
}
}
}
/*
<applet code=barchart.class width=300 height=250>

9
<param name="columns" value="4">

<param name="c1" value="110">


<param name="c2" value="150">
<param name="c3" value="100">
<param name="c4" value="170">

<param name="label1" value="91">


<param name="label2" value="92">
<param name="label3" value="93">
<param name="label4" value="94">
</applet>
*/

/*chekc board application*/


import java.awt.*;
import java.applet.*;
public class draw extends Applet
{
public void init()
{
setBackground(Color.red);
setForeground(Color.cyan);
}

public void paint(Graphics g)


{
int i=0,j=0;
while(true)
{
g.drawString("*",i,j);
i=i+10;
if(i==500)
{
j=j+10;
i=0;
}
}
}
}
/*<applet code=draw width=500 height=500></applet>*/

Designing a Web Page: A web page basically is made up of text and HTML tags that
can be interpreted by a web browser or an applet viewer. A web page is also known as
HTML document or HTML page. Web page is stored using a file extension .html. these
HTML files should be in the same directory where our applet files are. A web page is

10
marked by an opening <HTML> tag and a closing <HTML> tag and is divided into
mainly three sections.
1. Comment Section: This section contains comment about the web page which
tells us what is going on in the web page. A comment line begins with <! And
ends with >. Web browser will ignore the text enclosed between them. Comment
are optional and can be added anywhere in the web page.
2. Head Section: The head section is defined with a starting <HEAD> tag and a
closing </HEAD> tag. This section usually contains a title for the web page as
shown below:
<head><title>Welcome to Java Applets</title></head>
the text enclosed in title tag will be displayed on the title bar of the web browser
which will display this page. The head section is also optional. A slash (/) in the tag
signifies an end of the tag.
3. Body Section: This section contains the entire information about the web page
and its behaviour. We can set many options to indicate how our page must appear
on the screen like colour, location, sound etc.

Syntext:
<HTML>

<!
………………. Comment Section
………………..
>

<HEAD>
Title Tag
Head Section
</HEAD>

<Body>
Applet Tag Body Section
</Body>

</HTML>

A web page structure

A simple web page by HTML


<html>
<! This page includes a welcome title in the title bar and also
display a welcome message. Then it specifies the applet to be
loaded and execute.>

11
<head><title>Welcome to java Applets</title> </head>

<body> <center> <h1>Welcome to the world of Applets</h1></center><br>


<center>
<h5>This My Simple Web Page Demotsation created by html</h5>
</center>
</body>
</html>
A simple web page of HTML which bind java applet program in it. (It necessary
that html file and the applet file must be in the java bin directory.)
Example 1:
a.
import java.awt.*;
import java.applet.*;
public class hellojava extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello java",50,50);
}
}
/* <applet><applet code=hellojava.class width=400 height=200></applet>*/

b.
<html>
<! This page includes a welcome title in the title bar and also
display a welcome message. Then it specifies the applet to be
loaded and execute.>

<head><title>Welcome to java Applets</title> </head>

<body> <center> <h1>Welcome to the world of Applets</h1></center><br>


<center>
<applet code=hellojava.class width=400 height=200> </applet>
</center>
</body>
</html>

Example 2:
a.
import java.applet.*;
import java.awt.*;
/*<applet code="myapplet" width=300 height=100></applet>*/
public class myapplet extends Applet
{
String msg;

12
public void init()
{
setBackground(Color.yellow);
setForeground(Color.red);
msg="init() method-->";
}

public void start()


{
msg=msg+"start() method-->";
}

public void paint(Graphics g)


{
msg=msg+"paint() method ";
g.drawString(msg,20,50);
}
}

b.
<html>
<! This program is binding myapplet program in html file>
<head>
<title> Welcome to Java Applet </title>
</head>
<body>
<center>
<h1> Welcome to java applet</h1>
</center>
<center>
<applet code=myapplet.class width=400 height=100>
</applet>
</center>
</body>
</html>

/*************param and html page*********/


a.
import java.awt.*;
import java.applet.*;
public class useparam extends Applet
{
String str;
public void init()
{
str=getParameter("message");

13
}
public void paint(Graphics g)
{
g.drawString(str,25,25);
}
}
/*<applet>
<applet code=useparam.class width=200 height=2500>
<param name=message value="The message to be displayed"></applet>*/

b.
<html>
<!This program will show param applet>
<head>
<title>Applet program with param</title>
</head>
<body>
<center><h1>It is Applet program with param </h1></center>
<center>
<applet>
<applet code=useparam.class width=200 height=200>
<param name=message value="message to display">
</applet>
</center>
</body>
</html>

Applect Context and showDocument(): The AppletContext interface contains methods


to access an applet’s environment, such as changing the URL displayed by the browser. It
contains methods that are useful for manipulating an applet’s environment. These
methods allow the applet to exchange information with the web browser for updating
web pages and for communicating applet status to the browser. The applet class has
method getApplectContent ( ) , which allows the applet to obtain information about its
environment which can be either the appletviewer or the web browser. The
showDocument ( ) method can be used to send a new URL to the browser.
Syntext : void showDocument(new URL(url));

NOTE: When we run this page in internet explorer this will display myapplet application
that is present in the bin of jdk.
a.
/*****using show document method****/
import java.awt.*;
import java.applet.*;
import java.net.URL;
/*<applet code=geturl width=300 height=300></applet>*/
public class geturl extends Applet

14
{
public void start()
{
AppletContext ac=getAppletContext();
try
{
URL obj=getCodeBase();
System.out.println(new URL(obj+"myapplet.html"));
ac.showDocument(new URL(obj+"myapplet.html"));
}
catch(Exception e)
{
showStatus("URL not found");
} }}
b. this program will display myapplet program on running it in internet explorer but will
not display any thing in the appleviewr.
<html>
<body>
<applet>
<applet code=geturl.class width=200 height=200>
</applet>
</body>
</html>

AppletStub and AudioClip Interface: AppletStup is an interface that contains methods


used to write an applet viewer like appletviewer provided by java. Because these methods
are used for interpreting applets so they are not used by applet programmer in creating
applets.
AudioClip interface contains methods for manipulating audio from within your applets.
Methods of AudiClip are as follow:
1. getAudioClip()
AudioClip getAudioClip (URL obj)
Returns an AudioClip object that encapsulates the audio clip found at the location
specified by obj.
2. play()
void play (URL obj)
used to play an audio file until the end of the file.
3. Loop()
Void loop ()
Used to play an audio file until the end, and repeat.
4. Stop()
Void stop ()
Used to playing the clip.

15
getDocumentBase() and getCodeBase(): The getDocumentBase method will return the
path of the file in which you are working right now. And getCodeBase method will also
return the path of the file but along with file name and extension.
/**This program will return the address of current file and document**/
import java.awt.*;
import java.applet.*;
import java.net.*;
/*<applet code="bases" width=300 height=200></applet>*/
public class bases extends Applet
{
public void paint(Graphics g)
{
String msg;
URL obj=getCodeBase();
msg="Code Base :"+obj.toString();
g.drawString(msg,10,20);

obj=getDocumentBase();
msg="Document Base : "+obj.toString();
g.drawString(msg,10,40);
}
}
Output: Code Base File: /c:/jdk16~1.0/bin/ (Folder address)
Code Base File: /c:/jdk16~1.0/bin/bases.java (File address)

/* A simple banner applet.*/


import java.awt.*;
import java.applet.*;
/*<applet code="SimpleBanner" width=600 height=150></applet>*/
public class SimpleBanner extends Applet implements Runnable
{
String msg = " A Simple Moving Banner.";
Thread t = null;
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
t=new Thread(this);
t.start();

16
}

public void run()


{
char ch;
for( ; ; )
{
try
{
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1, msg.length());
msg += ch;
} catch(InterruptedException e) {}
}
}
public void paint(Graphics g)
{
Font f=new Font("Times New Roman",Font.BOLD,40);
g.setFont(f);
g.drawString(msg, 50, 30);
}
}

/**********************A simple form in Applet**************/


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

/*<applet code = "application.class" width=506 height=405></applet>*/

public class application extends Applet //implements ActionListener

17
{
TextField Name,Age,Salary,Bonus;
Label l1,l2,l3,l4;
TextArea t;
String s;
Button Submit, Close, Clear;

public void init()


{
setLayout(new FlowLayout(FlowLayout.LEFT,25,35));
setBackground(Color.cyan);
setForeground(Color.red);

l1 = new Label("Name : ");


l2 = new Label("Age : ");
l3 = new Label("Salary : ");
l4 = new Label("Bonus : ");

Name = new TextField(15);


Age = new TextField(15);
Salary = new TextField(15);
Bonus = new TextField(15);

add(l1);
add(Name);
add(l2);
add(Age);
add(l3);
add(Salary);
add(l4);
add(Bonus);

t=new TextArea();

18
add(t);

Submit=new Button("Submit");
add(Submit);
Clear=new Button("Clear");
add(Clear);
Close=new Button("Close");
add(Close);

Submit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
t.setText("Name : "+Name.getText()+"\n"+"Age : "+Age.getText()+"\n"+"Salary :
"+Salary.getText()+"\n"+"Bonus : "+Bonus.getText());
}
});

Close.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
stop();
}
});

Clear.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
Name.setText("");
Age.setText("");
Salary.setText("");

19
Bonus.setText("");
t.setText("");
}
});
}

public void paint(Graphics g)


{
Font f = new Font("Arial",Font.BOLD,25);
g.setFont(f);
g.setColor(Color.black);
g.drawString("EMPLOYEE",190,25);
g.drawString("OUTPUT",190,145);
}
}

Graphics
Introduction: Graphics is one of the most important features of java. We can write java
applets that draw lines, figures of different shapes, images and text in different fonts and
styles. We can incorporate different colors also. Every applet has its own area of screen
known as canvas, where it creates its display. The size of an applet’s space is decided by
the attributes of the <APPLET…> tag. A java applet draws graphics image inside its
space using the coordinate system. Java’s coordinate system has the origin (0, 0) in the
upper-left corner. Positive X values are to the right, and positive Y values are to the
bottom. The values of coordinates are in pixels.

The Graphics Class: The Graphics class includes methods for drawing many different
types of shapes, from simple lines to polygons to text in a variety of fonts. To draw a
shape we may call one of the methods available in the graphics class. These are listed
below:
clearRect() : Erases a rectangular area of the canvas.
copyArea() : Copies a rectangular area of the canvas to another area.

20
drawArc() : Draws a hollow arc.
drawLine() : Draws a straight line.
drawOval() : Draws a hollow oval.
drawPolygon(): Draws a hollow polygon.
drawRect() : Draws a hollow Rectangle.
drawRoundRect() : Draw a hollow rectangle with rounded corners.
drawString() : Displays a text string.
fillArc() : Draws a filled arc.
fillOval() : Draws a filled oval.
fillPolygon() : Draws a filled polygon.
fillRect() : Draws a filled rectangle.
fillRoundRect():Draws a filled rectangle with rounded corner.
getColor() : Retrieves the current drawing colour.
getFont() : Retrieves the currently used font.
getFontMetrics(): Retrieves information about the current font.
setColor() : set the drawing colour.
setFont() : Sets the Font.

All these drawing methods have arguments representing end points, corners, or starting
locations of a shape as values in the applet’s coordinate system.

Lines and Rectangles: Line is the simplest shape that we can draw with help of graphics.
The drawLine() method takes two pair of coordinates (x1,y1) and (x2,y2) as arguments
and draw a line between them.
Example: g.drawLine(10,10,50,50);
Here g is the Graphics object passed to the paint method. Here 10, 10 are the starting
point of line while 50, 50 are the end point of line in the canvas.
Similarly we can draw a rectangle using the drawRect() method. It takes four arguments.
The first two represents the x and y coordinates of the top left corner of the rectangle and
the remaining two represent the width and the height of the rectangle. The drawRect()
method will draw only a hollow rectangle, to draw a solid rectangle we should use
fillRect() method. We can draw rounded corner rectangle also using the method
drawRoundRect() and fillRoundRect().These method takes two extra arguments
representing the width and height of the angle of corners.

//*****Demonstration of Common Graphics Shapes and default


animation******//
import java.awt.*;
import java.applet.*;
public class animation extends Applet
{
public void paint(Graphics g)
{
Font f=new Font("Times New Roman",Font.BOLD,15);
setFont(f);
g.setColor(Color.red);

21
g.drawString("Tital : Different type shapes
Demotsation",200,35);
g.setColor(Color.green);
g.drawLine(0,50,800,50); //horizontal line
g.setColor(Color.red);
g.drawString("Horizontal Line",150,60);//horizontal line
text
g.setColor(Color.blue);
g.drawLine(50,0,50,800);//vertical line
g.setColor(Color.red);
g.drawString("Virtical Line",60,80); //text for virtical
line
g.setColor(Color.black);
g.fillRect(100,100,200,200);//fill squar
g.setColor(Color.white);
g.drawString("Fill Squar",150,150); //text within squar
g.setColor(Color.blue);
g.drawRect(350,100,200,200); //blank squar
g.setColor(Color.red);
g.drawString("Squar",400,150); //squar text("squar")
g.setColor(Color.red);
g.drawRoundRect(300,450,180,180,15,15);//Round squar
g.setColor(Color.black);
g.drawString("Round Rectangle",350,500); //text within round
rec
g.setColor(Color.orange);
g.fillRoundRect(100,500,150,150,15,15); //fill round squar
g.setColor(Color.magenta);
g.drawString("Fill Round Rectangle",115,550); //text of fill
round rect
g.setColor(Color.cyan);
g.fillOval(600,100,150,150); //fill circle
g.setColor(Color.red);
g.drawString("Fill Circle",630,130); //text in fill circle
g.setColor(Color.magenta);
g.drawOval(800,100,150,150); //blank circle
g.setColor(Color.red);
g.drawString("Circle",830,130);//text within circle
g.setColor(Color.yellow);
g.fillOval(600,400,150,200); //fill oval(egg shape)
g.setColor(Color.black);
g.drawString("Fill Oval(Egg Shape)",630,450); //text within
oval
g.setColor(Color.red);
g.drawOval(800,400,200,150);// blanck oval
g.drawString("Blanck Oval",840,450);
g.setColor(Color.pink);

22
g.fillRect(450,350,150,60); //fill rectangle
g.setColor(Color.cyan);
g.drawString("Fill Rectangle",470,370); //text within
rectangle
g.setColor(Color.black);
g.drawRect(250,350,150,70); //blanck rectangle
g.setColor(Color.red);
g.drawString("Rectangle",270,370);//text in blanck rectangle
}
}
/* <applet code=animation.class width=1200 height=900>
</applet> */

/*Demotsation of Common Graphics Shapes */


import java.awt.*;
import java.applet.*;
public class squar extends Applet
{
public void paint(Graphics g)
{
showStatus("Common Shapes is displaying");
g.setColor(Color.red);
g.drawString("Tital : Different type shapes
Demotsation",200,35);
g.setColor(Color.green);
g.drawLine(0,50,800,50); //horizontal line
g.setColor(Color.red);
g.drawString("Horizontal Line",150,60);//horizontal line
text
g.setColor(Color.blue);
g.drawLine(50,0,50,800);//vertical line
g.setColor(Color.red);
g.drawString("Virtical Line",60,80); //text for virtical
line
g.setColor(Color.black);
g.fillRect(100,100,200,200);//fill squar
g.setColor(Color.white);
g.drawString("Fill Squar",150,150); //text within squar
g.setColor(Color.blue);
g.drawRect(350,100,200,200); //blank squar
g.setColor(Color.red);
g.drawString("Squar",400,150); //squar text("squar")
g.setColor(Color.red);
g.drawRoundRect(300,450,180,180,15,15);//Round squar
g.setColor(Color.black);
g.drawString("Round Rectangle",350,500); //text within round
rec

23
g.setColor(Color.orange);
g.fillRoundRect(100,500,150,150,15,15); //fill round squar
g.setColor(Color.magenta);
g.drawString("Fill Round Rectangle",115,550); //text of fill
round rect
g.setColor(Color.cyan);
g.fillOval(600,100,150,150); //fill circle
g.setColor(Color.red);
g.drawString("Fill Circle",630,130); //text in fill circle
g.setColor(Color.magenta);
g.drawOval(800,100,150,150); //blank circle
g.setColor(Color.red);
g.drawString("Circle",830,130);//text within circle
g.setColor(Color.yellow);
g.fillOval(600,400,150,200); //fill oval(egg shape)
g.setColor(Color.black);
g.drawString("Fill Oval(Egg Shape)",630,450); //text within
oval
g.setColor(Color.red);
g.drawOval(800,400,200,150);// blanck oval
g.drawString("Blanck Oval",840,450);
g.setColor(Color.pink);
g.fillRect(450,350,150,60); //fill rectangle
g.setColor(Color.cyan);
g.drawString("Fill Rectangle",470,370); //text within
rectangle
g.setColor(Color.black);
g.drawRect(250,350,150,70); //blanck rectangle
g.setColor(Color.red);
g.drawString("Rectangle",270,370);//text in blanck rectangle
}
}
/* <applet code=squar.class width=1200 height=900>
</applet> */

Drawing Arcs: An arc is a part of an oval. In fact we can think of an oval as a series of
arcs that are connected together in an orderly manner. The drawArc() method designed to
draw arcs. it takes six arguments. The first four are the same as the argument for
drawOval() method and the last two represent the starting angle of the arc and the number
of degrees around the arc. While drawing an arc java consider 3 O’clock as zero degree
position and degree increase in anti clockwise direction. To draw an arc from 12.00 to
6.00 O’clock position, the starting angle would be 90, and the sweep angle would be 180.
We can also draw an arc in backward direction by specifying the sweep angle as
negative. We can draw a fill arc by fillArc() method.
(Note: in all these method first argument is the horizontal position second is vertical
position, next two arguments are the length and width of arc, second last is the starting
point of angle, last argument is the size of angle.)

24
90

180

180 0

270
/*different shape of graphics*/
import java.awt.*;
import java.applet.*;
public class arcs extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.red);
g.setColor(Color.yellow);
g.fillOval(10,10,100,100);

/*drawing a circle by using four arcs*/


/*10,120 starting point
100,100 size of arc
0 is starting angle
90 is the arc angle*/

g.fillArc(10,120,100,100,0,90);
g.fillArc(0,120,100,100,90,90);
g.fillArc(0,130,100,100,180,90);
g.fillArc(10,130,100,100,270,90);

/*drawing circle by revers arc*/


g.fillArc(270,10,100,100,-90,-180);
g.fillArc(280,10,100,100,90,-180);

g.fillArc(270,120,100,100,0,180);
g.fillArc(270,130,100,100,0,-180);

g.fillArc(150,10,100,100,0,-270);
g.fillArc(150,130,100,100,0,270);

g.fillArc(150,250,100,100,180,270);

25
g.fillArc(270,260,100,100,270,270);
g.fillArc(10,260,100,100,0,360);
}
}
/*<applet code=arcs.class width=500 height=500></applet>*/

Drawing Polygons: Polygons are shape with many sides. A polygon may be considered
as a set of lines connected together. The end of the first line is the beginning of second
line, the end of second line is the beginning of third line and so on. We can draw a
polygon by drawLine method. This polygon can be draw by the help of drawPolygon()
method. Polygon method contain three arguments. First is X coordinates, second Y
coordinates and last is the number of total points.

/*************polygon example******/
import java.awt.*;
import java.applet.*;
public class polygon extends Applet
{
public void paint(Graphics g)
{
g.drawLine(10,10,100,10);
g.drawLine(100,10,100,100);
g.drawLine(100,100,10,10);
}
}
/*<applet code=polygon width=500 height=500></applet>*/

Output: (10, 10) (100, 10)

(100, 100)

/*************polygon by graphics class method drawPolygon(x,y,z)******/


import java.awt.*;
import java.applet.*;
public class polygons extends Applet
{
public void paint(Graphics g)
{
int x[]={10,100,100,10};
int y[]={10,10,100,10};
int length=x.length;

26
g.drawPolygon(x,y,length);}}
/*<applet code=polygons width=500 height=500></applet>*/

/********fill polygon*********************/
import java.awt.*;
import java.applet.*;
public class fillpolygon extends Applet
{
public void paint(Graphics g)
{
int x[]={10,100,100,10};
int y[]={10,10,100,10};
int length=x.length;
g.fillPolygon(x,y,length);}}
/*<applet code=fillpolygon width=500 height=500></applet>*/

Output: (10, 10) (100, 10)

(100, 100)
/*we can draw polygon by polygon class, with the help of it method addPoint() ***/
Example:
import java.applet.*;
import java.awt.*;
public class polygon2 extends Applet
{
public void paint(Graphics g)
{
Polygon poly=new Polygon();
poly.addPoint(20,20);
poly.addPoint(120,120);
poly.addPoint(220,20);
poly.addPoint(20,20);
g.drawPolygon(poly);}}
/*<applet code=polygon2.class width=500 height=500></applet>*/

Output: (20, 20) (220, 20)

(12, 120)
Line Graphs:
/***********Line graph**********/

27
import java.awt.*;
import java.applet.*;
public class graph extends Applet
{
public void paint(Graphics g)
{
int x[]={100,70,70,100,200,230,230,200,100};
int y[]={100,200,300,400,500,400,300,200,100};
int n=x.length;
g.drawPolygon(x,y,n);
}
}
/*<applet code=graph.class width=500 height=500></applet>*/
Output:

Using Control Loops in Applets: we can use all control structure in an applet.
Example: /***********applying loop control structure to applet*/
import java.awt.*;
import java.applet.*;
public class appletloop extends Applet
{
public void paint(Graphics g)
{
for(int i=0;i<=4;i++)
{
if(i%2==0)
g.drawOval(120,i*60+10,50,50);

28
else
g.fillOval(120,i*60+10,50,50);
}}}
/*<applet code=appletloop.class width=500 height=500></applet>*/
Output:

Drawing Bar Charts: /****************Bar chart*/


import java.awt.*;
import java.applet.*;
public class chart extends Applet
{
int n=0;
String label[];
int value[];

public void init()


{
try
{
n=Integer.parseInt(getParameter("colomns"));
label=new String[n];
value=new int[n];

label[0]=getParameter("label1");
label[1]=getParameter("label2");
label[2]=getParameter("label3");
label[3]=getParameter("label4");

value[0]=Integer.parseInt(getParameter("c1"));
value[1]=Integer.parseInt(getParameter("c2"));
value[2]=Integer.parseInt(getParameter("c3"));
value[3]=Integer.parseInt(getParameter("c4"));
}
catch(Exception e){}
}
public void paint (Graphics g)
{
for(int i=0;i<n;i++)
{
g.setColor(Color.red);
g.drawString(label[i],20,i*50+30);
g.fillRect(50,i*50+10,value[i],40);
}
}

29
}
/* <applet code=chart.class width=350 height=350>

<param name="colomns" value= "4">

<param name="label1" value="91">


<param name="label2" value="92">
<param name="label3" value="93">
<param name="label4" value="94">

<param name="c1" value="110">


<param name="c2" value="150">
<param name="c3" value="100">
<param name="c4" value="170">
</applet> */

/* Program to draw Umbrella by the of line,arc */


import java.awt.*;
import java.applet.*;
public class rect extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.cyan);
setForeground(Color.blue);
g.drawString("Umbrella",160,125);
g.setColor(Color.red);
g.fillArc(10,10,120,120,0,180);
g.setColor(Color.black);
g.drawLine(70,70,70,175);
g.drawArc(70,154,40,40,0,-180);
}
}
/* <applet code=rect.class width=200 height=200>
</applet> */

30
Working with color: /***A color demotsation applet**/
import java.awt.*;
import java.applet.*;
/*<applet code="color.class" width=500 height=600></applet>*/
public class color extends Applet
{
public void paint(Graphics g)
{
Color c1=new Color(255,100,100);
Color c2=new Color(100,255,100);
Color c3=new Color(100,100,255);

/*cross line*/
g.setColor(c1); /*red color
g.drawLine(0,0,100,100);
g.drawLine(0,100,100,0);

/*paralal line with green color*/


g.setColor(c2);
g.drawLine(40,25,250,180);
g.drawLine(75,90,400,400);

g.setColor(c3);
g.drawLine(20,150,400,40);
g.drawLine(5,290,80,19);

g.setColor(Color.red);
g.drawOval(10,10,50,50);
g.drawOval(70,90,140,100);

g.setColor(Color.blue);
g.drawOval(190,10,90,30);
g.drawOval(10,10,60,50);

31
g.setColor(Color.cyan);
g.fillRect(100,10,60,50);
g.drawRoundRect(190,10,60,50,15,15);
g.fillRoundRect(200,200,150,100,15,15);
}
}

Font Matrics
Class
Leading: Leading is the distance between lines. getleading() function returns the
distance between lines.
Total height of Font: on adding value returned by getAscent()+getDescent(), we can get
total height of font.
Baseline: The line that the bottoms of characters are aligned to.
Ascent: The distance from the baseline to the top of a character.
Descent: The distance from the baseline to the bottom of a character.

Dimension class of awt: This class returns the size of appletviewer’s page or web page
on which our applet is displaying, i.e. Dimension class will return the size of web page in
width and height format. It will change as we will do any change in the web page size.

/*use of Dimension class*/


import java.applet.*;
import java.awt.*;
/*<applet code=dimension width=200 height=200></applet>*/
public class dimension extends Applet
{
Font f=new Font("SansSerif", Font.BOLD, 25);

public void paint(Graphics g)


{
Dimension d=this.getSize();
g.setColor(Color.black);
g.setFont(f);
g.drawString(String.valueOf(d),50,50);

32
}
}
(Note: here this key word stand for web page on which output is displaying, Black is the
color of font.
Output: java.awt.Dimension[width=258, height=300]

Use of stringWidth function of FontMatrics class: This function returns the width,
height, leading, ascend ,decent of matrix in pixels.
All these properties are different with different font type
Example: use of font matrix class
import java.applet.*;
import java.awt.*;
//<applet code=stringmatrix width=500 height=200></applet>
public class stringmatrix extends Applet
{
Font f=new Font("SansSerif",Font.PLAIN,30);

public void paint(Graphics g)


{
g.setFont(f);
String str="This is centered string";
FontMetrics fm=g.getFontMetrics();
int x=fm.stringWidth(str);
int y=fm.getHeight();
int z=fm.getAscent();
int d=fm.getDescent();
int l=fm.getLeading();
g.drawString("String width in pixels :"+String.valueOf(x),25,25);
g.drawString("String height in pixels :"+String.valueOf(y),25,50);
g.drawString("String Ascent in pixels :"+String.valueOf(z),25,75);
g.drawString("String Descent in pixels :"+String.valueOf(d),25,100);
g.drawString("String Leading in pixels :"+String.valueOf(l),25,125);
}
}

/*********Centered Text***************/
import java.applet.*;
import java.awt.*;
//<applet code=centeredtext width=200 height=200></applet>
public class centeredtext extends Applet
{
Font f=new Font("SansSerif", Font.BOLD,18);

public void paint(Graphics g)


{
Dimension d=this.getSize();

33
g.setColor(Color.red);
g.fillRect(0,0,d.width,d.height);
g.setColor(Color.black);
g.setFont(f);
drawCenteredString("This is centered
string",d.width,d.height,g);
}

public void drawCenteredString(String s, int w, int h,


Graphics g)
{
FontMetrics fm=g.getFontMetrics();
int x=(w-fm.stringWidth(s))/2;
//int y=(h-(fm.getAscent()+fm.getDescent()))/2;
int y=(h-fm.getLeading())/2;
g.drawString(s,x,y);
}
}

/*************Umrella by Laxmi*************/
import java.awt.*;
import java.applet.*;

public class umbrella extends Applet


{

public void paint(Graphics g)


{
setBackground(Color.cyan);
g.setColor(Color.blue);
g.fillArc(240,50,500,500,0,180);
g.setColor(Color.cyan);
g.fillArc(245,290,100,20,0,180);
g.fillArc(351,290,100,20,0,180);
g.fillArc(457,290,100,20,0,180);
g.fillArc(562,290,100,20,0,180);
g.fillArc(666,290,69,20,0,180);
g.setColor(Color.red);
g.fillRect(490,291,18,240);
g.fillArc(434,476,75,110,0,-180);
g.setColor(Color.cyan);
g.fillArc(451,496,40,70,0,-180);
g.setColor(Color.red);
g.fillArc(434,525,18,18,0,180);

34
g.fillArc(490,38,18,30,0,180);

}
}
/*
<applet code = "umbrella.class" width=1000 height=1000></applet>
*/

/*Applet with font matrix */


//<applet code=Fonts width=500 height=500></applet>

import java.awt.*;
import java.applet.*;
public class Fonts extends Applet
{
public void paint(Graphics g)
{
String FontList[];
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
FontList=ge.getAvailableFontFamilyNames();
for(int i=0;i<FontList.length;i++)
g.drawString(FontList[i],10,i*15);
}
}

Events
Events: An Event is an object that describes a state change in a source. It can be
generated by interaction of a person with the elements in a graphical user interface. Some
of the activities that cause events to be generated are pressing a button, entering a
character by keyboard, selecting an item in a list, and clicking the mouse. Some event
occurs without user interface, like an event may be generated when a timer expire, a
counter exceeds a value, a software or hardware failure etc.

35
Event Sources: A source is an object that generates an event. This occurs when internal
state of that object changes in some way. Sources may generate more than one type of
event. A source must register listeners in order for the listeners to receive notifications
about a specific type of event. Each type of event has its own registration method.

Example: public void addTypeListener(TypeListener obj)

Here type is the name of the event and obj is a reference to the event listener. For
example the method that register a keyboard event listener is called addKeyListener(),
and the method that registers a mouse motion listener is called
addMouseMotionListener(). When an event occurs all registered listeners are notified and
receive a copy of the event object. This is known as multicasting the event. In all cases
notifications are sent only to listeners that register to receive them.
Some sources may allow only one listener to register. The general form of such a method
is this:
Public void addTypeListener(TypeListener el)
Throws java.util.TooManyListenerException

Here type is the name of the event and el is a reference to the event listener. When such
an event occurs, the registered listener is notified. This is known as unicasting the event.
A source must also provide methods that allow a listener to unregister an interest in a
specific type of event. The general form of such a method is:

Public void removeTypeListener(TypeListener el);

Her type is the name of the event and el is a reference to the event listener. For example
to remove a keyboard listener, you would call removeKeyListener(). The methods that
add or remove listeners are provided by the source that generates events.

Event Listener: A listener is an object that is notified when an event occurs. It has two
major requirements. First, it must have been registered with one or more sources to
receive notification about specific types of events. Second, it must implement methods to
receive and process these notifications.
The method that receive and process events are
defined in a set of interfaces found in java.awt.event. For example, the
MouseMotionListener interface defines two methods to receive notifications when the
mouse is dragged or moved. Any object may receive and process one or both of these
events if it provides an implementation of this interface.

Event Classes: At the root of the java event class hierarchy is EventObject, which is in
java.util. It is the super class for all events. Its one constructor is this:
EventObject(Object obj)
Here, obj is the object that generates this event. EventObject contains two methods:
getSource() and toString(). The getSource() method returns the source of the event. Its
general for is shown here.

36
Object getSource()
The toString() returns the string equivalent of the event.
The class AWT Event, defined within the java.awt package, is a subclass of
EventObject. It is super class of all AWT-based events used by the delegation event
model. Its getID() , method can be used to determine the type of the event. The signature
of this method as follow:
int getID()

Enter event
public boolean action(Event e, Object ob)
{
repaint();
return true;
}

Example:
//<applet code=entereventdemo width=500 height=500></applet>
import java.awt.*;
import java.applet.*;
public class entereventdemo extends Applet
{
int x,y;
public void init()
{
x=x+10;
y=y+10;
}
public void paint(Graphics g)
{
g.drawString("Firing and envet",x,y);
}

public boolean action(Event e, Object obj)


{
repaint();
return true;
}
}

Handling Mouse Events: To handle mouse events, you must implement the
MouseListener and the MouseMostionListener interfaces.

37
Mouse Event
/***This program will display all mouse activities*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="MouseEvents" width=300 height=100></applet>*/
public class MouseEvents extends Applet implements MouseListener,
MouseMotionListener
{
String msg="";
int x=0,y=0;

public void init()


{
addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me)


{
x=0;
y=10;
msg="Mouse Clicked";
repaint();
}

public void mouseEntered(MouseEvent me)


{
x=0;
y=10;
msg="Mouse entered";
repaint();
}

public void mouseExited(MouseEvent me)


{
x=0;
y=10;
msg="Mouse exited";
repaint();
}

public void mousePressed(MouseEvent me)

38
{
x=me.getX();
y=me.getY();
msg="Down";
repaint();
}

public void mouseReleased(MouseEvent me)


{
x=me.getX();
y=me.getY();
msg="UP";
repaint();
}

public void mouseDragged(MouseEvent me)


{
x=me.getX();
y=me.getY();
msg="*";
showStatus("Dragging mouse at "+x+" , "+y);
repaint();
}

public void mouseMoved(MouseEvent me)


{
showStatus("Moving mouse at "+me.getX()+" , "+me.getY());
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}
/*Mouse Event (Event will fire on mouse click)*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
//<applet code="mevent.class" height=400 width=400></applet>
public class mevent extends Applet implements MouseListener
{
Label l1;
TextField t1,t2,t3;
public void init()
{
l1=new Label("Mushak");
t1=new TextField(10);

39
t2=new TextField(10);
t3=new TextField(10);
add(l1);
add(t1);
add(t2);
add(t3);
l1.addMouseListener(this);
}

public void mouseEntered(MouseEvent e)


{
t1.setText("Entered");
}
public void mousePressed(MouseEvent e)
{
t2.setText("Pressed");
}
public void mouseReleased(MouseEvent e)
{
t3.setText("Released");
}
public void mouseClicked(MouseEvent e)
{
t1.setBackground(Color.red);
t2.setBackground(Color.blue);
t3.setBackground(Color.green);
}
public void mouseExited(MouseEvent e)
{
t1.setBackground(Color.white);
t2.setBackground(Color.white);
t3.setBackground(Color.white);
t1.setText("");
t2.setText("");
t3.setText("");
}
}

Keyboard Events
/**This program will display three events: key down, key up, and key character*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="simplekey" width=300 height=100></applet>*/

40
public class simplekey extends Applet implements KeyListener
{
String msg="";
int x=10,y=20;
public void init()
{
addKeyListener(this);
requestFocus();
}

public void keyPressed(KeyEvent ke)


{
showStatus("Key Down");
}

public void keyReleased(KeyEvent ke)


{
showStatus("Key Up");
}

public void keyTyped(KeyEvent ke)


{
msg+=ke.getKeyChar();
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg,x,y);
}
}

/***********************key Event*****************/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
//<applet code="keyeve.class" height=400 width=400></applet>
public class keyeve extends Applet implements KeyListener,ActionListener
{
String msg="";
//Button b1;
Applet a1=new Applet();
public void init()
{

41
//b1=new Button("clear");
//add(b1);
//b1.addActionListener(this);

addKeyListener(this);
a1.requestFocus();
}
public void keyPressed(KeyEvent e)
{
showStatus("Key Down");
}
public void keyReleased(KeyEvent e)
{
showStatus("Key up");
}
public void keyTyped(KeyEvent e)
{
msg=msg+e.getKeyChar();
repaint();
}
public void actionPerformed(ActionEvent e1)
{
// msg="";
}
public void paint(Graphics g)
{
g.drawString(msg,10,20);
}
}

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

class KeyPress extends Frame


{
Label label;
TextField txtField;
public static void main(String[] args)
{
KeyPress k = new KeyPress();
}

public KeyPress()
{
super("Key Press Event Frame");
Panel panel = new Panel();

42
label = new Label();
txtField = new TextField(20);
txtField.addKeyListener(new MyKeyListener());
add(label, BorderLayout.NORTH);
panel.add(txtField, BorderLayout.CENTER);
add(panel, BorderLayout.CENTER);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
setSize(400,400);
setVisible(true);
}

public class MyKeyListener extends KeyAdapter


{
public void keyPressed(KeyEvent ke)
{
char i = ke.getKeyChar();
String str = Character.toString(i);
label.setText(str);
}
}
}

/****Special key Events***/


(applicable for all keys)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="keyevents" width=300 height=100></applet>*/
public class keyevents extends Applet implements KeyListener
{
String msg="";
int x=10,y=20;

public void init()


{
addKeyListener(this);
requestFocus();
}

43
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
int key=ke.getKeyCode();
switch(key)
{
case KeyEvent.VK_F1:
msg+="<F1>";
break;
case KeyEvent.VK_F2:
msg+="<F2>";
break;
case KeyEvent.VK_F3:
msg+="<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg+="<Page Down>";
break;
case KeyEvent.VK_PAGE_UP:
msg+="<Page Up>";
break;
case KeyEvent.VK_LEFT:
msg+="<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg+="<Right Arrow>";
break;
case KeyEvent.VK_UP:
msg+="<UP Arrow>";
break;
case KeyEvent.VK_DOWN:
msg+="<Down Arrow>";
break;
case KeyEvent.VK_HOME:
msg+="<Home key Pressed>";
break;
case KeyEvent.VK_END:
msg+="<End key Pressed>";
break;
case KeyEvent.VK_INSERT:
msg+="<Insert key Pressed>";
break;
case KeyEvent.VK_DELETE:
msg+="<Delete key Pressed>";
break;
case KeyEvent.VK_SHIFT:

44
msg+="<SHIFT>";
break;
case KeyEvent.VK_CONTROL:
msg+="<Control>";
break;
case KeyEvent.VK_SPACE:
msg+="<SPACE>";
break;
case KeyEvent.VK_ALT:
msg+="<ALT>";
break;

case KeyEvent.VK_BACK_SPACE:
msg+="<BACK_SPACE>";
break;
case KeyEvent.VK_TAB:
msg+="<TAB>";
break;

case KeyEvent.VK_CAPS_LOCK:
msg+="<cAPS LOCK>";
break;

case KeyEvent.VK_NUM_LOCK:
msg+="<NUM LOCK>";
break;
case KeyEvent.VK_ENTER:
msg+="<ENTER>";
break;
case KeyEvent.VK_ESCAPE:
msg+="<ESCAPE PRESS>";
break;
}
repaint();
}

public void keyReleased(KeyEvent ke)


{
showStatus("Key Up");
}

public void keyTyped(KeyEvent ke)


{
msg+=ke.getKeyChar();
repaint();
}

45
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}

Adapter Classes
An Adapter class provides an empty implementation of all the methods in an
event listener interface. Adapter classes are useful when you want to receive and process
only some of the events that are handled by a particular event listener interface. We can
define a new class to act as an event listener by extending one of the adapter classes and
implementing only those events in which you are interested.
/*****************use of Adapter Classes*****/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="adapterdemo" width=300 height=100></applet>*/
public class adapterdemo extends Applet
{
public void init()
{
addMouseListener(new mymouseadapter(this));
addMouseMotionListener(new mymousemotionadapter(this));
addKeyListener(new mykeyadapter(this));
addKeyListener(new mykeyadapter2(this));
}
}
class mymouseadapter extends MouseAdapter
{
adapterdemo adp;
public mymouseadapter(adapterdemo obj)
{
adp=obj;
}

public void mouseClicked(MouseEvent me)


{
adp.showStatus("Mouse Clicked");
}
}
class mymousemotionadapter extends MouseMotionAdapter
{

46
adapterdemo adp;
public mymousemotionadapter(adapterdemo obj)
{
adp=obj;
}

public void mouseDragged(MouseEvent me)


{
adp.showStatus("Mouse dragged");
}
}
class mykeyadapter extends KeyAdapter
{
adapterdemo adp;
public mykeyadapter(adapterdemo obj)
{
adp=obj;
}

public void keyPressed(KeyEvent ke)


{
adp.showStatus("Key Pressed");
}
}
class mykeyadapter2 extends KeyAdapter
{
adapterdemo adp;
public mykeyadapter2(adapterdemo obj)
{
adp=obj;
}

public void keyReleased(KeyEvent ke)


{
adp.showStatus("Key Released");
}
}

Inner Class
An inner class is a class defined within other class, or event within an expression.

Example: /********program without the use of inner class**********/


import java.applet.*;

47
import java.awt.event.*;
/*<applet code="mousepressed" width=200 height=100></applet>*/
public class mousepressed extends Applet
{
public void init()
{
addMouseListener(new mymouseadapter(this));
}
}
class mymouseadapter extends MouseAdapter
{
mousepressed obj;
public mymouseadapter(mousepressed m)
{
obj=m;
}

public void mousePressed(MouseEvent me)


{
obj.showStatus("Mouse Pressed ");
}
}
/******above program by the use of innner class****/
import java.applet.*;
import java.awt.event.*;
/*<applet code="innerclass" width=200 height=100></applet>*/
public class innerclass extends Applet
{
public void init()
{
addMouseListener(new mymouseadapter());
}

class mymouseadapter extends MouseAdapter


{
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
}
}
}
Anonymous Inner class: an anonymous inner class is one that is not assigned a name.
This example represents an anonymous class:

Example: /*Anonymous class, an alternative to inner class and adapter class or a


combine form of both classes*/

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

/*<applet code="anonymousclass" width=200 height=100></applet>*/

public class anonymousclass extends Applet


{
String str="";
public void init()
{
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
str="I am pressed";
repaint();
}
});

public void paint(Graphics g)


{
g.drawString(str,10,10);
}
}

AWT controls, Layout


Manager, and Menus
AWT-> Abstract Window Tool kit.

Controls-> Controls are the components that allow a user to interact with your
application in various ways-for example, Button, Label, Check box etc.

Layout Manager-> A layout Manager automatically positions components within a


container. Thus, the appearance of a window is determined by a combination of the
controls that it contains and the layout manager used to position them.

49
Menus-> A frame window can also include a standard style menu bar. Each entry in a
menu bar activates a drop down menu of options from which the user can choose. A
menu bar is always positioned at the top of a window.

Adding and Removing Controls: We can add a control to the window by add ( )
method. This method is defined by Container class. The simple form of add method is
like this:
Component add (Component obj)
Once a control has been added it will automatically be visible whenever its parent
window is displayed.
To remove a method from window remove ( ) method of Container
class is used. Its general form is like this:
Void remove (Component obj)

Labels: A label is an object of type Label, and it contains a string, which


it displays. Labels do not support any interaction with the user. Label defines the
following constructors.
Label ( )
Label (String str)
Label (String str, int i)

The first version creates a blank label. The second version creates a label that contains the
string specified by str. This string is left justified. The third version creates a label that
contains the string specified by str using the alignment specified by i. the value of I must
be one of these three contants: Label.LEFT, Label.RIGHT, or Label.CENTER. we can
set text in a label by using setText() method. We can obtain the current label by calling
getText().
Void setText(String str)
String getText()
We can set alignment of the string within label by calling setAlignment() to obtain the
current alignment , call getAlignment().
Void setAlignment(int i)
Where i is 0 for LEFT, 1 for CENTER, 2 for RIGHT
Int getAlignment()
This function will return an integer value either 0 or 1 or 2.

/*Label*/
//<applet code=labeldemo width=500 height=500></applet>
import java.awt.*;
import java.applet.*;
public class labeldemo extends Applet
{
Label l1,l2,l3,l4;

50
public void init()
{
l1=new Label("Enter Name ");
add(l1);

l2=new Label("Enter Age ",Label.CENTER);


add(l2);

l3=new Label("Enter Address : ",2);


add(l3);

l4=new Label();
add(l4);
}
}

/*Label with all functions*/


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
//<applet code=labelmethod width=500 height=500></applet>
public class labelmethod extends Applet
{
Label l1;
Button b;
String str,s;

public void init()


{
l1=new Label("Hello");
add(l1);
b=new Button("Ok");
add(b);

b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
str=l1.getText();
l1.setText("Java");
l1.setAlignment(2);
s=String.valueOf(l1.getAlignment());
repaint();
}
});
}

51
public void paint(Graphics g)
{
g.drawString("newly Set Text : "+str,150,150);
g.drawString("Alignment : "+s,200,200);
}
}

TextField: The TextField class implements a single line text entry


area, usually called an edit control, text fields allow the user to enter strings and to edit
the text using the arrow keys, cut and paste keys, and mouse selections. TextField is a
subclass of TextComponent. TextField defines the following constructors.
TextField()
TextField(int numchars)
TextFiled(String str)
TextField(String str, int numchars)

The first version creates a default text field.


The second form creates a text field that is numchars characters wide.
The third form initializes the text field with string contain in str.
The fourth form initializes a text field and sets its width.

To obtain the string in text field use getText() method and to set the text call setText()
method.

String getText();
Void setText(String str)

The user can select a portion of text in the text field. By the help of select() method we
can select a portion of the text in the text field. We can obtain currently selected portion
of text field by using getSelectedText() method. These methods are like this.

Void select(int startindex, int endindex)


String getSelectedText()

The getSelectedText() returns the selected text. The select() method selects the characters
beginning at startindex and ending at endindex-1.

You can control whether the contents of a text field may be modified by the user by
calling setEditable(). You can determine editability by calling isEditable(). These
methods are shown here.

Boolean isEditable()
Void setEditable(Boolean canedit)

52
isEditable() returns true if the text may be changed and false if not. In setEditable(), if
canedit is true, the text may be changed otherwise text cannot be altered.
We can disable the echoing of the characters as they are typed by calling setEchoChar().
This method specifies a single character that the TextField will display when characters
are entered. You can check a text Field to see if it is in this mode with the
echoCharIsSet() method. You can retrieve the eco character by calling the getEchoChar()
method.

Void setEchoChar(char ch)


Boolean echoCharIsSet()
Char getEchoChar()

Ch specifies the character to be echosed.

//TextField Demo
import java.awt.*;
import java.applet.*;

public class textfield extends Applet


{
TextField t1,t2,t3,t4;
String str,str1;

public void init()


{
t1=new TextField();
t2=new TextField(10); //10 pixel long box
t3=new TextField("Hello");
t4=new TextField("Hello",1); //1 pixel long box

add(t1);
add(t2);
add(t3);
add(t4);

//getting and setting text


t3.setText("hello java");
str=t3.getText();

//getting selected text


t3.select(0,4); //0 is starting index and 4 number of character to select
str1=t3.getSelectedText();
}

public void paint(Graphics g)


{

53
g.drawString("Text box3's value: "+str,100,100);
g.drawString("Selected text of text box3 is: "+str1,150,150);
}
}
/*<applet code=textfield width=500 height=500></applet>*/

/*Text Field functions*/


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

public class textf extends Applet


{
TextField f1,f2;
boolean b1,b2;

public void init()


{
f1=new TextField("Editable");
f1.setEditable(true);

f2=new TextField("Not Editable");


f2.setEditable(false);

add(f1);
add(f2);

b1=f1.isEditable();
b2=f2.isEditable();
}

public void paint(Graphics g)


{
g.drawString(Boolean.toString(b1),50,50); //Boolean.toString(b1) is to convert
the boolean value to string
g.drawString("Is editable="+b2,70,70);// " " quote is applied to convert boolean
value to string
}
}
/*<applet code=textf width=500 height=500></applet>*/

/*Text Field function*/


import java.awt.*;
import java.applet.*;
public class textfields extends Applet

54
{
TextField t1,t2,t3;
boolean b1,b2,b3;
char ch;

public void init()


{
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);

t1.setEditable(true);
t2.setEditable(false);

t3.setEchoChar('*');// * will display in text while typing

add(t1);
add(t2);
add(t3);

b1=t1.isEditable();
b2=t2.isEditable();

b3=t3.echoCharIsSet();
ch=t3.getEchoChar();
}

public void paint(Graphics g)


{
g.drawString("Text box one : "+String.valueOf(b1),100,120);
g.drawString("Text box Two : "+String.valueOf(b2),200,140);
g.drawString("Set Eco char : "+String.valueOf(b3),300,160);
g.drawString("Eco char is : "+String.valueOf(ch),400,180);
}
}
/*<applet code=textfields width=500 height=500></applet>*/

/**********Text Filed*********/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=textfield width=400 height=400></applet>*/
public class textfield extends Applet implements ActionListener
{
TextField name,pass;

55
public void init()
{
Label lblname=new Label("Name : ", Label.RIGHT);
Label lblpass=new Label("Password : ",Label.RIGHT);
name=new TextField(12);
pass=new TextField(10);
pass.setEchoChar('*');

add(lblname);
add(name);
add(lblpass);
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);
g.drawString("Echo char is : "+pass.getEchoChar(),6,140);
}
}

Text Area: The AWT includes a multiline editor called TextAreaa.


Following are the constructor of TextArea.

TextArea()
TextArea(int numlines, int numchars)
TextArea(String str)
TextArea(String str, int numlines, int numchars)
TextArea(String str, int numlines, int numchars, int sbars)

Here numlines specifies the height, in lines, of the text area, and numchars specifies its
width in characters. Initial text can be specified by str. Sbars is used to specify scroll
barsl. Sbars must be one of these values.

56
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY

TextArea is a subclass of TextComponent. So it supports the getText(), setText(),


getSelectedText(), select(), isEditable() and setEditable() methods.

TextArea adds the following methods.

Void append(String str)


Void insert(String str, int index)
Void replaceRange(String str, int startindex, int endindex)

The append() method appends the string, specified by str to the end of the current text.
Insert() method inserts the string passed in str at the specified index. To replace text, call
replaceRange(). It replaces the characters from startindex to endindex-1, with the
replacement text passed in str. TextArea only generates got-focus and lost-focus events.

/*Text Area constructors*/


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

public class textarea extends Applet


{
TextArea t1,t2,t3,t4,t5;

public void init()


{
t1=new TextArea();
t2=new TextArea(4,10);//4->lines, 10->characters in each line
t3=new TextArea("Hello java and C++");
t4=new TextArea("hello how are you",4,20);
//t5=newTextArea("Hello how are
you",4,20,SCROLLBARS_HORIZONTAL_ONLY);

add(t1);
add(t2);
add(t3);
add(t4);
//add(t5);
}
}
/*<applet code=textarea width=500 height=500></applet>*/

57
/*Text Area*/
import java.awt.*;
import java.applet.*;
public class textarea3 extends Applet
{
TextArea t1,t2,t3,t4,t5;
String s1,s2;
boolean b;
public void init()
{
t1=new TextArea();
t2=new TextArea(4,10);
t3=new TextArea("Hello java and C++");
t4=new TextArea("Hello how are you",4,20);
//t5=new TextArea("Hello how are
you",4,20,SCROLLBARS_HORIZONTAL_ONLY);

add(t1);
add(t2);
add(t3);
add(t4);
//add(t5);

s1=t3.getText();
t1.setText("Hello java and c++");
t4.select(6,9);
s2=t4.getSelectedText();

t2.setEditable(false);
t2.setText("Editing");
b=t2.isEditable();
}

public void paint(Graphics g)


{
g.drawString(s1,200,200);
g.drawString("Selected text : "+s2,300,300);
g.drawString(String.valueOf(b),400,400);
}
}
/*<applet code=textarea3 width=1000 height=1000></applet>*/

/***********Text Area Demo**********/


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

58
/*<applet code=textareademo width=600 height=600></applet>*/
public class textareademo extends Applet
{
public void init()
{
String val="There are two ways of constructing"+" a software design. \n"+" one way is to
make it so simple \n"+ "that there are obviously no deficiencies. \n"+" That there are no
obvious deficiencied. \n\n"+" -C.A.R. \n\n"+" there's an old story about the person
who wished \n";

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


add(text);
}
}

/* Programe to create a textarea which is uneditable */


import java.applet.*;
import java.awt.*;
public class textarea extends Applet
{
public void init()
{
TextArea ta=new TextArea(5,8);
Label l1=new Label("TEXTAREA,label.CENTRE");
ta.setText("This\nis the\nTst\n for text area ");
add(l1);
add(ta);
ta.setEditable(false);
}
}
/*<applet code="textarea.class" width=200 height=100>
</applet> */

Buttons: A button is a component that contain a label and that generates


an event when it is pressed. Button defines two constructors.
Button()
Button(String str)
The first version creates an empty button. The second creates a button that contains a
label.
After a button has been created, you can set its label by callilng setLabel(). You can
retrieve its label by calling getLabel(). Example
Void setLabel(String str)
String getLabel()

59
Each time a button is pressed, an action event is generated. This is sent to any listeners.
Each listener implements the ActionListener interface. That interface defines the
actionPerformed() method, which is called when event occurs. An ActionEvent object is
supplied as the argument to this method.

/*button demo*/
import java.awt.*;
import java.applet.*;
public class button extends Applet
{
Button b1,b2;
String s;
public void init()
{
b1=new Button();
b2=new Button("OK");

add(b1);
add(b2);

b1.setLabel("Cancel");
s=b1.getLabel();
}

public void paint(Graphics g)


{
g.drawString(s,100,100);
}
}
/*<applet code=button width=400 height=400></applet>*/

Example:/*************Button Demo****************************/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class ButtonDemo extends Applet implements ActionListener


{
String msg="";
Button yes,no,maybe;

public void init()


{
yes=new Button("Yes");
no=new Button("No");
maybe=new Button("Undecided");

60
add(yes);
add(no);
add(maybe);

yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("Yes"))
msg="You pressed Yes";
else if(str.equals("No"))
msg="You pressed No";
else
msg="You pressed Undecided";
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg,6,100);
}
}
/*<applet code="ButtonDemo" width=500 height=500></applet>*/
/***********Button list demo****/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class ButtonList extends Applet implements ActionListener
{
String msg="";
Button blist[]=new Button[3];
public void init()
{
Button yes=new Button("Yes");
Button no=new Button("No");
Button maybe=new Button("Undecided");
blist[0]=(Button)add(yes);
blist[1]=(Button)add(no);
blist[2]=(Button)add(maybe);
for(int i=0; i<3; i++)
blist[i].addActionListener(this);
}

61
public void actionPerformed(ActionEvent ae)
{
for(int i=0;i<3;i++)
{
if(ae.getSource()==blist[i])
msg="You Pressed "+blist[i].getLabel();
}
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,6,100);
}
}
/*<applet code=ButtonList width=600 height=600></applet>*/

/*Login form*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class loginform extends Applet
{
TextField t1,t2;
Label l1,l2;
Button b1,b2;

public void init()


{
setLayout(new GridLayout(3,3));
l1=new Label("Enter name : ");
add(l1);
t1=new TextField(10);
add(t1);
l2=new Label("Enter age : ");
add(l2);
t2=new TextField(10);
add(t2);
b1=new Button("Ok");
add(b1);
b2=new Button("Cancel");
add(b2);
}
}
/*<applet code=loginform width=200 height=200></applet>*/

62
Check boxes: A check box is a control that is used to turn an option
on or off. It consists of a small box that can either contain a check mark or not. There is a
label associated with each check box that describes what option the box represents. You
change the state of a check box by clicking on it. Checkbox support the following
constructors:
Checkbox()
Checkbox(String str)
Checkbox(String str, Boolean on)
Checkbox(String str, Boolean on, CheckboxGroup cbg)
Checkbox(String str, CheckboxGroup cbg, Boolean on)

To retrieve the current state of a check box, call getState(). To set its state call setState().
You can obtain the current label associated with a check box by calling getLabel(). To set
the label call setLabel(). These methods are as follow:

Boolean getState()
Void setState(Boolean on)
String getLabel()
Void setLabel(String str)

each time a check box is selected or deselected, an item event is generated. This is sent to
a listener. Each listener implements the ItemListener interface. That interface defines the
itemStateChanged() method. An ItemEvent object is supplied as the argument to this
method. It contain information about the event.

/**********check box*****/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=checkbox width=600 height=600></applet>*/

public class checkbox extends Applet implements ItemListener


{
String msg="";
Checkbox winXP, winNT, winVista, win7;

public void init()


{
winXP=new Checkbox("Windows XP",null,true);
winNT=new Checkbox("Windows NT");
winVista=new Checkbox("Windows Vista");
win7=new Checkbox("Windows Seven ");

add(winXP);
add(winNT);

63
add(winVista);
add(win7);

winXP.addItemListener(this);
winNT.addItemListener(this);
winVista.addItemListener(this);
win7.addItemListener(this);
}

public void itemStateChanged(ItemEvent ie)


{
repaint();
}

public void paint(Graphics g)


{
msg="Current state ";
g.drawString(msg,6,80);
msg=" windows XP "+ winXP.getState();
g.drawString(msg,6,100);
msg=" windows NT "+winNT.getState();
g.drawString(msg,6,120);
msg=" windows Vista "+ winVista.getState();
g.drawString(msg,6,140);
msg=" windows Seven"+win7.getState();
g.drawString(msg,6,160);
}
}

/* Programe to use a checkbutton in form */


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class check extends Applet
{
public void init()
{
setLayout(new GridLayout(3,1));
Checkbox c1=new Checkbox("Hindi",true);
Checkbox c2=new Checkbox("English");
Checkbox c3=new Checkbox("Panjabi");
add(c1);
add(c2);
add(c3);

c1.addItemListener(this);

64
c2.addItemListener(this);
c3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
if(ie.getSource()==c1)
msg="Current statate : "+c1.getState();
else if(ie.getSource()==c2)
msg="Current statate : "+c2.getState();
else if(ie.getSource()==c3)
msg="Current statate : "+c3.getState();
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg,6,80);
}

}
/* <applet code="check.class" width=200 height=200>
</applet> */

CheckboxGroup VS Radio Buttons: It is


possible to create a set of mutually exclusive check boxes in which one and only one
check box in the group can be checked at any one time. These check boxes are often
called as radio buttons. Before define these check boxes we should define the group to
which they will belong.
We can determine which check box in a group is currently selected by calling
getSelectedCheckbox(). You can set a check box by calling setSelectedCheckbox().
These methods are as follow:
Checkbox getSelectedCheckbox()
Void setSelectedCheckbox(Checkbox which)

/*option button or readio button*/


import java.awt.*;

65
import java.awt.event.*;
import java.applet.*;
/*<applet code=cbgroup width=600 height=600></applet>*/

public class cbgroup extends Applet implements ItemListener


{
String msg="";
Checkbox winXP, winNT, winVista, win7;
CheckboxGroup cbg;

public void init()


{
cbg=new CheckboxGroup();
winXP=new Checkbox("Windows Xp",cbg,true);
winNT=new Checkbox("Windows NT",cbg,false);
winVista=new Checkbox("Windows Vista",cbg, false);
win7 =new Checkbox("Window Seven",cbg, false);

add(winXP);
add(winNT);
add(winVista);
add(win7);

winXP.addItemListener(this);
winNT.addItemListener(this);
winVista.addItemListener(this);
win7.addItemListener(this);
}

public void itemStateChanged(ItemEvent ie)


{
repaint();
}

public void paint(Graphics g)


{
msg="Current Selection ";
msg+=cbg.getSelectedCheckbox().getLabel();
g.drawString(msg,6,100);
}
}

/* Programe to use a radiobutton in form */


import java.applet.*;
import java.awt.*;
public class checkbg extends Applet

66
{
public void init()
{
setLayout(new GridLayout(3,1));
CheckboxGroup cbg=new CheckboxGroup();
Checkbox c1=new Checkbox("M.sc",cbg,true);
Checkbox c2=new Checkbox("M.C.A",cbg,false);
Checkbox c3=new Checkbox("M.E",cbg,true);
add(c1);
add(c2);
add(c3);
}

}
/*<applet code="checkbg.class" width=200 height=200>
</applet> */

Choice Controls: The Choice class is used to create a pop-up list of


items from which user may choose. Thus a choice control is a form of menu. When
inactive , a choice component takes up only enough space to show the currently selected
item. When the user clicks on it, the whole list of choices pops up, and a new selection
can be made. Each item in the list is a string. Choice class define only the default
constructor, which creates an empty list. To add a selection to the list , call addItem() or
add() method.

Void addItem(String name)


Void add(String name)

Here name is the name of item being added. Items are added to the list in the order in
which calls to add() or addItem() occur. To determine which item is currently selected,
you may call either getSelectedItem() or getSelectedIndex() method.

String getSelectedItem()
String getSelectedIndex()

The getSelected Item() method returns a string containing the name of the item.
getSelectedIndex() returns the index of the item. The first item is at index 0. By default
the first item of the list is selected.
To obtain the number of items in the list, call
getItemCount(). You can get the currently selected item using the select() method with
either an index or a string that will match a name in the list.

Int getItemCount()

67
Void select(int index)
Void select(String name)

By the help of index we can obtain the name of item associated with that index by using
this method.

String getItem(int index)


Here index specifies the index of desired item.

/*choice controls*/
import java.awt.*;
import java.applet.*;
public class choice_control extends Applet
{
Choice c;
String s1,str;
int index,count=0;

public void init()


{
c=new Choice();
c.addItem("Amit");
c.addItem("Sumit");
c.add("Raman");
c.add("Suman");

add(c);

s1=c.getSelectedItem(); //will show selected item name


index=c.getSelectedIndex(); //will show selected item index

count=c.getItemCount(); //will show total item count of list

c.select(3); //will show suman selected


c.select("Sumit");//will show sumit select

str=c.getItem(3); //will show name at index 3


}

public void paint(Graphics g)


{
g.drawString(s1,100,100);
g.drawString(String.valueOf(index),200,200);
g.drawString("Total items in the list "+String.valueOf(count),300,300);
g.drawString("At index 3 is "+str,400,400);
}

68
}
/*<applet code=choice_control width=500 height=500></applet>*/

Choice List box: Each time a choice is selected, an item event is


generated. This is sent to any listener which receive item event notification from that
component. Each listener implements the ItemListener interface. That interface defines
the itemStateChanged() method. An ItemEvent object is supplied as the argument to this
method.

Example: /*****************Choice List Box Demo***********/


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

/*<applet code=choicelistbox width=600 height=600></applet>*/

public class choicelistbox extends Applet implements ItemListener


{
Choice os,browser;
String msg="";

public void init()


{
os=new Choice();
browser=new Choice();

os.add("Window Nt");
os.add("Window XP");
os.add("Window 7");
os.add("Window Vista");
browser.add("Internet Explorer");
browser.add("Hot Java");
browser.add("NetScape");
browser.add("Machintos");
add(os);
add(browser);
os.addItemListener(this);
browser.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}

69
public void paint(Graphics g)
{
msg="Current OS :";
msg+=os.getSelectedItem();
g.drawString(msg,6,120);
msg="Current Browser :";
msg+=browser.getSelectedItem();
g.drawString(msg,6,140);
}
}

Using List: The List class provides a compact, multiple-choice, scrolling


list. Unlike the choice object, which shows only the single selected item in the menu, a
list object can be constructed to show any number of choices in the visible window. It can
also be created to allow multiple selections. List provides these constructors.

List()
List(int numrows)
List(int numrows, boolean multipleselect)

The first version creates a List control that allows only one item to be selected at any one
time. In the second form, the numrows specifies the number of entries in the list that will
always be visible. In the third form, if multipleselect is true then the user may select two
or more items at a time. It is false then only one item may be selected. To add a selection
to the list call add ( ) method. It has the following forms;

Void add(String name)


Void add(string name, int index)

Here name is the name of the item added to the list. The first form adds items to the end
of the list. The second form adds the item at the index specified by index. Indexing
begins at zero. You can specify -1 to add the item to the end of the list.
For list that allow only single selection, you can determine which item is currently
selected by calling either getSelectedItem() or getSelectedIndex(). These methods are like
this.
String getSelectedItem()
Int getSelectedIndex()

The getSelectedItem() method returns a string containing the name of the item. If more
than one item is selected or if no selection has yet been made, null is returned.
getSelectedIndex() returns the index of the item. The first item is at index 0. If more than
one item is selected or if no selection has yet been made. -1 is returned.
For list that allow multiple selection, you must use either getSelectedItems() or
getSelectedIndexes().

70
String [] getSelectedItems()
Int [] getSelectedIndex()

To obtain the number of items in the list, call getItemCount(). You can set the currently
selected item by using the select() method with a zero-based integer index.

Int getItemCount()
Void select(int index)

To obtain the name of an item associated with an index we can use getItem() method. It
is like this.
String getItem(int index)

/*List control*/
import java.awt.*;
import java.applet.*;
/*<applet code=list width=500 height=500></applet>*/
public class list extends Applet
{
List l1,l2,l3;

public void init()


{
l1=new List();
l2=new List(4);// 4 row
l3=new List(5,true);//multiple select

l1.add("a");

l2.add("amit");
l2.add("sumit");

l3.add("Apple");
l3.add("Mango");
l3.add("Banana");
l3.add("Litchi");
l3.add("Pulam");
l3.add("Piches");

l3.add("Grapes",2);//adding to a specific position

add(l1);
add(l2);
add(l3);
}
}

71
Example: /***************** List Box Demo***********/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=listbox width=600 height=600></applet>*/
public class listbox extends Applet implements ActionListener
{
List os,browser;
String msg="";
public void init()
{
os=new List(4,true);
browser=new List(4,false);
os.add("Window Nt");
os.add("Window XP");
os.add("Window 7");
os.add("Window Vista");
browser.add("Internet Explorer");
browser.add("Hot Java");
browser.add("NetScape");
browser.add("Machintos");
browser.select(1);
add(os);
add(browser);
os.addActionListener(this);
browser.addActionListener(this);
}
public void actionPerformed(ActionEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
int idx[];
msg="Current OS :";
idx=os.getSelectedIndexes();
for(int i=0; i<idx.length;i++)
msg+=os.getItem(idx[i])+" ";
g.drawString(msg,6,120);
msg="Current Browser :";
msg+=browser.getSelectedItem();
g.drawString(msg,6,140);
}
}

72
/* All Above Tools in combination*/
import java.awt.*;
import java.applet.*;
//<applet code="tools.class" height=400 width=400></applet>
public class tools extends Applet
{
TextField t1;
Label l1,l2,l3,l4,l5,l6;
Button b1;
Checkbox c1,c2,c3;
CheckboxGroup cbg;
Checkbox g1,g2,g3;
List li;
Choice ch;
TextArea ta;
public void init()
{
t1=new TextField(15);
l1=new Label("Name");
b1=new Button("Click me");
l2=new Label("Qualification");
c1=new Checkbox("HS",null,false);
c2=new Checkbox("Inter",null,false);
c3=new Checkbox("Graduate",null,false);
l3=new Label("Category");
cbg=new CheckboxGroup();
g1=new Checkbox("Gen",cbg,true);
g2=new Checkbox("Sc",cbg,false);
g3=new Checkbox("St",cbg,false);
l4=new Label("Etables");
li=new List(4);
li.add("Pizza");
li.add("Burger");
li.add("Patties");
li.add("Hot Dog");
li.add("Samosa");
l5=new Label("Soft Drinks");
ch=new Choice();
ch.add("Pepsi");
ch.add("Coke");
ch.add("Dew");
ch.add("Thumbsup");
l6=new Label("Comment");
ta=new TextArea(5,15);
add(l1);
add(t1);

73
add(b1);
add(l2);
add(c1);
add(c2);
add(c3);
add(l3);
add(g1);
add(g2);
add(g3);
add(l4);
add(li);
add(l5);
add(ch);
add(l6);
add(ta);
}
}

Scroll Bars: Scroll bars are used to select continues values between a
specified minimum and maximum. Scroll bars may be oriented horizontally or vertically.
A scroll bar is a composite of several individual parts. Each end has an arrow that you
can click to move the current value of the scroll bar on unit in the direction of the arrow.
Scroll bar are encapsulated by the Scrollbar class. Scrollbar defines the following
constructors.

Scrollbar()
Scrollbar(int style)
Scrollbar(int style, int initialvalue, int thumbsize, int min, int max)

The first form creates a vertical scroll bar. The second and third forms allow you to
specify the orientation of the scroll bar. If style is scrollbar.VERTICAL, a vertical scroll
bar is created. If style is Scrollbar.HORIZONTAL the scroll bar is horizontal. In the third
form of the constructor, the initial value of the scroll bar is passed in initialvalue. The
number of units represented by the height of the thumb is passed in thumbsize. The
minimum and maximum values for the scroll bar are specified by min and max.
To obtain the current value of the scroll bar , call getValue() method. It returns the
current setting. To set the current value, call setValue(). These method are as follow:

Int getValue()
Void setValue(int newvalue)

Her newvalue specifiers the new value for the scroll bar. You can retrieve the minimum
and maximum value by getMinimum() and getMaximum() method.
By default , 1 is the increment added to or subtracted from the scroll bar each time it is
scrolled up or down one line. We can change this increment by calling

74
setUnitIncrement(). By default page up and page down increments are 10. You can
change this value by calling setBlockIncrement(). These methods are shown here.

Void setUnitIncrement(int newincre)


Void setBlockIncrement(int newincr)

/*scroll bars*/
import java.awt.*;
import java.applet.*;
/*<applet code=scrollbars width=500 height=500></applet>*/
public class scrollbars extends Applet
{
Scrollbar s1,s2,s3;

public void init()


{
s1=new Scrollbar();
s2=new Scrollbar(Scrollbar.HORIZONTAL);
s3=new Scrollbar(Scrollbar.HORIZONTAL,5,10,0,100);
//0 is the minimum value , 100 is the maximmum value, 10 is the thumb size, 5 is the
initial value of scrollbar where slider will display in the begining

add(s1);
add(s2);
add(s3);
}

public void paint(Graphics g)


{
int i=s3.getMinimum();
int j=s3.getMaximum();

g.drawString(String.valueOf(i),100,100);
g.drawString(String.valueOf(j),200,200);
}
}

/*scroll bars event*/


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=scrollbars1 width=500 height=500></applet>*/
public class scrollbars1 extends Applet implements AdjustmentListener
{
String msg;

75
Scrollbar hr,vr;

public void init()


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

vr=new Scrollbar(Scrollbar.VERTICAL,10,10,0,height);
hr=new Scrollbar(Scrollbar.HORIZONTAL,0,5,0,width);

add(hr);
add(vr);

hr.addAdjustmentListener(this);
vr.addAdjustmentListener(this);

hr.setUnitIncrement(10); //clicking on scroll bar


hr.setBlockIncrement(25); //work with page up and page down
}

public void adjustmentValueChanged(AdjustmentEvent ae)


{
repaint();
}

public void paint(Graphics g)


{
msg="Horizontal Scrollbar :"+hr.getValue();
msg+=", Vertical Scrollbar :"+vr.getValue();
g.drawString(msg,6,160);
g.drawString("*",hr.getValue(),vr.getValue());
}
}

76
Layout
Layout Managers: A layout manager automatically arranges your controls within a
window by using some type of algorithm. Each container object has a layout manager
associated with it. A Layout manager is an instance of any class that implements the
LayoutManager interface. The layout manager is set by the setLayout() method. If no call
to setLayout() is made, then the default layout manager is used. Whenever a container is
resized the layout manager is used to position each of the components within it. The
setLayout() method has the following general form.

Void setLayout(LayoutManager layoutobj)

Here layoutobj is a reference to the desired layout manager. If you wish to disable the
layout manager and position components manually, pass null for layoutobj. If you do this,
you will need to determine the shape and position of each component manually, using the
setBounds() method defined by component.

FlowLayout : FlowLayout is the default layout manager. It


implements a simple layout style, which is similar to how words flow in a text editor.
Components are laid out from the upper left corner, left to right and top to bottom. When
no more components fit on a line, the next one appears on the next line. A small space is
left between each component, above and below, as well left and right. Here are
constructor for FlowLayout.

FlowLayout()
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)

The first form creates the default layout, which centers components and leaves five pixels
of space between each component. The second form lets you specify how each line is
aligned. Valid values of how are as follow:

FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT

77
The third constructor allow you to specify the horizontal and vertical space left between
components in hors and vert, respectively.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=flowlayout width=175 height=130></applet>*/

public class flowlayout extends Applet


{
TextField t1,t2;
Label l1,l2;

public void init()


{
//setLayout(new FlowLayout()); //bydefault it is center

//setLayout(new FlowLayout(FlowLayout.LEFT));
//setLayout(new FlowLayout(FlowLayout.RIGHT));
//setLayout(new FlowLayout(FlowLayout.CENTER));

setLayout(new FlowLayout(FlowLayout.CENTER,10,25));
//10 is the horizontal space between controls and 25 is the vertical space between
controls

l1=new Label("Name :");


l2=new Label("Age : ");
t1=new TextField(10);
t2=new TextField(10);
add(l1);
add(t1);
add(l2);
add(t2);
}
}

/********************Flow Layout demo ****/


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

/*<applet code="flowlayout" width=250 height=200></applet>*/

public class flowlayout extends Applet implements ItemListener


{
String msg="";

78
Checkbox winxp, win7, winvista;

public void init()


{
//setLayout(new FlowLayout(FlowLayout.LEFT));
//setLayout(new FlowLayout(FlowLayout.CENTER));
setLayout(new FlowLayout(FlowLayout.RIGHT));

winxp=new Checkbox("Window XP", null, true);


win7=new Checkbox("Window 7 ");
winvista=new Checkbox("Window Vista");

add(winxp);
add(win7);
add(winvista);

winxp.addItemListener(this);
win7.addItemListener(this);
winvista.addItemListener(this);
}

public void itemStateChanged(ItemEvent ie)


{
repaint();
}

public void paint(Graphics g)


{
msg="Current state ";
g.drawString(msg, 6, 80);
msg=" windows 98 :"+winxp.getState();
g.drawString(msg,6,100);
msg=" window 7 "+win7.getState();
g.drawString(msg, 6,120);
msg=" window vista "+ winvista.getState();
g.drawString(msg, 6,140);
}
}

/*Panel*/
import java.awt.*;
import java.applet.*;
/*<applet code=panels width=500 height=500></applet>*/
public class panels extends Applet
{

79
public void init()
{
Panel p=new Panel();
Button b1=new Button("Ok");
Button b2=new Button("Cancel");
p.add(b1);
p.add(b2);
add(p);

Panel p2=new Panel();


Button b3=new Button("THird");
Button b4=new Button("Fourth");
p2.add(b3);
p2.add(b4);
add(p2);

Panel p3=new Panel();


Checkbox c1=new Checkbox("Male");
Checkbox c2=new Checkbox("Female");
p3.add(c1);
p3.add(c2);
add(p3);
}
}

/*A form with with all controls*/


import java.awt.event.*;
import java.awt.*;
import java.applet.*;
//<applet code=employee width=500 height=500></applet>
public class employee extends Applet
{
Label l;
Font f;
Label name,age,salary,address,designation;
TextField tname,tage,tsalary,taddress,tdesignation;
Checkbox male,female, married, unmarried;
CheckboxGroup cbg;

public void init()


{
f=new Font("Arial Black",Font.PLAIN,15);
setFont(f);
setSize(360,540);//to set the size of form
setLayout(new FlowLayout(FlowLayout.LEFT,30,5));
cbg=new CheckboxGroup();

80
Panel p=new Panel();
l=new Label("Employee",Label.RIGHT);
p.add(l);
f=new Font("Arial Black", Font.BOLD,25);
p.setFont(f);
add(p);

Panel p1=new Panel();


name=new Label("Name ");
p1.add(name);
tname=new TextField(15);
p1.add(tname);
add(p1);

Panel p2=new Panel();


age=new Label("Age ");
p2.add(age);
tage=new TextField(10);
p2.add(tage);
add(p2);

Panel p3=new Panel();


salary=new Label("Salary ");
p3.add(salary);
tsalary=new TextField(10);
p3.add(tsalary);
add(p3);

Panel p4=new Panel();


address=new Label("Address ");
p4.add(address);
taddress=new TextField(15);
p4.add(taddress);
add(p4);

Panel p5=new Panel();


designation=new Label("Designation");
p5.add(designation);
tdesignation=new TextField(15);
p5.add(tdesignation);
add(p5);

Panel p6=new Panel();


Label lblgender=new Label("Gender");

81
male=new Checkbox("Male");
female=new Checkbox("Female");
p6.add(lblgender);
p6.add(male);
p6.add(female);
add(p6);

Panel p7=new Panel();


Label lblms=new Label("Marital Status");
married=new Checkbox("Married",cbg,true);
unmarried=new Checkbox("Un-married",cbg,false);
p7.add(lblms);
p7.add(married);
p7.add(unmarried);
add(p7);

Panel pout=new Panel();


Label output=new Label("OUTPUT");
pout.add(output);
f=new Font("Arial Black",Font.BOLD,25);
pout.setFont(f);
add(pout);

TextArea t=new TextArea(4,35);


add(t);

Button b1=new Button("Ok");


add(b1);
Button b2=new Button("Cancel");
add(b2);
}

BorderLayout: This class implements a common layout style


for top level windows. It has four narrow, fixed width components at the edges and one
large area in the center. The four sides are referred to as north, south, east, and west. The
middle area is called the center. Here are the constructors defined by BorderLayouat.

BorderLayout()
BorderLayout(int horz, int vert)

The first form creates a default border layout. The second allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.
BorderLayout defines the following constants that specify the regions.

82
BorderLayout.CENTER
BorderLayout.EAST
BorderLayout.NORTH
BorderLayout.SOUTH
BorderLayout.WEST

You can add these components by add() method.

Void add(Component compobj, Object region)

Here compobj is the component to be added, and region specifies where the component
will be added.

/*Border Layout Demo*/


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=borderlayout width=500 height=500></applet code>*/
public class borderlayout extends Applet
{
Button b1,b2,b3,b4,b5;

public void init()


{
//setLayout(new BorderLayout());
setLayout(new BorderLayout(10,10)); //200 is the vertical tab between
controls
b1=new Button("Ok");
b2=new Button("Cancel");
b3=new Button("Bottom");
b4=new Button("Top");
b5=new Button("Left");

add(b1, BorderLayout.EAST);
add(b2, BorderLayout.WEST);
add(b3, BorderLayout.SOUTH);
add(b4, BorderLayout.NORTH);
add(b5, BorderLayout.CENTER);
}
}

/**********Border layout *****/


import java.awt.*;
import java.applet.*;
import java.util.*;

83
/*<applet code=borderlayout width=400 height=200></applet>*/
public class borderlayout extends Applet
{
public void init()
{
setLayout(new BorderLayout());
add(new Button("This is across the top. "), BorderLayout.NORTH);
add(new Label("The footer message might go here."), BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);

String msg="The reasonable man adapts "+"Himself to the world \n"+ " the
unreasonable one persists in "+" trying to dapt the world to himself \n"+" There fore all
progress depends "+ " on the unreasonable man \n\n"+ " -George Bernard Shaw \n\n";

add(new TextArea(msg), BorderLayout.CENTER);


}
}

Using Insets: Sometimes you will want to leave a small amount of space between the
container that holds your components and the window that contains it. To do this,
override the getInsets() method that is defined by Container. This function returns an
Insets object that contains the top, bottom, left, and right manager to inset the
components when it lays out the window. The constructor for Insets in shown here.

Insets(int top, int left, itn bottom, int right)

The values passed in top, left, bottom and right specify the amount of space between the
container and its enclosing window. The getInsets() method has this general form.

Insets getInsets()

When override one of these methods, you must return a new Insets object that contains
the inset spacing you desire.

/**********Border layout with Insets *****/


import java.awt.*;
import java.applet.*;
import java.util.*;

/*<applet code=insetborderlayout width=400 height=200></applet>*/

public class insetborderlayout extends Applet


{
public void init()
{

84
setBackground(Color.cyan);
setLayout(new BorderLayout());
add(new Button("This is across the top. "), BorderLayout.NORTH);
add(new Label("The footer message might go here."), BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);

String msg="The reasonable man adapts "+"Himself to the world \n"+ " the
unreasonable one persists in "+" trying to dapt the world to himself \n"+" There fore all
progress depends "+ " on the unreasonable man \n\n"+ " -George Bernard Shaw \n\n";

add(new TextArea(msg), BorderLayout.CENTER);


}
public Insets getInsets()
{
return new Insets(10,10,10,10);
}
}

/***frame with Bordarlyout and with panel****/


import java.awt.*;
class frames
{
Frame f;
Panel p,p1,p2,p3;
Button file, help,west,works;
TextField t1,t2;
Label l1,l2;
Checkbox male,female;

frames()
{
f=new Frame("Frame with BorderLayout & Panel ");
west=new Button("West");
works=new Button("Work Space");
file=new Button("File");
help=new Button("Help");
l1=new Label("Name");
l2=new Label("Age");
t1=new TextField(10);
t2=new TextField(10);
male=new Checkbox("Male");
female=new Checkbox("Female");
}

public void create()

85
{
p1=new Panel();
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(t2);
f.add(p1,BorderLayout.NORTH); //top

p3=new Panel();
p3.add(male);
p3.add(female);
f.add(p3,BorderLayout.WEST);

p2=new Panel();
p2.add(west);
p2.add(works);
f.add(p2, BorderLayout.EAST); //right

p=new Panel();
p.add(file);
p.add(help);
f.add(p, BorderLayout.SOUTH);//Bottom

f.pack();
f.setVisible(true);
}

public static void main(String args[])


{
frames obj=new frames();
obj.create();
}
}

GridLayout: GridLayout lays out components in a two dimensional


grid. When you instantiate a GridLayout, you define the number of rows and columns.
The constructors supported by GridLayout are as follow:

GridLayout()
GridLayout(int numrows, int numcolumns)
GridLayout(int numrows, int numcolumns, int horz, int vert)

The first form creates a single column grid layout. The second form creates a grid layout
with the specified number of rows and columns. The third form allows you to specify the

86
horizontal and vertical space left between components in horz and vert. either numrows
or numcolumns can be zero specifying numrows as zero allows for unlimited length
columns. Specifying numcolumns as zero allows for unlimited length rows.

/*Grid Layout */
import java.awt.*;
import java.applet.*;
/*<applet code=gridlayout width=500 height=500></applet>*/
public class gridlayout extends Applet
{
Button b1,b2,b3,b4;

public void init()


{
//setLayout(new GridLayout()); //will show all buttons in four columns
//setLayout(new GridLayout(2,2));//2 row and 2 columns
setLayout(new GridLayout(2,2,10,10)); //10 is the horizontal gap and next
10 is vertical gap
b1=new Button("First");
b2=new Button("Second");
b3=new Button("Third");
b4=new Button("Fourth");
add(b1);
add(b2);
add(b3);
add(b4);
}
}

/************ Grid Layout ******/


import java.awt.*;
import java.applet.*;
/*<applet code=gridlayout width=300 height=200></applet>*/

public class gridlayout extends Applet


{
Int n=4;
public void init()
{
//setLayout(new GridLayout(n,n,10,20));
setLayout(new GridLayout(n,n));
//setLayout(new GridLayout());
setFont(new Font("SansSerif", Font.BOLD, 25));
for(int i=1;i<=15;i++)
add(new Button(""+i));

87
}
}

/*Employee form with grid layout*/


import java.awt.*;
class gridlayouts
{
Frame f;
Label l,bl,l1,l2,l3,l4,l5;
TextField t1,t2,t3,t4,t5;
Button b1,b2;
Font ft;

gridlayouts()
{
f=new Frame("Frame with grid Layout");
f.setLayout(new GridLayout(7,2));
ft=new Font("Areal Black",Font.PLAIN,20);
f.setFont(ft);
l=new Label("Employee",Label.RIGHT);
bl=new Label();
l1=new Label("Name",Label.CENTER);
t1=new TextField(10);
l2=new Label("Age ",Label.CENTER);
t2=new TextField(10);
l3=new Label("Salary",Label.CENTER);
t3=new TextField(10);
l4=new Label("Address ",Label.CENTER);
t4=new TextField(15);
l5=new Label("Code",Label.CENTER);
t5=new TextField(5);
b1=new Button("OK");
b2=new Button("Cancel");

f.add(l);
f.add(bl);
f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.add(l3);
f.add(t3);
f.add(l4);
f.add(t4);
f.add(l5);

88
f.add(t5);
f.add(b1);
f.add(b2);
f.pack();
f.setVisible(true);
}

public static void main(String args[])


{
gridlayouts obj=new gridlayouts();
}
}

/******************Form with two layout layouts***************/


import java.awt.*;
import java.applet.*;
//<applet code="pan.class" height=400 width=400></applet>
public class pan extends Applet
{
Button e,w,s,c;
Label l1,l2,l3;
TextField t1,t2,t3;
BorderLayout bl;
Panel p1;
public void init()
{
bl=new BorderLayout();
setLayout(bl);
e=new Button("East");
w=new Button("West");
s=new Button("South");
c=new Button("Center");
add(e,BorderLayout.EAST);
add(w,BorderLayout.WEST);
add(s,BorderLayout.SOUTH);
add(c,BorderLayout.CENTER);

p1=new Panel();
p1.setLayout(new GridLayout(3,2));
l1=new Label("Name");
l2=new Label("Address");
l3=new Label("Rollno");
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
p1.add(l1);

89
p1.add(t1);
p1.add(l2);
p1.add(t2);
p1.add(l3);
p1.add(t3);

add(p1,BorderLayout.NORTH);
}
}

/***attech applet form with window form*******/


1. First Form or Main Applet form
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
//<applet code=atteched width=500 height=500></applet>
public class atteched extends Applet implements ActionListener
{
Button btnok;

public void init()


{
btnok=new Button("Ok");
add(btnok);
btnok.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
if(ae.getSource()==btnok)
{
demoform obj=new demoform("Hello");
obj.setSize(100,100);
obj.setVisible(true);
}
}
}

2. Second Form
import java.awt.*;
public class demoform extends Frame
{
String str;
demoform(String s)
{

90
str=s;
}

public void paint(Graphics g)


{
g.drawString(str,100,100);
}
}

Attached Forms by applet.


1.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code=form1 width=547 height=282></applet>
public class form1 extends Applet implements ActionListener
{
Panel p1,p2,p3;
Label lblname,lblage,lblsal,lbladd,lblgender,lblms;
TextField txtn,txtage,txtsal,txtadd;
Checkbox chkmale,chkfemale,chkmr,chkur;
CheckboxGroup cbg;
Button btnok, btncancel;

public void init()


{
setBackground(Color.blue);
setLayout(new GridLayout(2,2));
p1=new Panel();
p2=new Panel();
p3=new Panel();

p1.setSize(100,100);
p1.setBackground(Color.yellow);
lblname=new Label("Name");
txtn=new TextField(25);
p1.add(lblname);
p1.add(txtn);
add(p1);
lblage=new Label("Age");

91
p1.add(lblage);
txtage=new TextField(5);
p1.add(txtage);
lblsal=new Label("Salary");
p1.add(lblsal);
txtsal=new TextField(5);
p1.add(txtsal);
lbladd=new Label("Address");
p1.add(lbladd);
txtadd=new TextField(20);
p1.add(txtadd);

add(p2);
p2.setSize(100,100);
p2.setBackground(Color.cyan);
lblgender=new Label("Gender");
p2.add(lblgender);
chkmale=new Checkbox("Male");
chkfemale=new Checkbox("Female");
p2.add(chkmale);
p2.add(chkfemale);

lblms=new Label("Marital Status");


p2.add(lblms);
cbg=new CheckboxGroup();
chkmr=new Checkbox("Married",cbg,true);
chkur=new Checkbox("Unmarried",cbg,false);
p2.add(chkmr);
p2.add(chkur);

p3.setSize(100,100);
p3.setBackground(Color.red);
add(p3);
btnok=new Button(" OK ");
btncancel=new Button("Cancel");
p3.add(btnok);
p3.add(btncancel);
btnok.addActionListener(this);
btncancel.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
String s=ae.getActionCommand();
s=s.trim();
if(s.equals("OK"))

92
{
form2 obj=new form2();
String str=txtn.getText()+"\n"+txtage.getText()+"\
n"+txtsal.getText()+"\n"+txtadd.getText();
if(chkmr.getState())
str+="\nMarried";
else if(chkur.getState())
str+="\nUnmarried";
if(chkmale.getState())
str+="\nMale";
else if(chkfemale.getState())
str+="\nFemale";
obj.t.setText(str);
}
else if(s.equals("Cancel"))
System.exit(1);
}

}
2.Output form
import java.awt.*;
import java.awt.event.*;
public class form2 extends Frame
{
Frame f;
TextArea t;

form2()
{
f=new Frame("Output Form");
f.setSize(200,200);
f.setVisible(true);
t=new TextArea(4,50);
f.add(t);

f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
f.setVisible(false);
dispose();
}
});
}
}

93
/*Frame with panel and Grid layout*/
import java.awt.*;
import java.awt.event.*;
public class form1 implements ActionListener
{
Frame f;
Panel p1,p2,p3;
Label lblname,lblage,lblsal,lbladd,lblgender,lblms;
TextField txtn,txtage,txtsal,txtadd;
Checkbox chkmale,chkfemale,chkmr,chkur;
CheckboxGroup cbg;
Button btnok, btncancel;

form1()
{
f=new Frame("Employee Form");
f.setSize(545,235);
f.setBackground(Color.blue);
f.setLayout(new GridLayout(2,2));
p1=new Panel();
p2=new Panel();
p3=new Panel();
}

void create()
{
p1.setSize(100,100);
p1.setBackground(Color.yellow);
lblname=new Label("Name");
txtn=new TextField(25);
p1.add(lblname);
p1.add(txtn);
f.add(p1);
lblage=new Label("Age");
p1.add(lblage);
txtage=new TextField(5);
p1.add(txtage);
lblsal=new Label("Salary");
p1.add(lblsal);
txtsal=new TextField(5);
p1.add(txtsal);
lbladd=new Label("Address");
p1.add(lbladd);
txtadd=new TextField(20);
p1.add(txtadd);

94
f.add(p2);
p2.setSize(100,100);
p2.setBackground(Color.cyan);
lblgender=new Label("Gender");
p2.add(lblgender);
chkmale=new Checkbox("Male");
chkfemale=new Checkbox("Female");
p2.add(chkmale);
p2.add(chkfemale);

lblms=new Label("Marital Status");


p2.add(lblms);
cbg=new CheckboxGroup();
chkmr=new Checkbox("Married",cbg,true);
chkur=new Checkbox("Unmarried",cbg,false);
p2.add(chkmr);
p2.add(chkur);

p3.setSize(100,100);
p3.setBackground(Color.red);
f.add(p3);
btnok=new Button(" OK ");
btncancel=new Button("Cancel");
p3.add(btnok);
p3.add(btncancel);
btnok.addActionListener(this);
btncancel.addActionListener(this);

f.setVisible(true);
}

public void actionPerformed(ActionEvent ae)


{
String s=ae.getActionCommand();
s=s.trim();
if(s.equals("OK"))
{
//System.out.println(f.getSize());
form2 obj=new form2();
String str=txtn.getText()+"\n"+txtage.getText()+"\
n"+txtsal.getText()+"\n"+txtadd.getText();
if(chkmr.getState())
str+="\nMarried";
else if(chkur.getState())
str+="\nUnmarried";

95
if(chkmale.getState())
str+="\nMale";
else if(chkfemale.getState())
str+="\nFemale";
obj.t.setText(str);
}
else if(s.equals("Cancel"))
System.exit(1);
}
public static void main(String args[])
{
form1 obj=new form1();
obj.create();
}
}
Output form form 2
/*output of last form on ok button click*/
import java.awt.*;
import java.awt.event.*;
public class form2 extends Frame
{
Frame f;
TextArea t;

form2()
{
f=new Frame("Output Form");
f.setSize(200,200);
f.setVisible(true);
t=new TextArea(4,50);
f.add(t);

f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
f.setVisible(false);
dispose();
}
});
}

96
Card Layout: This class is unique among the other layout managers
because it stores several different layouts. Card layout provides two constructors.

CardLayout()
CardLayout(int horz, int vert)

The first form creates a default card layout. The second form allows you to specify the
horizontal and vertical space left between components in horz and vert.
The card typically held in an object of type Panel. This panel must have CardLayout
selected as its layout manager.
Most of the time you will use this form of add() when adding cards to a panel.

Void add(Component panelobj, object name);

Here name is a string that specifies the name of the card whose panel is specified by
panelobj.
After you have created a deck, your program activates a card by calling one of the
following methods defined by CardLayout.

Void first(Container deck)


Void last(Container deck)
Void next(Container deck)
Void pervious (Container deck)
Void show(Container deck, String cardname)

Here deck is the reference to the container (usually a panel) that holds the cards, and
cardname is the name of a card. Calling first() caused the first card in the deck to be
shown. To show the last card, call last(). To show the next card, call next(). To show the
previous card , call previous(). Both next() and previous() automatically cycle back to the
top or bottom of the deck, respectively. The show() method displays the card whose ame
is passed in cardname.

/**********Card Layout Demo***************/


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
//<applet code=cardlayouts width=500 height=500></applet>
public class cardlayouts extends Applet implements ActionListener
{
Panel p1,p2,p3;
Button b1,b2;
CardLayout card;
public void init()
{
card=new CardLayout();

97
p1=new Panel();
p1.setBackground(Color.red);
b1=new Button("First Button within First panel");
p1.add(b1);//adding button1 to panel1
add(p1);

p2=new Panel();
p2.setBackground(Color.cyan);
b2=new Button("Second Button within Second Panel");
p2.add(b2);//adding button2 to apnel2
add(p2);

p3=new Panel();
p3.setBackground(Color.green);
p3.setLayout(card);//setting card layout of panel 3
p3.add(p1,"First");//adding panel 1 to panel3
p3.add(p2,"Second");//adding panel 2 to panel3
add(p3);

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

public void actionPerformed(ActionEvent ae)


{
card.next(p3); //method to get next panel of card
}
}

/**********Card layout *********/


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=cardlayout width=300 height=100></applet>*/

public class cardlayout extends Applet implements ActionListener, MouseListener


{
Checkbox winxp, winnt, winvista;
Panel oscards;
CardLayout card;
Button win, other;

public void init()


{
win=new Button("Windows");

98
other=new Button("Other");
add(win);
add(other);

card=new CardLayout();
oscards=new Panel();
oscards.setLayout(card); //set panel layout to card layout

winxp=new Checkbox("Window xp ", null, true);


winnt=new Checkbox("Window Nt");
winvista=new Checkbox("Window Vista");
Panel winpan=new Panel();
winpan.add(winxp);
winpan.add(winnt);
Panel otherpan=new Panel();
otherpan.add(winvista);
oscards.add(winpan, "Windows");
oscards.add(otherpan, "Other");

add(oscards);
win.addActionListener(this);
other.addActionListener(this);
addMouseListener(this);
}
public void mousePressed(MouseEvent me)
{
card.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)
{
card.show(oscards, "Windows");
}
else
{
card.show(oscards, "Other");
}
}
}

99
Frame
The AWT classes are contained in the java.awt package. It is one of java’s largest
packages. It is logically organized in a top down, hierarchical fashion.

Component: This class lies at the top of the AWT hierarchy. Component is an abstract
class that encapsulates all of the attributes of a visual component. It defines over a
hundred public methods that are responsible for managing events. A component object is
responsible for remembering the current foreground and background colors and the
currently selected text font.

Container: This class is sub class of Component. It has additional methods that allow
other component objects to be nested within it. A container is responsible for laying out
any component that it contains. It does this through the various layout managers.

Panel: The panel is concrete subclass of container. It does not add any new methods. It
simply implements container. Panel is the super class of Applet class. When screen
output is directed to an Applet, it is drawn on the surface of a Panel object. A panel is a
window that does not contain a title bar, menu bar or border. This is why you don’t see
these items when an Applet is run inside a browser. When you run an Applet using applet
viewer than applet viewer provides that title and boarder.
Other objects can be added to a panel object by its add() method (inherited
from container). Once these components have been added, you can position and resize
them manually using the setLocation(), setSize(), setBounds() methods defined by
Component.

Window: This class creates a top level window. It is not contained within any other
object. It sits directly on the desktop. Generally we would not create window objected
directly but we will use a subclass of Window called Frame.

Frame: Frame encapsulate what is commonly thought of as a Window. It has a title bar,
menu bar, borders, and resizing corners. When a frame window is created by a program
rather than an Applet, a normal window is created. But if a frame window is created by

100
an applet then a warning message will be sent to the user, telling that this window is
created by applet and not by software running on their computer.

Canvas: Every applet has its own area of screen known as canvas, where it creates its
display. It is not a part of hierarchy for applet or frame windows, it is one different type
of window. A java applet draws graphics image inside this space using the coordinate
system. Java’s coordinate system has the origin (0, 0) in the upper-left corner. Positive X
values are to the right, and positive Y values are to the bottom. The values of coordinates
are in pixels.

Working with frame window: frame class creates a top level window for applications.
Here are two frame constructors.
Frame()-> this form creates a standard window that does not contain a title.
Frame(String title)-> this form creates a with title.
We must specified the size of window by setSize(width, height) method.
The size must specified in pixels.
void setSize(width, height);
void setSize(Dimension newSize);

the getSize() method is used to get the size of window.

Dimension getSize();

Hiding and showing a window: to show a window there is not of setVisible() method
without it we can’t display our window.
void setVisible(true) //to display
void setVisible(false) //to hide

Setting a window’s title: This method will set the title of window.
void setTitle(String title);

Closing a window: We can close a window either by setting the false to the method
setVisible(false) or by windowClosing() method.

/*Frame*/
import java.awt.*;
public class frames extends Frame
{
public static void main(String args[])
{
Frame f=new Frame("Frame window");
f.setSize(250,250);
f.setVisible(true);
System.out.println(f.getSize());//to get size of frame
}

101
}

/***********Frame with few functions*******/


import java.awt.*;
class framedemo extends Frame
{
public static void main(String args[])
{
Frame f=new Frame();
//Frame f=new Frame("Demo Form");
f.setSize(200,200);
f.setVisible(true);
f.setTitle("Demo Form");
System.out.println(f.getSize());
}
}

/*Frame with applet*/


import java.awt.*;
import java.applet.*;
/*<applet code="frame" width=300 height=300></applet>*/
public class frame extends Applet
{
Frame f;

public void init()


{
f=new Frame("Frame window");
f.setSize(250,250);
f.setVisible(true);
}
}

/*fram closing event*/


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

public class MainWindow3 extends Frame


{
public MainWindow3()
{
super("Menu Window");
setSize(400, 400);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)

102
{
System.exit(0);
}
});
}

public static void main(String args[])


{
MainWindow3 w = new MainWindow3();
w.setVisible(true);
}
}

/********************frame hide****************/
import java.awt.*;
import java.awt.event.*;
/*<applet code=FrameHide width=600 height=600></applet>*/
public class FrameHide{
public static void main(String[] args){
Frame fa= new Frame("Frame Hiding");
Panel p =new Panel();
Label l1=new Label("Welcome roseindia");
p.add(l1);
fa.add(p);
fa.setSize(300,200);
fa.setVisible(true);
fa.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
Frame frame = (Frame)e.getSource();
frame.setVisible(false);
}
});
}
}

/*********creating a window that will run directly without appletviewer**/


import java.awt.*;

103
import java.awt.event.*;
/*<applet code=framedemo width=600 height=600></applet>*/
public class framedemo extends Frame
{
Label lbl;
TextField txt;

public framedemo()
{
super("Frame creation demo"); //call to super must be first statment in constructor
lbl=new Label("Name ");
txt=new TextField(20);
Panel p=new Panel();
p.add(lbl, BorderLayout.NORTH);
p.add(txt, BorderLayout.CENTER);
add(p, BorderLayout.CENTER);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
framedemo obj=new framedemo();
}}
Run: framedemo.java

/*A form with frame and with all controls*/


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

class employee extends Frame


{
Label l;
Font f;
Label name,age,salary,address,designation;
TextField tname,tage,tsalary,taddress,tdesignation;
Checkbox male,female, married, unmarried;
CheckboxGroup cbg;

104
employee()
{
f=new Font("Arial Black",Font.PLAIN,15);
setFont(f);
setSize(360,540);
setTitle("Employee Form");
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT,30,5));
//setLayout(new GridLayout(8,8,10,10));
cbg=new CheckboxGroup();

Panel p=new Panel();


l=new Label("Employee",Label.RIGHT);
p.add(l);
f=new Font("Arial Black", Font.BOLD,25);
p.setFont(f);
add(p);

Panel p1=new Panel();


name=new Label("Name ");
p1.add(name);
tname=new TextField(15);
p1.add(tname);
add(p1);

Panel p2=new Panel();


age=new Label("Age ");
p2.add(age);
tage=new TextField(10);
p2.add(tage);
add(p2);

Panel p3=new Panel();


salary=new Label("Salary ");
p3.add(salary);
tsalary=new TextField(10);
p3.add(tsalary);
add(p3);

Panel p4=new Panel();


address=new Label("Address ");
p4.add(address);
taddress=new TextField(15);
p4.add(taddress);
add(p4);

105
Panel p5=new Panel();
designation=new Label("Designation");
p5.add(designation);
tdesignation=new TextField(15);
p5.add(tdesignation);
add(p5);

Panel p6=new Panel();


Label lblgender=new Label("Gender");
male=new Checkbox("Male");
female=new Checkbox("Female");
p6.add(lblgender);
p6.add(male);
p6.add(female);
add(p6);

Panel p7=new Panel();


Label lblms=new Label("Marital Status");
married=new Checkbox("Married",cbg,true);
unmarried=new Checkbox("Un-married",cbg,false);
p7.add(lblms);
p7.add(married);
p7.add(unmarried);
add(p7);

Panel pout=new Panel();


Label output=new Label("OUTPUT");
pout.add(output);
f=new Font("Arial Black",Font.BOLD,25);
pout.setFont(f);
add(pout);

TextArea t=new TextArea(4,35);


add(t);

Button b1=new Button("Ok");


add(b1);
Button b2=new Button("Cancel");
add(b2);
}
public static void main(String args[])
{
employee obj=new employee();
}
}

106
Menu
Menu Bars and Menus: A menu bar displays a list of top-level menu choice. Each
choice is associated with a drop-down menu. This concept is implemented in java by the
following classes: MenuBar, Menu and MenuItem. To create a menu bar, first create an
instance of MenuBar. This class only defines the default constructor. Next, create
instances of Menu that will define the selections displayed on the bar. Following are the
constructor for Menu:

Menu()
Menu(String optionName)
Menue(String optionName, Boolean removable)

Here optionName specifies the name of the menu selection. If removable is true, the pop-
up menu can be removed and allowed to float free. Otherwise it will remain attached to
the menu bar.
Individual menu item are of type MenuItem. It defines these constructors:

MenuItem()
MenuItem(String itemName)
MenuItem(String itemName, MenuShortcut keyAccel)

Here, itemName is the name shown in the menu, and keyAccel is the menu shortcut for
this item. You can disable or enable a menu item by using the setEnabled() method.

Void setEnabled(Boolean enabledflag)

If the enabledflag is true , the menu item is enabled. If false, the menu item is diabled.
You can determine an item’s status by calling isEnabled().

Boolean isEnabled()

107
isEnabled() returns true if the menu item on which it is called is enabled. Otherwise it
returns false. We can change the name of a menu item by calling setLabel(). You can
retrieve the current name by using getLabel().

Void setLabel(String newName)


String getLabel()

You can create a checkable menu item by using a subclass of MenuItem called
CheckboxMenuItem. It has these constructors:

CheckboxMenuItem()
CheckboxMenuItem(String itemname)
CheckboxMenuItem(String itemname, Boolean on)

We can obtain the status of a checkable item by calling getState(). You can set it to a
know state by using setState(). These methods are shown here:

Boolean getState()
Void setState(Boolean checked)

If the item is checked, getState() returns true otherwise it returns false.


Once you have created a menu item , you must add the item to a Menu object by using
add(), which has the following form:

MenuItem add(MenuItem item)

Here item is the item being added. Items are added to a menu in the order in which the
calls to add() take place. After adding all the items to a Menu object , you can add that
object to the menu bar by using this version of add() defined y MenuBar:

Menu add(Menu menu)

Here menu is the menu being added.


Menus generate events when an item of type MenuItem or CheckboxMenuItem is
selected. So we need to implements the ActionListener and ItemListener interface in
order to handle these menu events. The getItem() method of ItemEvent returns a
reference to the item that generated this event. The general form of this method is this:

Object getItem()

/*` bar and menu*/


import java.awt.*;
public class frames extends Frame
{
public static void main(String args[])

108
{
MenuBar mb=new MenuBar();
Frame f=new Frame("Menu Bar");

Menu m1=new Menu("File");


Menu m2=new Menu("Edit");
Menu m3=new Menu("Help");
mb.add(m1);
mb.add(m2);
mb.add(m3);

f.setSize(250,250);
f.setVisible(true);
f.setMenuBar(mb);
}
}

/*Frame with menu bar and menu*/


import java.awt.*;
public class framemenu extends Frame
{
public static void main(String args[])
{
Frame f=new Frame("Menu Bar");
MenuBar mb=new MenuBar();

Menu file=new Menu("File");


MenuItem mi1=new MenuItem("New");
MenuItem mi2=new MenuItem("Open");
MenuItem mi3=new MenuItem("Save");
Menu m4=new Menu();//blanck Menu
file.add(mi1);
file.add(mi2);
file.add(mi3);
mb.add(file);

Menu edit=new Menu("Edit");


MenuItem e1=new MenuItem("Cut");
MenuItem e2=new MenuItem("Copy");
MenuItem e3=new MenuItem("Past");
edit.add(e1);
edit.add(e2);
edit.add(e3);
mb.add(edit);

Menu help=new Menu("Help");

109
MenuItem h1=new MenuItem("About Us");
MenuItem h2=new MenuItem("Help");
MenuItem h3=new MenuItem("Contanct");
help.add(h1);
help.add(h2);
help.add(h3);
mb.add(help);
mb.add(m4);
f.setSize(250,250);
f.setVisible(true);
f.setMenuBar(mb);
}
}

/*Frame with checked menu bar and menu*/


import java.awt.*;
public class cframemenu extends Frame
{
public static void main(String args[])
{
Frame f=new Frame("Menu Bar");
MenuBar mb=new MenuBar();

Menu file=new Menu("File");


CheckboxMenuItem mi1=new CheckboxMenuItem("New");
CheckboxMenuItem mi2=new CheckboxMenuItem("Open");
CheckboxMenuItem mi3=new CheckboxMenuItem("Save");
file.add(mi1);
file.add(mi2);
file.add(mi3);
mb.add(file);

f.setSize(250,250);
f.setVisible(true);
f.setMenuBar(mb);
}
}

/*Frame with checked menu bar and with getting and setting
various properites*/
import java.awt.*;
public class cframemenu extends Frame
{
public static void main(String args[])
{
Frame f=new Frame("Menu Bar");

110
MenuBar mb=new MenuBar();

Menu file=new Menu("File");


CheckboxMenuItem mi1=new CheckboxMenuItem();
CheckboxMenuItem mi2=new CheckboxMenuItem("Open");
CheckboxMenuItem mi3=new CheckboxMenuItem("Save",true);
file.add(mi1);
file.add(mi2);
file.add(mi3);
mb.add(file);

/************setting and getting check state*******/


mi1.setState(true);
boolean s=mi1.getState();
System.out.println(s);

/***********setting and getting label***********/


mi1.setLabel("New");
String st=mi1.getLabel();
System.out.println(st);

/**************getting and setting enable to the menu item***/


mi3.setEnabled(false);
boolean bol=mi3.isEnabled();
System.out.println(bol);

f.setSize(250,250);
f.setVisible(true);
f.setMenuBar(mb);
}

/*Frame with Shortcut key menu bar*/


import java.awt.*;
public class menushortcutkey extends Frame
{
public static void main(String args[])
{
Frame f=new Frame("Menu Bar");
MenuBar mb=new MenuBar();
MenuShortcut s1=new MenuShortcut(78);//shortcut for New (78->N)
MenuShortcut s2=new MenuShortcut(79);//shortcut for Open (79->O)
MenuShortcut s3=new MenuShortcut(83);//shortcut for Save (83->S)

111
Menu file=new Menu("File");
MenuItem mi1=new MenuItem("New",s1);
MenuItem mi2=new MenuItem("Open",s2);
MenuItem mi3=new MenuItem("Save",s3);
file.add(mi1);
file.add(mi2);
file.add(mi3);
mb.add(file);

f.setSize(250,250);
f.setVisible(true);
f.setMenuBar(mb);
}
}

/*Frame with sub menu and seperator and menu*/


import java.awt.*;
public class submenu extends Frame
{
public static void main(String args[])
{
Frame f=new Frame("Menu Bar");
MenuBar mb=new MenuBar();

Menu file=new Menu("File");


MenuItem mi1=new MenuItem("New");
MenuItem mi2=new MenuItem("Open");
MenuItem mi3=new MenuItem("Save");

/*******if you want to make a menue item as sub menu than make it menu first****/
/*Menu m2=new Menu("Save");
m2.add(new MenuItem("First")); //temprary menuitem
m2.add(new MenuItem("Second"));
MenuItem mm=new MenuItem("Third");//parmanent menu item
m2.add(mm);//adding menue item to menu*/
/****************************************************//
/*********adding seperator***************/
file.addSeparator(); //will add separator to the menu
MenuItem mi4=new MenuItem("-");
MenuItem mi5=new MenuItem("Save As");

file.add(mi1);
file.add(mi2);
file.add(mi3);
file.add(mi4);

112
file.add(mi5);

/*************Adding a sub menu**************/


Menu sub=new Menu("Sub Menu");
sub.add(new MenuItem("First"));
sub.add(new MenuItem("Second"));
sub.add(new MenuItem("Third"));
file.add(sub);
/**************************************/

mb.add(file);
f.setSize(250,250);
f.setVisible(true);
f.setMenuBar(mb);
}
}

Programe to create a menu fram with all options (Sepratro, checkbox, sub menu)
import java.awt.*;
public class mymenu
{
public static void main(String args[])
{
Frame f=new Frame("this is test for menu");
MenuBar main=new MenuBar();
f.setMenuBar(main);
Menu filemenu=new Menu("File");
Menu editmenu=new Menu("Edit");
Menu helpmenu=new Menu("Help");
main.add(filemenu);
main.add(editmenu);
main.add(helpmenu);
MenuItem new1=new MenuItem("New");
MenuItem open=new MenuItem("Open");
MenuItem close=new MenuItem("Close");
MenuItem line=new MenuItem("-");
CheckboxMenuItem print=new CheckboxMenuItem("Print");
MenuItem exit=new MenuItem("Exit");
filemenu.add(new1);
filemenu.add(open);
filemenu.add(close);
filemenu.add(line);
filemenu.add(print);
filemenu.add(exit);
MenuItem cut=new MenuItem("Cut");
MenuItem copy=new MenuItem("Copy");

113
MenuItem paste=new MenuItem("Paste");
MenuItem undo=new MenuItem("Undo");
editmenu.add(cut);
seditmenu.add(copy);
editmenu.add(paste);
editmenu.addSeparator();
editmenu.add(undo);
undo.setEnabled(false);
Menu more=new Menu("More");
helpmenu.add(more);
more.add("commands");
more.add("about");
f.setSize(200,200);
f.setVisible(true);
}
}

/*******Menu Events with frame*********/


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

public class MainWindow5 extends Frame implements ActionListener


{
public MainWindow5()
{
super("Menu Window");
setSize(400, 400);
Menu file=new Menu("File");
MenuItem open=new MenuItem("Open");
MenuItem close=new MenuItem("Close");
MenuItem exit=new MenuItem("Exit");

file.add(open);
file.add(close);
file.add(exit);

MenuBar mb = new MenuBar();


mb.add(file);
setMenuBar(mb);

open.addActionListener(this);
close.addActionListener(this);
exit.addActionListener(this);

addWindowListener(new WindowAdapter()
{

114
public void windowClosing(WindowEvent e)
{
System.exit(1);
}
});
}

public void actionPerformed(ActionEvent e)


{
String item = e.getActionCommand();
if (item.equals("Exit"))
System.exit(1);
else
System.out.println("Selected FileMenu " + item);
}

public static void main(String args[])


{
MainWindow5 w = new MainWindow5();
w.setVisible(true);
}
}

/*******Menu Demo with Applet ******/


import java.awt.*;
import java.applet.*;
//<applet code=withapplet width=500 height=500></applet>
class form extends Frame
{
MenuBar mb;
Menu mnufile;

form()
{
mb=new MenuBar();
mnufile=new Menu("File");
MenuItem open=new MenuItem("Open");
MenuItem save=new MenuItem("Save");
MenuItem close=new MenuItem("Close");

mnufile.add(open);
mnufile.add(save);
mnufile.add(close);
mb.add(mnufile);
setMenuBar(mb);
setSize(200,200);

115
setVisible(true);
}
}
public class withapplet extends Applet
{
public void init()
{
form obj=new form();
}
}

/*******Menu Demo with Applet complete program ******/

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=menudemo width=250 height=250></applet>*/

class menuframe extends Frame


{
String msg="";
CheckboxMenuItem debug,test;

menuframe(String title)
{
super(title);
MenuBar mbar=new MenuBar();
setMenuBar(mbar);

Menu file=new Menu("File");


MenuItem item1,item2,item3,item4,item5;

file.add(item1=new MenuItem("New..."));
file.add(item2=new MenuItem("Open..."));
file.add(item3=new MenuItem("Close..."));
file.add(item4=new MenuItem("-"));
file.add(item5=new MenuItem("Quit..."));
mbar.add(file);

Menu edit=new Menu("Edit");


MenuItem item6,item7,item8,item9;

edit.add(item6=new MenuItem("Cut"));
edit.add(item7=new MenuItem("Copy"));
edit.add(item8=new MenuItem("Paste"));
edit.add(item9=new MenuItem("-"));

116
Menu sub=new Menu("Special");
MenuItem item10,item11,item12;
sub.add(item10=new MenuItem("First"));
sub.add(item11=new MenuItem("Second"));
sub.add(item12=new MenuItem("Third"));
edit.add(sub);

debug=new CheckboxMenuItem("Debug");
edit.add(debug);
test=new CheckboxMenuItem("Testing");
edit.add(test);

mbar.add(edit);

mymenuhandler handler=new mymenuhandler(this);

item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
item4.addActionListener(handler);
item5.addActionListener(handler);
item6.addActionListener(handler);
item7.addActionListener(handler);
item8.addActionListener(handler);
item9.addActionListener(handler);
item10.addActionListener(handler);
item11.addActionListener(handler);
item12.addActionListener(handler);

debug.addItemListener(handler);
test.addItemListener(handler);

mywindowadapter adapter=new mywindowadapter(this);


addWindowListener(adapter);
}

public void paint(Graphics g)


{
g.drawString(msg,10,200);
if(debug.getState())
g.drawString("Debug is on ", 10,220);
else
g.drawString("Debug is off", 10,220);

if(test.getState())

117
g.drawString("Testing is on",10,240);
else
g.drawString("Testing is off",10,240);
}
}
class mywindowadapter extends WindowAdapter
{
menuframe mframe;
public mywindowadapter(menuframe mf)
{
mframe=mf;
}

public void windowClosing(WindowEvent we)


{
mframe.setVisible(false);
}
}
class mymenuhandler implements ActionListener, ItemListener
{
menuframe mframe;
public mymenuhandler(menuframe m)
{
mframe=m;
}
public void actionPerformed(ActionEvent ae)
{
String msg="You Selected ";
String arg=(String)ae.getActionCommand();
if(arg.equals("New..."))
msg+="New";
else if(arg.equals("Open..."))
msg+="Open";
else if(arg.equals("Close..."))
msg+="Close";
else if(arg.equals("Quit..."))
msg+="Quit";
else if(arg.equals("Edit"))
msg+="Edit";
else if(arg.equals("Cut"))
msg+="Cut";
else if(arg.equals("Copy"))
msg+="Copy";
else if(arg.equals("Paste"))
msg+="Paste";
else if(arg.equals("First"))

118
msg+="First";
else if(arg.equals("Second"))
msg+="Second";
else if(arg.equals("Third"))
msg+="Third";
else if(arg.equals("Debug"))
msg+="Debug";
else if(arg.equals("Testing"))
msg+="Testing";

mframe.msg=msg;
mframe.repaint();
}

public void itemStateChanged(ItemEvent ie)


{
mframe.repaint();
}
}
public class menudemo extends Applet
{
Frame f;
public void init()
{
f=new menuframe("Menu Demo");
int width=Integer.parseInt(getParameter("width"));
int height=Integer.parseInt(getParameter("height"));
setSize(new Dimension(width, height));
f.setSize(width, height);
f.setVisible(true);
}

public void start()


{
f.setVisible(true);
}

public void stop()


{
f.setVisible(false);
}
}

119
Frame with Controls
/*Frame with buttons*/
import java.awt.*;
class fcontrols extends Frame
{
Frame f;
Button b1,b2,b3,b4,b5;

fcontrols()
{
f=new Frame("Frame with buttons");
b1=new Button("Ok");
b2=new Button("Cancel");
b3=new Button("First");
b4=new Button("Second");
b5=new Button("Center");
}

void apply()
{
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);

f.setSize(250,250);
f.setVisible(true);
}

public static void main(String args[])


{
fcontrols obj=new fcontrols();
obj.apply();
}
}

/*Frame with with flow layout*/


import java.awt.*;
class layout extends Frame
{
Frame f;
Button ok, cancel, third;

120
layout()
{
f=new Frame("Flow Layout Demo");
ok=new Button("Ok");
cancel=new Button("Cancel");
third=new Button("Third");

f.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
f.add(ok);
f.add(cancel);
f.add(third);

f.setSize(300,300);
f.setVisible(true);
}

public static void main(String args[])


{
layout obj=new layout();
}
}

/********Frame with Image*****/


import java.awt.*;
import java.awt.event.*;
class framewithimage extends Frame
{
Image img;

framewithimage()
{
super("Image Frame");
MediaTracker mt=new MediaTracker(this);
img=Toolkit.getDefaultToolkit().getImage("Penguins.jpg");
//img=Toolkit.getDefaultToolkit().getImage("C:\\Users\\Public\\Pictures\\Sample
Pictures\\Penguins.jpg");
mt.addImage(img,0);
setSize(400,400);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
dispose();
}
});

121
}

public void update(Graphics g)


{
paint(g);
}

public void paint(Graphics g)


{
if(img!=null)
g.drawImage(img,10,20,this);
else
g.clearRect(0,0, getSize().width, getSize().height);
}

public static void main(String args[])


{
framewithimage obj=new framewithimage();
}
}

/**Frame with Event*/


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

public class events implements ActionListener


{
Frame f;
Button b;

events()
{
f=new Frame("Events Test");
b=new Button("Press Me");
b.setActionCommand("ButtonPressed");
}

public void launch()


{
b.addActionListener(this);
f.add(b, BorderLayout.CENTER);
f.setVisible(true);
}

public void actionPerformed(ActionEvent ae)


{

122
System.out.println("Action occured ");
System.out.println("Button's command is "+ae.getActionCommand());
}
public static void main(String args[])
{
events obj=new events();
obj.launch();
}
}

/*Frame with Events (Mouse, Key and window)*/


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

class framewithevents extends Frame


{
String keymsg="";
String mousemsg="";

public framewithevents()
{

addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke)
{
keymsg="Typed key "+ke.getKeyChar();
repaint();
}
});

addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
mousemsg="Mouse Pressed at "+me.getX()+" , "+me.getY();
repaint();
}
});

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);

123
}
});

public void paint(Graphics g)


{
g.drawString(keymsg,100,100);
g.drawString(mousemsg,80,80);
}

public static void main(String args[])


{
framewithevents obj=new framewithevents();
obj.setSize(new Dimension(300,200));
obj.setTitle("An Awt-Based Application");
obj.setVisible(true);
}
}

Frame with Applet


/*******create a child frame window from within an applet*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="frame" width=300 height=50></applet>*/
public class frame extends Applet
{
Frame f;
public void init()
{
f=new Frame("A fram window");
f.setSize(250,250);
f.setVisible(true);
}
public void paint(Graphics g)
{
g.drawString("This is in applet window ",10,20);
}}

/*******create a child frame window from within an applet with full functionality*/
import java.awt.*;
import java.awt.event.*;

124
import java.applet.*;
//<applet code=framewithapplet width=500 height=500></applet>
public class framewithapplet extends Applet
{
Frame f;
String keymsg="";
String mousemsg="";

public void init()


{
f=new Frame();
f.setSize(new Dimension(300,200));
f.setTitle("Frame with event within applet");

f.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke)
{
keymsg="Typed key "+ke.getKeyChar();
repaint();
}
});

f.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
mousemsg="Mouse Pressed at "+me.getX()+" , "+me.getY();
repaint();
}
});

f.setVisible(true);
}

public void paint(Graphics g)


{
g.drawString(keymsg,100,100);
g.drawString(mousemsg,80,80);
}
}

/************************how to create window frame*******************/


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

125
import java.applet.*;
public class menudemo extends Applet
{
Frame f;
public void init()
{
f=new Frame("Menu Demo");
int width=Integer.parseInt(getParameter("width"));
int height=Integer.parseInt(getParameter("height"));

setSize(new Dimension(width,height));
f.setSize(width,height);
f.setVisible(true);
}
}
/* <applet code=menudemo.class width=600 height=1000> </applet> */

Creating a Frame Window in an Applet


/*creating a simple frame by applet*/f
import java.applet.*;
import java.awt.*;
public class appletframe extends Applet
{
Frame f;
public void init()
{
f=new Frame("Demo Frame By applet");
f.setSize(250,250);
f.setVisible(true);
}
public void paint(Graphics g)
{
g.drawString("This is in applet window ",10,20);
}
}
/*<applet code=appletframe width=500 height=500></applet>*/

/*******create a child frame window from within an applet*/


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="appletframe" width=300 height=50></applet>*/
class sampleframe extends Frame
{
sampleframe(String title)
{

126
super(title);
mywindowadapter adp=new mywindowadapter(this);
addWindowListener(adp);
}
public void paint(Graphics g)
{
g.drawString("This is in fram window", 10,40);
}
}
class mywindowadapter extends WindowAdapter
{
sampleframe samp;

public mywindowadapter(sampleframe sample)


{
samp=sample;
}
public void windowClosing(WindowEvent e)
{
samp.setVisible(false);
}
}
public class appletframe extends Applet
{
Frame f;
public void init()
{
f=new sampleframe("A fram window");
f.setSize(250,250);
f.setVisible(true);
}
public void paint(Graphics g)
{
g.drawString("This is in applet window ",10,20);
}}

/* Handle mouse events in both child and applet windows*/


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="windowevents" width=300 height=50></applet>*/
class sampleframe extends Frame
{
String msg="";
int x=10,y=40;
int movx=0, movy=0;

127
sampleframe(String title)
{
super(title);
/***************Window Closing******************/
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
setVisible(false);
}
});

/**************Mouse Motion****************/
addMouseMotionListener(new MouseAdapter()
{
public void mouseDragged(MouseEvent me)
{
x=me.getX();
y=me.getY();
movx=me.getX();
movy=me.getY();
msg="*";
repaint();
}
public void mouseMoved(MouseEvent me)
{
movx=me.getX();
movy=me.getY();
repaint(0,0,100,60);
}
});

/*****************Mouse Listener********************/
addMouseListener(new MouseAdapter()
{
public void mouseEntered(MouseEvent me)
{
x=10;
y=54;
msg="Mouse just entered child";
repaint();
}
public void mouseExited(MouseEvent me)
{
x=10;

128
y=54;
msg="Mouse just left child window";
repaint();
}
public void mousePressed(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="Down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="Up";
repaint();
}
});
}//constructor close

public void paint(Graphics g)


{
g.drawString(msg,x,y);
g.drawString("Mouse at "+movx+", "+movy,10,40);
}
}
public class windowevents extends Applet
{
sampleframe f;
String msg="";
int x=0,y=10;
int movx=0, movy=0;

public void init()


{
f=new sampleframe("Handle Mouse Events");
f.setSize(300,200);
f.setVisible(true);

/**************Mouse Motion****************/
addMouseMotionListener(new MouseAdapter()
{
public void mouseDragged(MouseEvent me)
{
x=me.getX();

129
y=me.getY();
movx=me.getX();
movy=me.getY();
msg="*";
repaint();
}
public void mouseMoved(MouseEvent me)
{
movx=me.getX();
movy=me.getY();
repaint(0,0,100,60);
}
});

/*****************Mouse Listener********************/
addMouseListener(new MouseAdapter()
{
public void mouseEntered(MouseEvent me)
{
x=10;
y=54;
msg="Mouse just entered child";
repaint();
}
public void mouseExited(MouseEvent me)
{
x=10;
y=54;
msg="Mouse just left child window";
repaint();
}
public void mousePressed(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="Down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="Up";
repaint();
}
});

130
}

public void paint(Graphics g)


{
g.drawString(msg,x,y);
g.drawString("Mouse At "+movx+", "+movy,0,10);
}
}

Dialog Boxes
/*File Dialog Box*/
import java.awt.*;
import java.awt.event.*;

class filedialog extends Frame


{
public static void main(String args[])
{
Frame f=new Frame("File Dialog ");
f.setVisible(true);
f.setSize(200,200);
FileDialog file=new FileDialog(f, "File Dialog");
file.setVisible(true);
}
}

/*File Dialog Box with file menu*/


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

class filedialog2 extends Frame implements ActionListener


{
Frame f;
filedialog2()
{
MenuBar mb=new MenuBar();
Menu file=new Menu("File");
MenuItem open=new MenuItem("Open");
MenuItem close=new MenuItem("Close");

131
file.add(open);
file.add(close);
mb.add(file);
open.addActionListener(this);
close.addActionListener(this);

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

f=new Frame("File Dialog ");


f.setVisible(true);
f.setSize(200,200);
f.setMenuBar(mb);
}

public void actionPerformed(ActionEvent ae)


{
String s=ae.getActionCommand();
if(s.equals("Open"))
{
FileDialog file=new FileDialog(f,"Open File Dialog");
file.setVisible(true);
}
else if(s.equals("Close"))
{
System.exit(1);
}
}

public static void main(String args[])


{
filedialog2 obj=new filedialog2();
}
}

/****************Menu Demo ******/


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=dialogdemo width=250 height=250></applet>*/

132
class sampledialog extends Dialog implements ActionListener
{
sampledialog(Frame parent, String title)
{
super(parent, title, false);
setLayout(new FlowLayout());
setSize(300,200);

add(new Label("Press This Button"));


Button b;
add(b=new Button("Cancel"));
b.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
dispose();
}

public void paint(Graphics g)


{
g.drawString("This is in the dialog box",10,70);
}
}
class menuframe extends Frame
{
String msg="";
CheckboxMenuItem debug, test;
menuframe(String title)
{
super(title);
M enuBar mbar=new MenuBar();
setMenuBar(mbar);

Menu file=new Menu("File");


MenuItem item1,item2,item3,item4,item5;

file.add(item1=new MenuItem("New..."));
file.add(item2=new MenuItem("Open..."));
file.add(item3=new MenuItem("Close..."));
file.add(item4=new MenuItem("-"));
file.add(item5=new MenuItem("Quit..."));
mbar.add(file);

Menu edit=new Menu("Edit");

133
MenuItem item6,item7,item8,item9;

edit.add(item6=new MenuItem("Cut"));
edit.add(item7=new MenuItem("Copy"));
edit.add(item8=new MenuItem("Paste"));
edit.add(item9=new MenuItem("-"));

Menu sub=new Menu("Special");


MenuItem item10,item11,item12;
sub.add(item10=new MenuItem("First"));
sub.add(item11=new MenuItem("Second"));
sub.add(item12=new MenuItem("Third"));
edit.add(sub);

debug=new CheckboxMenuItem("Debug");
edit.add(debug);
test=new CheckboxMenuItem("Testing");
edit.add(test);

mbar.add(edit);

mymenuhandler handler=new mymenuhandler(this);

item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
item4.addActionListener(handler);
item5.addActionListener(handler);
item6.addActionListener(handler);
item7.addActionListener(handler);
item8.addActionListener(handler);
item9.addActionListener(handler);
item10.addActionListener(handler);
item11.addActionListener(handler);
item12.addActionListener(handler);

debug.addItemListener(handler);
test.addItemListener(handler);

mywindowadapter adapter=new mywindowadapter(this);


addWindowListener(adapter);
}

public void paint(Graphics g)


{
g.drawString(msg,10,200);

134
if(debug.getState())
g.drawString("Debug is on ", 10,220);
else
g.drawString("Debug is off", 10,220);

if(test.getState())
g.drawString("Testing is on",10,240);
else
g.drawString("Testing is off",10,240);
}
}
class mywindowadapter extends WindowAdapter
{
menuframe mframe;
public mywindowadapter(menuframe mf)
{
mframe=mf;
}

public void windowClosing(WindowEvent we)


{
mframe.setVisible(false);
}
}
class mymenuhandler implements ActionListener, ItemListener
{
menuframe mframe;

public mymenuhandler(menuframe m)
{
mframe=m;
}
public void actionPerformed(ActionEvent ae)
{
String msg="You Selected ";
String arg=(String)ae.getActionCommand();
if(arg.equals("New..."))
{
msg+="New";
sampledialog d=new sampledialog(mframe, "New Dialog Box");
d.setVisible(true);
}
else if(arg.equals("Open..."))
msg+="Open";
else if(arg.equals("Close..."))
msg+="Close";

135
else if(arg.equals("Quit..."))
msg+="Quit";
else if(arg.equals("Edit"))
msg+="Edit";
else if(arg.equals("Cut"))
msg+="Cut";
else if(arg.equals("Copy"))
msg+="Copy";
else if(arg.equals("Paste"))
msg+="Paste";
else if(arg.equals("First"))
msg+="First";
else if(arg.equals("Second"))
msg+="Second";
else if(arg.equals("Third"))
msg+="Third";
else if(arg.equals("Debug"))
msg+="Debug";
else if(arg.equals("Testing"))
msg+="Testing";

mframe.msg=msg;
mframe.repaint();
}

public void itemStateChanged(ItemEvent ie)


{
mframe.repaint();
}
}
public class dialogdemo extends Applet
{
Frame f;
public void init()
{
f=new menuframe("Menu Demo");
int width=Integer.parseInt(getParameter("width"));
int height=Integer.parseInt(getParameter("height"));
setSize(new Dimension(width, height));
f.setSize(width, height);
f.setVisible(true);
}

public void start()


{
f.setVisible(true);

136
}

public void stop()


{
f.setVisible(false);
}
}
File Dialog: Java provides a built in dialog box that lets the user specify a file. That is
known as file dialog. It is standard file dialog box displayed by operating system.
FileDialog provides these constructors.

FileDialog(Frame parent, String boxName)


FileDialog(Frame parent, String boxName, int how)
FileDialog(Frame parent)

Here parent is the owner of dialog box, and boxName is the name displayed in the box’s
Title bar. If boxName is omitted then the title of the file dialog box is empty. If how is
FileDialog.LOAD, then the box is selecting a file for reading. If how is
FileDialog.SAVE, the box is selecting a file for writing. The third constructor creates a
dialog box for selecting a file for reading. FileDialog() provides methods that allow you
to determine the name of the file and its path as selected by the user. Here are two
example:

String getDirectory()
String getFile()

/*********File dialog2 demo (complicated method) ****/


import java.awt.*;
import java.awt.event.*;
class sampleframe extends Frame
{
sampleframe(String title)
{
super(title);
mywindowadapter adp=new mywindowadapter(this);
addWindowListener(adp);
}
}
class mywindowadapter extends WindowAdapter
{
sampleframe frame;
public mywindowadapter(sampleframe s)
{
frame=s;
}

137
public void windowClosing(WindowEvent we)
{
frame.setVisible(false);
}
}
class filedialog2
{
public static void main(String args[])
{
Frame f=new sampleframe("File Dialog demo");
f.setVisible(true);
f.setSize(100,100);
FileDialog fd=new FileDialog(f, "File Dialog");
//FileDialog fd=new FileDialog(f, "File Dialog",FileDialog.LOAD);
//FileDialog fd=new FileDialog(f, "File Dialog",FileDialog.SAVE);
//FileDialog fd=new FileDialog(f);
fd.setVisible(true);
}
}

/*********File dialog demo (Simple and correct method)****/


import java.awt.*;
import java.awt.event.*;
class filedialog extends Frame implements ActionListener
{
Button b;
filedialog(String title)
{
super(title);
b=new Button("Close");
b.addActionListener(this);
setLayout(new FlowLayout());
add(b);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b)
System.exit(0);
}
public static void main(String args[])
{
filedialog f=new filedialog("File Dialog Demo");
f.setVisible(true);
f.setSize(500,500);
//FileDialog fd=new FileDialog(f, "File Dialog");
FileDialog fd=new FileDialog(f, "File Dialog",FileDialog.LOAD);

138
//FileDialog fd=new FileDialog(f, "File Dialog",FileDialog.SAVE);
//FileDialog fd=new FileDialog(f);
fd.setVisible(true);
}
}

/********creating a button by extending button class**/


/*<applet code = buttondemo2 width=200 height=100></applet>*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class buttondemo2 extends Applet
{
mybutton b;
static int i=0;
public void init()
{
b=new mybutton("Test Button");
add(b);
}

class mybutton extends Button


{
public mybutton(String label)
{
super(label);
enableEvents(AWTEvent.ACTION_EVENT_MASK);
}
protected void processActionEvent(ActionEvent ae)
{
showStatus("action event :"+i++);
super.processActionEvent(ae);
}
}
}

139
Fonts
The AWT supports multiple type fonts. Fonts have a family name, a logical name, and a
face name. The family name is the general name of the font, such as Courier. The logical
name specifies a category of font, such as Monospaced. The face specifies a specific font,
such Courier Italic. Fonts are encapsulated by the Font class.

Determining the Available Fonts: To obtain the information about the fonts available
on our machine we can use the getAvailableFontFamilyNames() method defined by the
GraphicsEnvironment class.
String getAvailableFontFamilyNames() [];
This method returns an array of strings that contain the names of the available font
families. In addition getAllFonts() method is defined by the GraphicsEnvironment class.
Font getAllFonts() [];
This method returns an array of Font objects for all of the available fonts. Since these
methods are members of GraphicsEnvironment, you need a GraphicsEnvironment
reference to call them. You can’t obtain this reference by using the
getLocalGraphicsEnvironment() static method, which is defined by
GraphicsEnvironment.
static GraphicsEnvironment getLocalGraphicsEnvironment()

example/*********This program will display the all the system fonts**/


import java.applet.*;
import java.awt.*;
//<applet code=showfont width=500 height=500></applet>
public class showfont extends Applet
{
TextArea txt;
public void init()
{
txt=new TextArea();
String FontList[];
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
FontList = ge.getAvailableFontFamilyNames();
for(int i=0;i<FontList.length;i++)
txt.append(FontList[i]+"\n");

140
add(txt);
}
}

/*******************************************/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code=showfonts width=500 height=500></applet>

public class showfonts extends Applet implements ItemListener


{
Choice c;
String FontList[];
String s="";
Font f;
public void init()
{
c=new Choice();

GraphicsEnvironment
ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
FontList=ge.getAvailableFontFamilyNames();
for(int i=0;i<FontList.length;i++)
c.add(FontList[i]);
add(c);
c.addItemListener(this);
}

public void itemStateChanged(ItemEvent ie)


{
s=c.getSelectedItem();
f=new Font(s,Font.PLAIN,30);
repaint();
}

public void paint(Graphics g)


{
g.setFont(f);
g.drawString(s,200,200);
}
}

Creating and selecting a Font: To select a Font, you must first construct a Font object
that describes that font.
Font(String fontName, int FontStyle, int pointSize)

141
Here FontName specifies the name of the desired font. The name can be specified using
either the logical or face name. Dialog is the default font of the system and it is the font
that is used by the systems dialog boxes. Font style specifies the three constants:
Font.PLAIN, Font.BOLD and Font.ITALIC. To combine styles use like this:

Font.BOLD|Font.ITALIC.

The pointSize is used to specified the size of Font. To use a font we must select it using
setFont() method which is defined by Component.

Void setFont(Font fontobj)

Fontobj is the font object that contain desired font.

Example: /****This program will display different fonts on mouse Click***/


/*<applet code=samplefonts.class width=100 height=200></applet>*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class samplefonts extends Applet
{
int next=0;
Font f;
String msg;
public void init()
{
f=new Font("Dialog", Font.PLAIN, 12);
msg="Dialog";
setFont(f);
addMouseListener(new mymouseadapter(this));
}

public void paint(Graphics g)


{
g.drawString(msg,4,20);
}
}
class mymouseadapter extends MouseAdapter
{
samplefonts samp;

public mymouseadapter(samplefonts s)
{
samp=s;
}

142
public void mousePressed(MouseEvent me)
{
samp.next++;
switch(samp.next)
{
case 0:
samp.f=new Font("Dialog", Font.PLAIN, 12);
samp.msg="Dialog";
break;
case 1:
samp.f=new Font("DialogInput ",Font.PLAIN, 12);
samp.msg="Dialog";
break;
case 2:
samp.f=new Font("SansSerif",Font.PLAIN, 12);
samp.msg="DialogInput";
break;
case 3:
samp.f=new Font("Serif", Font.PLAIN, 12);
samp.msg="Serif";
break;
case 4:
samp.f=new Font("Monospaced", Font.PLAIN, 12);
samp.msg="Monospaced";
break;
}

if(samp.next==4)
samp.next=-1;

samp.setFont(samp.f);
samp.repaint();
}
}

Obtaining Font Information: To obtain the information of currently selected font, we


must first get the current font by getFont() method, defined by Graphics class.
Font getFont()
After getting currently selected font, we can retrieve information by applying various
methods defined by Font class.

Font Code Font Style


0 PLAIN
1 BOLD
2 ITALIC
3 BOLD+ITALIC

143
Example: /*******This program will return font information****/
import java.applet.*;
import java.awt.*;
//<applet code=fontinfo width=800 height=500></applet>
public class fontinfo extends Applet
{
public void paint(Graphics g)
{
//Font ff=new Font("Times New Roman",Font.BOLD+Font.ITALIC,25); //3
//Font ff=new Font("Times New Roman",Font.BOLD,25);//1
//Font ff=new Font("Times New Roman",Font.ITALIC,25);//2
//Font ff=new Font("Times New Roman",Font.PLAIN,25);//0
Font ff=new Font("Times New Roman",2+1,25); //(2+1) is the code for bold + italic
g.setFont(ff);
Font f=g.getFont();
String fontname=f.getName();
String fontfamily=f.getFamily();
int fontsize=f.getSize();
int fontstyle=f.getStyle();

String msg="Family : "+fontfamily;


msg+=" , Font : "+fontname;
msg+=" , Size : "+fontsize;
msg+=" , Style : "+fontstyle;

/*if(fontstyle==Font.BOLD)
msg+="Bold";*/
g.drawString(msg,4,16);
}
}

Managing Text output using FontMetrics: As we know java supports a number of


fonts. For most fonts characters are not all the same dimension. The height of each
character, the length of descenders and the amount of space between horizontal lines vary
from font to font. Further, the point size (size) of a font can be changed. So to deal with a
font in applet we have to look all the aspects like we should know how tall the font is and
how many pixels are needed between lines. To fill all these needs, the AWT includes the
FontMetrics class, which encapsulates various information about a font. For example:

Height-> The top to bottom size of the tallest character in the font. (sum of leading space
+ ascent + descent)
Baseline-> The line that the bottoms of characters are aligned to.
Ascent-> The distance from the baseline to the top of a character.
Descent-> The distance from the baseline to the bottom of a character.

144
Leading-> The distance between the bottom of one line of text and the top of the next
line.

Displaying Multiple line of text: The most common use of FontMatrix class is to
determine the spacing between lines of text. The second most common use is to
determine the length of a string that is being displayed. So to determine the spacing
between lines, you can use the value returned by getLeading(). To determine the total
height of the font, add the value returned by getAscent() to the value returned by
getDescent(). Then we can use these values to position each line of text that is to output.
To start output at the end of previous output on the same line, we must the know the
length of each string in pixels that we display. To obtain string length we can call
stringWidth() method.

Example:/*********Displaying multiple line of text**/


/*<applet code=multiline.class width=800 height=800></applet>*/
import java.applet.*;
import java.awt.*;
public class multiline extends Applet
{
int curx=0, cury=0;
int a=200;
int b=80;

public void init()


{
Font f=new Font("SansSerif", Font.PLAIN, 12);
setFont(f);
}

public void paint(Graphics g)


{
FontMetrics fm=g.getFontMetrics();

nextLine("This is on line one. ",g);


nextLine("This is on line two. ",g);
sameLine("This is on same line.",g);
sameLine("This too.",g);
nextLine("This is on line three. ",g);
}

void nextLine(String s, Graphics g)


{
FontMetrics fm=g.getFontMetrics();
cury+=fm.getHeight(); //it will return total height of string(leading+ascent+descent)
curx=0;
g.drawString(s, curx, cury);

145
curx=fm.stringWidth(s); //it will return total length of string in pixel
g.drawString("String width = "+String.valueOf(curx)+" , "+"String height =
"+String.valueOf(cury),b,a); //This statement is to represent the width and height of string
a=a+50;
}

void sameLine(String s, Graphics g)


{
FontMetrics fm=g.getFontMetrics();
g.drawString(s, curx, cury);
curx+=fm.stringWidth(s);
g.drawString("String width = "+String.valueOf(curx)+" , "+"String height =
"+String.valueOf(cury),b,a); //This statement is to represent the width and height of string
a=a+50;
}
}

Centering Text: This example centers text, left to right, top to bottom, in a window. It
obtains the ascent, descent, and width of the string and computes the position at which it
must be displayed to be centered.
/**************Center text example******/
import java.applet.*;
import java.awt.*;
/*<applet code=centertext width=200 height=100></applet>*/
public class centertext extends Applet
{
final Font f=new Font("SansSerif",Font.BOLD, 18);

public void paint(Graphics g)


{
Dimension d=this.getSize();
g.setColor(Color.white);
g.fillRect(0,0,d.width,d.height);
g.setColor(Color.black);
g.setFont(f);
drawCenteredString("This is centered",d.width,d.height,g);
g.drawString("Width = "+String.valueOf(d.width)+" Height =
"+String.valueOf(d.height),50,50);//it will display the width and height of web page
}

public void drawCenteredString(String s, int w, int h, Graphics g)


{
FontMetrics fm=g.getFontMetrics();
int x=(w-fm.stringWidth(s))/2;
int y=(fm.getAscent()+(h-(fm.getAscent()+fm.getDescent()))/2);
g.drawString(s,x,y);

146
g.drawString(String.valueOf(fm.getAscent())+" ,
"+String.valueOf(fm.getDescent()),15,15);
}
}

Multiline Text Alignment: The string to be justified is broken into individual words. For
each word, the program keeps track of its length in the current font and automatically
advances to the next line if the word will not fit on the current line. Each completed click
the mouse in the applet’s window, the alignment style in changed.

/**********Multiline Text Alignment*********/


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

/* <title>Text Layout</title>
<applet code="Textlayout" width=200 height=200>
<param name="text" value="output to a java window is actually quite easy.
As you have seen, the AWT provides support for
font, colors, text, and graphics. <P> of course,
you must effectively utilize these items
if you are to achieve professional results.">
<param name="fontname" value="Serif">
<param name="fontsize" value="14">
</applet>
*/

public class Textlayout extends Applet


{
final int LEFT=0, RIGHT=1, CENTER=2, LEFTRIGHT=3;
int align;
Dimension d;
Font f;
FontMetrics fm;
int fontsize;
int fh,b1;
int space;
String text;
public void init()
{
setBackground(Color.white);
text=getParameter("text");
try
{
fontsize=Integer.parseInt(getParameter("fontsize"));

147
}
catch(NumberFormatException e)
{
fontsize=4;
}
align=LEFT;
addMouseListener(new mymouseadapter(this));
}

public void paint(Graphics g)


{
update(g);
}

public void update(Graphics g)


{
d=getSize();
g.setColor(getBackground());
g.fillRect(0,0,d.width,d.height);
if(f==null)
f=new Font(getParameter("fontname"), Font.PLAIN, fontsize);
g.setFont(f);
if(fm==null)
{
fm=g.getFontMetrics();
b1=fm.getAscent();
fh=b1+fm.getDescent();
space=fm.stringWidth(" ");
}
g.setColor(Color.black);
StringTokenizer st=new StringTokenizer(text);
int x=0;
int nextx;
int y=0;
String word,sp;
int wordcount=0;
String line=" ";
while(st.hasMoreTokens())
{
word=st.nextToken();
if(word.equals("<p>"))
{
drawString(g, line, wordcount, fm.stringWidth(line), y+b1);
line=" ";
wordcount=0;
x=0;

148
y=y+(fh*2);
}
else
{
int w=fm.stringWidth(word);
if((nextx=(x+space+w))>d.width)
{
drawString(g, line, wordcount, fm.stringWidth(line), y+b1);
line=" ";
wordcount=0;
x=0;
y=y+fh;
}
if(x!=0)
{ sp=" ";}
else
{sp=" ";}
line=line+sp+word;
x=x+space+w;
wordcount++;
}
}
drawString(g, line, wordcount, fm.stringWidth(line), y+b1);
}

public void drawString(Graphics g, String line, int wc, int linew, int y)
{
switch(align)
{
case LEFT:
g.drawString(line,0,y);
break;
case RIGHT:
g.drawString(line, d.width-linew, y);
break;
case CENTER:
g.drawString(line, (d.width-linew)/2, y);
break;
case LEFTRIGHT:
if(linew<(int)(d.width*.75))
{
g.drawString(line, 0, y);
}
else
{
int toFill=(int) ((d.width-linew)/wc);

149
int nudge=d.width-linew-(toFill*wc);
int s=fm.stringWidth(" ");
StringTokenizer st=new StringTokenizer(line);
int x=0;
while(st.hasMoreTokens())
{
String word=st.nextToken();
g.drawString(word, x, y);
if(nudge>0)
{
x=x+fm.stringWidth(word)+space+toFill+1;
nudge--;
}
else
{
x=x+fm.stringWidth(word)+space+toFill;
}
}
}
break;
}
}
}
class mymouseadapter extends MouseAdapter
{
Textlayout t1;
public mymouseadapter(Textlayout t)
{
t1=t;
}
public void mouseClicked(MouseEvent me)
{
t1.align=(t1.align+1)%4;
t1.repaint();
}}

150
Animations
/***********************Animation Line**********************/
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.*;
/*<applet code=AnimationLine width=900 height=900></applet>*/
public class AnimationLine extends JApplet
{
public void init()
{
getContentPane().add(new AnimationLinePanel());
setSize(800,500);
}
public class AnimationLinePanel extends JPanel
{
int linex,linem = 1;
public AnimationLinePanel()
{
setBackground(Color.black);
}
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.setColor(Color.red);
page.drawLine(linem,200,310,400);
if(linex > 500)
{

151
linem = -500;
page.setColor(Color.green);
page.drawLine(linem,200,310,400);
}
if(linex < 0)
{
linem = 600;
page.setColor(Color.yellow);
page.drawLine(linem,200,310,400);
}
linex += linem;
repaint();
}
}
}

//**blinking lights animation **//


import java.awt.*;
import java.applet.*;
public class animation4 extends Applet
{
int i;
int x=0,y=0;
public void paint(Graphics g)
{
int j=1;
while(j<=10)
{
try{Thread.sleep(15);}catch(Exception e){}
for(i=1;i<=15;i++)
{
if(j==2)
{
g.setColor(Color.cyan);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;

152
}
}
else
{
g.setColor(Color.red);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}
}
}

try{Thread.sleep(15);}catch(Exception e){}
for(int i=1;i<=15;i++)
{
if(j==3)
{
g.setColor(Color.black);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}
}

else
{
g.setColor(Color.blue);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}
}
}

try{Thread.sleep(15);}catch(Exception e){}
for(i=1;i<=15;i++)
{
if(j==4)

153
{
g.setColor(Color.green);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}
}
else
{
g.setColor(Color.pink);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}
}
}
try{Thread.sleep(15);}catch(Exception e){}
for(i=1;i<=15;i++)
{
if(j==5)
{
g.setColor(Color.gray);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}
}
g.setColor(Color.magenta);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}
}

try{Thread.sleep(15);}catch(Exception e){}

154
for(i=1;i<=15;i++)
{
if(j==6)
{
g.setColor(Color.pink);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}
}
g.setColor(Color.green);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}
}

try{Thread.sleep(15);}catch(Exception e){}
for(i=1;i<=15;i++)
{
if(j==7)
{
g.setColor(Color.magenta);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}
}
g.setColor(Color.black);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}
}

155
try{Thread.sleep(15);}catch(Exception e){}
for(i=1;i<=15;i++)
{
if(j==8)
{
g.setColor(Color.blue);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}

}
g.setColor(Color.cyan);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}
}

try{Thread.sleep(15);}catch(Exception e){}
for(i=1;i<=15;i++)
{
if(j==9)
{
g.setColor(Color.black);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}

}
g.setColor(Color.red);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;

156
}
}

try{Thread.sleep(15);}catch(Exception e){}
for(i=1;i<=15;i++)
{
if(j==10)
{
g.setColor(Color.red);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}

}
g.setColor(Color.yellow);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=y+70;
}
}

try{Thread.sleep(15);}catch(Exception e){}
for(i=1;i<=15;i++)
{
g.setColor(Color.gray);
g.fillOval(x,y,50,50);
x=x+70;
if(x>1020)
{
x=0;
y=0;
}
}
j++;
x=0;
y=0;
if(j==10)
j=1;

157
}
}
/* <applet code=animation4.class width=1020 height=669>
</applet> */

/* TEXT screen saver */


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

public class animation extends Applet implements


ActionListener
{

TextField text=new TextField(20);


TextField red=new TextField(20);
TextField gr=new TextField(20);
TextField blue=new TextField(20);
Button b1=new Button("Apply");
String str="Hello";
int size=50;
Font f;
boolean inc=true;
int r,g,b;
Color fcolor;

public void init()


{
add(new Label("Enter text to animate here"));
add(text);
add(new Label("Enter value for Red Color here "));
add(red);
red.setText("0");
add(new Label("Enter value for Green Color here"));
add(gr);
gr.setText("0");
add(new Label("Enter value for Blue Color here "));
add(blue);
blue.setText("0");
add(b1);
b1.addActionListener(this);
}

public void actionPerformed(ActionEvent e)

158
{
if(e.getSource()==b1)
{
str=text.getText();
if(str==" ")
str="Hello";
r=Integer.parseInt(red.getText());
g=Integer.parseInt(gr.getText());
b=Integer.parseInt(blue.getText());
fcolor=new Color(r,g,b);
repaint();
}
}
public void paint(Graphics g)
{

setBackground(Color.green);

f=new Font("Comic",Font.ITALIC,size);
g.setFont(f);
g.setColor(fcolor);
g.setColor(Color.red);

g.drawString(str,250,335);

try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if(inc==true)
{
size += 10;
if(size==300)
inc=false;
}
else
{
size -= 10;
if(size==10)
inc=true;
}

repaint();

159
}
}

/**************Text Screen Saver***********************/


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
//<applet code=centeredtext width=1360 height=663></applet>
public class centeredtext extends Applet
{
Font f=new Font("SansSerif", Font.BOLD,18);
int align=-1;

public void paint(Graphics g)


{
Dimension d=this.getSize();
g.setColor(Color.red);
g.fillRect(0,0,d.width,d.height);
g.setColor(Color.black);
g.setFont(f);
int w=d.width;
int h=d.height;
String s;
FontMetrics fm=g.getFontMetrics();
int y=(h-fm.getLeading())/2;
for(int i=1;i<=4;i++)
{
s="This is Centered String";
try
{
Thread.sleep(500);
if(i==1)
{
g.drawString(s,0,y);
}
else if(i==2)
{
int x=(w-fm.stringWidth(s))/2;
g.drawString(s,x,30);
}
else if(i==3)
{
int x=(w-fm.stringWidth(s));
g.drawString(s,x,y);
}
else if(i==4)
{

160
int x=(w-fm.stringWidth(s))/2;
g.drawString(s,x,h-20);
}
repaint();
Thread.sleep(500);
}catch(Exception ex){}
}
}
}

/* <applet code=animation.class width=1020 height=669 >


</applet> */

/*Larg circle blinking */


import java.awt.*;
import java.applet.*;
public class animation2 extends Applet
{
int i=0;
public void paint(Graphics g)
{
if(i==1)
setBackground(Color.blue);
else if(i==2)
setBackground(Color.green);
else if(i==3)
setBackground(Color.cyan);
else if(i==4)
setBackground(Color.pink);
else if(i==5)
setBackground(Color.red);
else
i=1;

g.setColor(Color.red);
g.fillOval(400,250,300,300);
g.setColor(Color.blue);
g.fillOval(0,0,250,250);
g.setColor(Color.green);
g.fillOval(750,0,250,250);
g.setColor(Color.white);
g.fillOval(750,400,250,250);
g.setColor(Color.yellow);
g.fillOval(0,420,250,250);
try

161
{
Thread.sleep(500);
}
catch(Exception e){}
g.setColor(Color.blue);
g.fillOval(430,280,250,250);
g.setColor(Color.red);
g.fillOval(30,30,200,200);
g.setColor(Color.black);
g.fillOval(770,20,200,200);
g.setColor(Color.green);
g.fillOval(770,420,200,200);
g.setColor(Color.cyan);
g.fillOval(20,440,200,200);

try
{
Thread.sleep(500);
}
catch(Exception e){}
g.setColor(Color.pink);
g.fillOval(460,310,200,200);
g.setColor(Color.cyan);
g.fillOval(60,60,150,150);
g.setColor(Color.green);
g.fillOval(790,40,150,150);
g.setColor(Color.black);
g.fillOval(790,440,150,150);
g.setColor(Color.red);
g.fillOval(40,460,150,150);

try
{
Thread.sleep(500);
}
catch(Exception e){}
g.setColor(Color.green);
g.fillOval(490,340,150,150);
g.setColor(Color.blue);
g.fillOval(90,90,100,100);
g.setColor(Color.pink);
g.fillOval(820,60,100,100);
g.setColor(Color.white);
g.fillOval(820,460,100,100);
g.setColor(Color.yellow);
g.fillOval(60,490,100,100);

162
try
{
Thread.sleep(500);
}
catch(Exception e){}
g.setColor(Color.black);
g.fillOval(520,370,100,100);
g.fillOval(120,120,50,50);
g.fillOval(840,80,50,50);
g.fillOval(840,480,50,50);
g.fillOval(80,510,50,50);

try
{
Thread.sleep(500);
}
catch(Exception e){}
g.setColor(Color.white);
g.fillOval(550,400,50,50);
g.fillOval(150,150,20,20);
g.fillOval(860,100,25,25);
g.fillOval(860,500,25,25);
g.fillOval(100,530,25,25);

i++;

repaint();

}
}
/* <applet code=animation2.class width=1020 height=669>
</applet> */

Networking
Socket Overview
Java offers socket based communications which enable applications to view networking
as input to or output from files. A program can read from a socket or write to a socket just
as you read from a file or write to a file.

163
“ a socket is an identifier for a particular service on a particular node on a network. The
socket consists of a node address and a port number, which identifies the service. For
example port number 80 indicates a web server.
Clients and servers establish sockets and communicate via sockets. Sockets are the end
points of internet communication. Client create client sockets and connect them to server
sockets. Sockets are associate with a host address and a port address. The host address is
the IP address of the host where the client or server program is located. The port address
is the communication port used by the client or server program.

Java provides two type of sockets:


1. Stream socket 2. Datagram sockets
Stream socket: This socket is used to establish connection from process to another. By
this socket data from in continues stream till the connection is present. So stream socket
provides a connection oriented service. The protocol used for transmission is TCP
(Transmission Control Protocol).

Datagram Sockets: By this sockets individual packets of information are transmitted.


This is connectionless or unreliable mode of data transmission. The protocol use to
transmission is UDP (User Datagram Protocol). This protocol does not guarantee that
packet will arrive at the desitnition error-free. The packet may get lost or may arrive out
of order.

Reserve Socket: Certain port numbers are reserved for special applications. For example
port number 21 for FTP, 23 for Telnet, 80 for HTTP, 119 for netnews etc. infact port
numbers 0-1024 are reserve for very specific protocols. Only the rest of the port numbers
are available for general use.

Proxy Servers: Proxy servers act as secure getways to the internet for client computers.
They are transparent to client computers. This means that the user interacting with the
internet through a proxy server is not aware of the fact the a proxy server is handling the
requests. Similarly the web server receiving the request is unware of the fact that the
proxy server is sending the interpreted requests and not the client computers
“ a proxy server is a computer that can act on behalf of the client computers to request
content from the internet or intranet.”
Proxy servers can be used to secure private networks connected to the unsecure internet.
They monitor and manage network access, i.e. they act as a security agent for a private
network.
Advantages of using a proxy server include the following:
1. It provides a single, secure getway to manage.
2. It can provide different types of access to the internet as appropriate for each
group of users. For example debarring certain web sites from being viewed by
children.
3. It can monitor and track internet usage for each user.
4. Many users can share a single high speed internet connection. For example as
done in a cybercafé.

164
Internet addressing: A computer in a network is known as a node or host. Every host, in
a network has a hostname which uniquely indetifies it in a network. Every host in a
TCP/IP network is also assigned a host address. Further, the TCP/IP network to which the
host belongs has got a network address. The combination of the TCP/IP network address
and host address form the IP address.
An IP address is a numeric indetifier assigned to each machine on a TCP/IP network. It
designates the location of the device in the network.
“ an IP address is a software address, not a hardware address. The hardware address is
coded in the machine or on the network interface card.”
An IP address is made up of 32 bits of information. These bits are divided into four
sections containing one byte (8 bits) each. These section are reffered to as octets. There
are three methods for depicting an IP address:
1. Dotted-decimal, as in 130.57.30.56
2. Binary, as in 10000010.00111001.00011110.00111000
3. Hexadecimal, as in 82::39::1E::38
The 32 bit IP addressing is two level hierarchical addressing scheme. The first part is
designed as a network address and the other part of the address is designated as a node
address.

The node address uniquely identifies each machine on the network. This part of address
must be unique because it identifies a particular machine. In the sample IP address
130.57.30.56, the 30.56 is the node address.

The network address uniquely identifies each network. Evey machin on the same network
share the network address as part of it’s IP address. Example in IP address 130.57.30.56
the 130.57 is the network address.

Three classes for network address


Class A format
Network.Node.Node.Node

Class B format
Network.Network.Node.Node

Class C format
Network.Network.Network.Node

Domain Naming Services (DNS): Sun Microsystems developed the Domain Name
System (DNS) in the early 1980s as an easier way to keep track of addresses. The DNS
gives each computer on the net an internet address, or domain name, using easily
recognizable letters and words instead of numbers. The DNS establishes a hierarchy of
domains. At the top is the unnamed root domain called . (dot). This has a number of top
level domains. The top level domains are assigned organization-wise and country-wise.
Domain names in DNS describe organizational or geographical existence. They either
indicate the country or type of organization and sometimes further details.

165
These top level domains in turn have second level domains under them, which in turn can
have sub-sub domains and the hierarchy can thus go down and y levele further. For
example in the address doeacc.org.in, org forms the second level domain under in (i.e.
India) and doeacc is the sub-domain name under org. Domain names are case sensitive
DOEACC.ORG is not the same as doeACC.oRg.

Java and the NET


Java supports both TCP and UDP. While TCP provides a reliable, connection-oriented
service, UDP provides a simple, connectionless but faster datagram-oriented service. The
java.net package provides several classes and interfaces that support socket based client
server communication.

InetAddress: The InetAddress class represents a hostname and its IP address. The class
also provides the functionality to obtain the IP address for a given hostname. An
InetAddress object encapsulates both the numerical IP address and the domain name for
that address.
getByName() returns a reference to an InetAddress object.
getAllByName() returns array of InetAddress objects. (some host known by more than
one IP address)
getLocalHost() returns the InetAddress object that represent the local host.

Some method defined by InetAddress

getHostName() : It returns the host name that the invoking InetAddress object
represents.

getAddress() : It returns an array of the raw bytes of the address.

Equals() : compares two InetAddress objects.

toString() : prints out the host name and IP address in string format.

Factory Methods: Factory methods are static methods of a class that return an instance
of that class. For example the static methods getLocalHost(), getByName() and
getAllByName() are factory methods because they return an instance of the InetAddress
object.

First connect with internet to get Answer


/*****This program is to get Inet Addresses***/
import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);

166
Address = InetAddress.getByName("www.ymail.com");//first connect system with
internet then type a website name
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.google.com");//first connect
system with internet then type a website name
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}

************use of socket*************/
import java.net.*;
import java.io.*;

public class GreetingClient


{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName+ " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);

System.out.println("....");
out.writeUTF("Hello from "+ client.getLocalSocketAddress());
System.out.println("....");
InputStream inFromServer = client.getInputStream();
System.out.println("....");
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("....");
System.out.println("Server says " + in.readUTF());
System.out.println("....");
client.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}

167
TCP/IP Server Socket
The ServerSocket class is used to create servers that listen to either local or remote client
programs to connect to them on publish ports. Serversocket are different from normal
Sockets. When we create a ServerSocket, it will register itself with the system as having
an interest in client connections. The constructor for serversocket specifies the server’s
port number, i.e. the port on which it will accept connections. Alos one can specify the
queue length. The queue length tells the system as to how many client connections it can
leave pending before it should start refusing connection requests. The default length is
50.
The following are the three constructors of the serversocket class:
a. ServerSocket(int port): Creates an instance of the ServerSocket on the specified
port with default queue length of 50.
b. ServerSocket(int port, int len): Creates an instance of ServerSocket on the
specified port with a maximum queue length of len.
c. ServerSocket(int port, int len, InetAddress loc_add): Creates an instance of the
ServerSocket on the specified port with a maximum queue length of len. The
loc_add specifies the IP address to which this socket binds.

To run below two programs first we have to compile ChatServer program in one
command prompt window and then run it and at the same time open second command
like below shown image.

3. ChatServer Programe:

168
1. ChatServer Program
import java.io.*;
import java.net.*;

class ChatServer
{
ServerSocket ss;

ChatServer()throws Exception
{
ss = new ServerSocket(12345);
System.out.println("Server Ready....");
}

void service()throws Exception


{
while(true)
{
System.out.println("Waiting for a request...");
Socket s = ss.accept();
System.out.println("Request arrived...");

PrintWriter writer = new PrintWriter(s.getOutputStream(),true);


BufferedReader reader = new BufferedReader(new
InputStreamReader(s.getInputStream()));

writer.println("Welcome to Chat Server..");


writer.println("You can now send your messages....");
writer.println("Type \"quit\" to disconnect....");

while(true)
{
String str = reader.readLine();
System.out.println("Client : "+str);
if(str.equalsIgnoreCase("quit"))
break;
System.out.print("Server : ");
str = System.console().readLine();
writer.println(str);
}

s.close();
System.out.println("Request processed...");

169
}

public static void main(String args[])throws Exception


{
ChatServer s = new ChatServer();
s.service();
}

2. ChatClient Program:
import java.io.*;
import java.net.*;

class ChatClient
{
public static void main(String args[])throws Exception
{
Socket s = new Socket("localhost",12345);

PrintWriter writer = new PrintWriter(s.getOutputStream(),true);


BufferedReader reader = new BufferedReader(new
InputStreamReader(s.getInputStream()));

System.out.println(reader.readLine());
System.out.println(reader.readLine());
System.out.println(reader.readLine());

while(true)
{
System.out.print("Client : ");
String str = System.console().readLine();
writer.println(str);
if(str.equalsIgnoreCase("quit"))
break;
str = reader.readLine();
System.out.println("Server : "+str);
}

s.close();
}
}

170
/**********************Datagram Socket*****************/

---------------------------------Server-------------------------

import java.net.*;
import java.io.*;
class server1
{
DatagramSocket ds;
byte buffer[]=new byte[1024];

void Myserver() throws Exception


{
System.out.println("Server ready..");
ds=new DatagramSocket(888);

DataInputStream inm=new DataInputStream(System.in);

while(true)
{
DatagramPacket request = new DatagramPacket(buffer,buffer.length);
ds.receive(request);
System.out.println(new
String(request.getData(),0,request.getLength()));

System.out.println("Type Some message here");


InetAddress address=request.getAddress();
String str=inm.readLine();
buffer=str.getBytes();
request=new DatagramPacket(buffer,buffer.length);
DatagramPacket reply = new
DatagramPacket(request.getData(),request.getLength(),address,777);
ds.send(reply);
}
}
public static void main(String args[]) throws Exception
{
server1 obj=new server1();
obj.Myserver();
}
}

171
-------------------------------------Client-----------------------------

import java.net.*;
import java.io.*;
class client1
{
public static DatagramSocket ds;
byte buffer[]=new byte[1024];

void Myclient() throws Exception


{
DataInputStream in=new DataInputStream(System.in);
while(true)
{
System.out.println("Type Some Message");
String str=in.readLine();
buffer=str.getBytes();
DatagramPacket p=new
DatagramPacket(buffer,buffer.length,InetAddress.getLocalHost(),888);
ds.send(p);
buffer=new byte[1024];
DatagramPacket request = new
DatagramPacket(buffer,buffer.length);
ds.receive(request);
System.out.println(new
String(request.getData(),0,request.getLength()));
}

public static void main(String args[]) throws Exception


{
System.out.println("Client - Press CTRL+C to quit");
ds=new DatagramSocket(777);
client1 obj=new client1();
obj.Myclient();
}
}

********************Important Function*************************
DatagramSocket myServerSocket = new DatagramSocket(9000); // server
socket
byte[] sendData = new byte[message.length()]; // build msg
sendData = message.getBytes();
InetSocketAddress destSocketAddr = new

172
InetSocketAddress("1.2.3.4",9000); // destination socket addr
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, destSocketAddr); // make packet
myServerSocket.send(sendPacket);

1. EchoServer
import java.net.*;
import java.io.*;
class EchoServer {
public static void main(String[] args) throws IOException{
ServerSocket svr=new ServerSocket(2000);
System.out.println("Waiting for request......");
Socket clt=svr.accept();
System.out.println("Request accepted");
BufferedReader br=new BufferedReader(new
InputStreamReader(clt.getInputStream()));
while(true){
String st=br.readLine();
System.out.println("Sending data to the client....");
if(st.equals("exit")==true){
System.out.println("Connection With Client Is Lost....");
System.exit(1);
}
System.out.println(st);
PrintStream ps=new PrintStream(clt.getOutputStream());
ps.println(st);
}
}
}

2.EchoClient
import java.net.*;
import java.io.*;
class EchoClient {
public static void main(String[] args) throws IOException{
System.out.println("Sending request to server....");
Socket clt=new Socket("127.0.0.1",2000);
System.out.println("successfully connected....");
BufferedReader br1=new BufferedReader(new
InputStreamReader(System.in));
PrintStream ps=new PrintStream(clt.getOutputStream());
BufferedReader br2=new BufferedReader(new
InputStreamReader(clt.getInputStream()));

173
while(true){
System.out.println("<<<<<Input Data>>>>>");
String s=br1.readLine();
ps.println(s);
if(s.equals("exit")){
System.exit(1);
}
String st=br2.readLine();
System.out.println("Data returned by server");
System.out.println(st);
}
}
}

import java.net.*;
import java.io.*;
public class SimpleServer
{
public static void main(String args[])
{
ServerSocket s=null;

try
{
s=new ServerSocket(5432);
}
catch(IOException e)
{
e.printStackTrace();
}

while(true)
{
try
{
Socket s1=s.accept();
OutputStream s1out=s1.getOutputStream();
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s1out));

bw.write("Hello Net World! \n");


bw.close();
s1.close();
}
catch(IOException e)
{

174
e.printStackTrace();
}
}
}
}
/*********************************/
import java.net.*;
import java.io.*;
public class SimpleClient
{
public static void main(String args[])
{
try
{
Socket s1=new Socket("127.0.0.1", 5432);

InputStream is=s1.getInputStream();

DataInputStream dis=new DataInputStream(is);

System.out.println(dis.readUTF());

//br.close();
s1.close();
}
catch(ConnectException connExc)
{
System.err.println("Could not connect");
}
catch(IOException e)
{
}
}
}

/******************Data Gram Application********************/

175
Server Program
import java.net.*;
class udpip_server
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];

public static void Myserver() throws Exception


{
int pos=0;
while(true)
{
int c=System.in.read();
switch(c)
{
case -1: System.out.println("Server quits");
return;
case '\r':break;
case '\n':ds.send(new
DatagramPacket(buffer,pos,InetAddress.getLocalHost(),777));
pos=0;
break;
default:
buffer[pos++]=(byte) c;
}
}
}

public static void main(String args[]) throws Exception


{
System.out.println("Server ready..\n Please type here");
ds=new DatagramSocket(888);
Myserver();
}
}

Client Program
import java.net.*;
class udpip_client
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];

public static void Myclient() throws Exception


{
while(true)

176
{
DatagramPacket p=new DatagramPacket(buffer,buffer.length);
ds.receive(p);
System.out.println(new String(p.getData(),0,p.getLength()));
}
}

public static void main(String args[]) throws Exception


{
System.out.println("Client - Press CTRL+C to quit");
ds=new DatagramSocket(777);
Myclient();
}
}

Swing
Light weight and heavy weight components: A heavy weight component is one
that is associated with its own native screen resource (commonly known as a
peer). A lightweight component is one that borrows the screen resource of an
ancestor (which means it has no native resource of its own, so it is lighter). All
AWT components are heavy weight and all swing components are lightweight
(except for the top-level like JWindow, JFrame, JDialog, JApplet ).
There are some significant differences between light weight and heavy weight
components.
1. A light weight component can have transparent pixels, a heavy weight is
always opaque.
2. A light weight component can appear to be non rectangular because of its
ability to set trsparent areas; a heavy weight can only be rectangular.
3. Mouse events on a light weight component fall through to its parent.
Mouuse events on a heavy weight component do not fall through to its
parent.
4. When a light weight component overlaps a heavy weight component, the
heavy weight component is always on top.

177
5. Light weight components provide more efficient use of resources.

Introduction: Swing is a set of classes that provides more powerful and flexible
components that are not possible with the AWT. In addition to the familiar controls like
button, Label ets. Swing supplies several other controls like tabbed panes, scroll panes,
trees and tables etc.
Unlike AWT components, swing components are not implemented by plateform-specific
code. Instead, they are written entirely in java and , therefore are plateform independent.
The term lightweight is used to describe such elements.
/*Simple Java Swing Frame */
import javax.swing.*;
class jframe
{
JFrame f;

jframe()
{
f=new JFrame("Demo Form");
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String args[])
{
jframe obj=new jframe();
}
}

/*First Swing frame with label program */


import javax.swing.*;
import java.awt.event.*;
class frame2 extends JPanel
{
static JFrame f;

frame2()
{
JLabel l=new JLabel("Hello java Swing");
add(l);
}

public static void main(String args[])


{
frame2 obj=new frame2();
f=new JFrame("Hello Swing");
f.setSize(250,150);
f.getContentPane().add("Center",obj);

178
//f.getContentPane().add("East",obj);
//f.getContentPane().add("West",obj);
//f.getContentPane().add("North",obj);
//f.getContentPane().add("South",obj);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
f.setVisible(true);
}
}

/*Java Swing Label*/


import javax.swing.*;
import java.awt.*;
class icons
{
JFrame f;
JLabel lbl;
ImageIcon img;

icons()
{
f=new JFrame("Frame with Label");
f.setSize(200,200);

//lbl=new JLabel("Label");
//f.add(lbl);

img=new ImageIcon("a7.gif");
//lbl=new JLabel(img);
//f.add(lbl);

lbl=new JLabel("Label 1",JLabel.RIGHT);


f.add(lbl);

//lbl=new JLabel("Label",img,JLabel.RIGHT);
//lbl=new JLabel("Label",img,JLabel.CENTER);
lbl=new JLabel("Label",img,JLabel.LEFT);
//lbl=new JLabel("Label",img,JLabel.LEADING);
lbl=new JLabel("Label",img,JLabel.TRAILING);

179
f.add(lbl);
f.setVisible(true);
}

public static void main(String args[])


{
icons obj=new icons();
}
}

/*****various method of label*****/


import javax.swing.*;
import java.awt.*;
class icons1
{
JFrame f;
JLabel lbl;
ImageIcon img;
Icon i;

icons1()
{
f=new JFrame("Frame with Label");
f.setSize(200,200);

img=new ImageIcon("a7.gif");
lbl=new JLabel("Label",img,JLabel.TRAILING);
f.add(lbl);

String s=lbl.getText();
i=lbl.getIcon();
System.out.println(s);//will show label text
System.out.println(i);//will show name of image

lbl.setText("LBL");
img=new ImageIcon("a5.gif");
lbl.setIcon(img);
f.setVisible(true);
}

public static void main(String args[])


{
icons1 obj=new icons1();
}
}

180
/**********Label with Applet*********/
import java.awt.*;
import javax.swing.*;
/*<applet code="jlabels" width=200 height=200></applet>*/
public class jlabels extends JApplet
{
public void init()
{
Container cont=getContentPane();
ImageIcon img=new ImageIcon("a5.gif");
JLabel jl=new JLabel("Label", img, JLabel.CENTER);
cont.add(jl);
}
}

/**Text Field**/
import java.awt.*;
import javax.swing.*;
class textfield
{
JFrame f;
JTextField txtname;

textfield()
{
f=new JFrame("Text Field");
f.setSize(200,200);
f.setLayout(new FlowLayout());
//txtname=new JTextField();
//txtname=new JTextField(10);
//txtname=new JTextField("Name");
txtname=new JTextField("Name",15);
f.add(txtname);
f.setVisible(true);
}

public static void main(String args[])


{
textfield obj=new textfield();
}
}

181
/***********Text Field with Applet***/
import java.awt.*;
import javax.swing.*;
/*<applet code=textfields width=200 height=200></applet>*/
public class textfields extends JApplet
{
JTextField jt;

public void init()


{
setLayout(new FlowLayout());
jt=new JTextField(15);
add(jt);
}
}

/**************Formatted Text Field*****************/


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
class formateds extends JFrame implements ActionListener
{
JTextField t;
formateds()
{
setSize(200,200);
setLayout(new FlowLayout());
JFormattedTextField txt=new
JFormattedTextField(Calendar.getInstance().getTime());
txt.setActionCommand("Hello java");
txt.addActionListener(this);
add(txt);

t=new JTextField(10);
t.setText(Calendar.getInstance().getTime().toString());
t.setActionCommand("Time : ");
t.addActionListener(this);
add(t);
setVisible(true);
}

public void actionPerformed(ActionEvent ae)

182
{
System.out.println(ae.getActionCommand());
System.out.println(t.getText());
}

public static void main(String args[])


{
formateds obj=new formateds();
}
}

Password Field
import java.awt.*;
import javax.swing.*;
class passwordfield extends JFrame
{
JPasswordField txt;

passwordfield()
{
setSize(200,200);
setLayout(new FlowLayout());

txt=new JPasswordField(10);
txt.setEchoChar('#');
add(txt);
setVisible(true);
}

public static void main(String args[])


{
passwordfield obj=new passwordfield();
}
}

/***************Text Area*********************/
import java.awt.*;
import javax.swing.*;
class textarea extends JFrame
{
JTextArea t1,t2,t3,t4;

textarea()
{
setLayout(new FlowLayout());

183
setSize(200,200);

t1=new JTextArea();//will remain invisible


t2=new JTextArea("Hello java and c++");
t3=new JTextArea(10,20);//10->row, 20->column
t4=new JTextArea("Hello how are you",5,10);//5->row, 10->column

add(t1);
add(t2);
add(t3);
add(t4);
setVisible(true);
}

public static void main(String args[])


{
textarea obj=new textarea();
}
}

/************************password field*********************/
import java.awt.*;
import javax.swing.*;
//<applet code=textarea width=300 height=300></applet>
public class textarea extends JApplet
{
JTextField f;
JTextArea a;
JPasswordField pf;

public void init()


{
Panel p1,p2,p3;
p1=new Panel();
p2=new Panel();
p3=new Panel();

Container cp=getContentPane();
f=new JTextField(10);
a=new JTextArea("Type some text",10,10);
pf=new JPasswordField(10);
pf.setEchoChar('*');
p1.add(f);
p2.add(a);
p3.add(pf);
cp.add(p1,BorderLayout.NORTH);

184
cp.add(p2, BorderLayout.CENTER);
cp.add(p3, BorderLayout.SOUTH);
}
}

/*Button*/
import java.awt.*;
import javax.swing.*;
class button
{
JFrame f;
JButton btnok, btncancel, btn;

button()
{
f=new JFrame("Buttons Application");
f.setSize(200,200);
f.setLayout(new FlowLayout());

ImageIcon img=new ImageIcon("a7.gif");


btnok=new JButton("OK");
btncancel=new JButton(img);
btn=new JButton("OK",img);

f.add(btnok);
f.add(btncancel);
f.add(btn);

f.setVisible(true);
}
public static void main(String args[])
{
button obj=new button();
}
}

/************Java Button with action command***/


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*<applet code="JButtonDemo" width=500 height=500></applet>*/
public class JButtonDemo extends JApplet implements ActionListener
{

185
JTextField jtf;

public void init()


{
Container contentPane=getContentPane();
contentPane.setLayout(new FlowLayout());

ImageIcon img=new ImageIcon("a7.gif");


JButton jb=new JButton(img);
jb.setActionCommand("OK");
jb.addActionListener(this);
contentPane.add(jb);

ImageIcon im=new ImageIcon("a5.gif");


jb=new JButton(im);
jb.setActionCommand("Cacel");
jb.addActionListener(this);
contentPane.add(jb);

ImageIcon i=new ImageIcon("a7.gif");


jb=new JButton(i);
jb.setActionCommand("Button");
jb.addActionListener(this);
contentPane.add(jb);

jtf=new JTextField(15);
contentPane.add(jtf);
}

public void actionPerformed(ActionEvent ae)


{
jtf.setText(ae.getActionCommand());
}
}

/*************Button with image and text field **************/


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//<applet code="jltb.class" height=400 width=400></applet>
public class jltb extends JApplet implements ActionListener
{
JLabel l1;
JTextField t1;
JButton b1;
public void init()

186
{
setLayout(new FlowLayout());
l1=new JLabel("Name");
t1=new JTextField(30);
b1=new JButton("Click me",new ImageIcon("aamir1.jpg"));
add(l1);
add(t1);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
t1.setText("Button is pressed");
}
}

/*Toggle Button*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
//<applet code=togglebutton width=500 height=500></applet>
public class togglebutton extends JApplet implements ActionListener
{
JToggleButton b1,b2,b3,b4,b5;
ImageIcon enable, disable;

public void init()


{
setLayout(new FlowLayout());
enable=new ImageIcon("a1.gif");
disable=new ImageIcon("a2.gif");
b1=new JToggleButton("Start", enable);
b2=new JToggleButton("Stop",disable);
b3=new JToggleButton("Ok");
b4=new JToggleButton();
b5=new JToggleButton("pressed",enable,true);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);

add(b1);

187
add(b2);
add(b3);
add(b4);
add(b5);
}

public void actionPerformed(ActionEvent ae)


{
JToggleButton b=(JToggleButton)ae.getSource();
if(b==b1)
b1.setIcon(disable);
if(b==b2)
b2.setIcon(enable);
}
}

/*Resizing of label and text field and setting fonts and use of SetBounds method*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class pm extends JFrame
{
JLabel l1;
JTextField t1;
Font fnt;

public pm()
{
l1=new JLabel("Name");
t1=new JTextField(10);
setLayout(null);
fnt=new Font("Comic Sans Ms",Font.BOLD,18);
l1.setBounds(100,20,100,25);
l1.setFont(fnt);
add(l1);
t1.setBounds(170,22,100,25);
add(t1);
}
public static void main(String args[])
{
pm p1=new pm();
p1.setSize(400,400);
p1.setVisible(true);
p1.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent winevt)

188
{
System.exit(0);
}
});
}
}

/****CheckBoxes**********/
import javax.swing.*;
import java.awt.*;
class checkbox
{
JCheckBox c1,c2,c3,c4,c5,c6;
JFrame f;
checkbox()
{
f=new JFrame("Frame with checkbox");
f.setSize(400,400);
f.setLayout(new FlowLayout());

ImageIcon icon=new ImageIcon("a7.gif");


c1=new JCheckBox(icon);
c2=new JCheckBox(icon,true);
c3=new JCheckBox("Male");
c4=new JCheckBox("Female",true);
c5=new JCheckBox("Married",icon);
c6=new JCheckBox("Unmarried",icon,true);

f.add(c1);
f.add(c2);
f.add(c3);
f.add(c4);
f.add(c5);
f.add(c6);

f.setVisible(true);
}

public static void main(String args[])


{
checkbox obj=new checkbox();
}
}
/*************check box****************/
import java.awt.*;
import java.awt.event.*;

189
import javax.swing.*;
/*<applet code=checkbox2 width=400 height=400></applet>*/
public class checkbox2 extends JApplet implements ItemListener
{
JTextField jtf;

public void init()


{
setLayout(new FlowLayout());
ImageIcon img1=new ImageIcon("a7.gif");
ImageIcon img2=new ImageIcon("a5.gif");

JCheckBox c1=new JCheckBox("CheckBox",img1);


c1.setRolloverIcon(img1);//when selected image will change
c1.setSelectedIcon(img2);
c1.addItemListener(this);
add(c1);

jtf=new JTextField(15);
add(jtf);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb=(JCheckBox)ie.getItem();
jtf.setText(cb.getText());
}
}

/***********************Radio Button with From***************/


import java.awt.*;
import javax.swing.*;
class radiobutton
{
JFrame f;
JRadioButton r1,r2,r3,r4,r5,r6;
ButtonGroup bg;

radiobutton()
{
f=new JFrame("Radio Buttons");
f.setSize(400,400);
f.setLayout(new FlowLayout());

ImageIcon img=new ImageIcon("a1.gif");


r1=new JRadioButton("Male");
r2=new JRadioButton(img);

190
r3=new JRadioButton("Female",img);
r4=new JRadioButton("Married",true);
r5=new JRadioButton("Unmarried",img,true);
r6=new JRadioButton(img,true);

f.add(r1);
f.add(r2);
f.add(r3);
f.add(r4);
f.add(r5);
f.add(r6);

bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
bg.add(r3);
bg.add(r4);
bg.add(r5);
bg.add(r6);

f.setVisible(true);
}

public static void main(String args[])


{
radiobutton obj=new radiobutton();
}
}
/*********Redio button****************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*<applet code=radiobutton2 width=300 height=300></applet>*/
public class radiobutton2 extends JApplet implements ActionListener
{
JTextField t;
ImageIcon img;

public void init()


{
setLayout(new FlowLayout());

img=new ImageIcon("a1.gif");

JRadioButton b1=new JRadioButton("A",img);

191
b1.addActionListener(this);
add(b1);

JRadioButton b2=new JRadioButton("B");


b2.addActionListener(this);
add(b2);

JRadioButton b3=new JRadioButton("C");


b3.addActionListener(this);
add(b3);

ButtonGroup bg=new ButtonGroup();


bg.add(b1);
bg.add(b2);
bg.add(b3);

t=new JTextField(5);
add(t);
}

public void actionPerformed(ActionEvent ae)


{
t.setText(ae.getActionCommand());
}
}

/****************java Radio button********************/


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//<applet code="jrb.class" height=400 width=400></applet>
public class jrb extends JApplet implements ItemListener
{
JRadioButton r1,r2,r3,r4;
ButtonGroup group;
JTextField t1;
public void init()
{
setLayout(new FlowLayout());
group=new ButtonGroup();
r1=new JRadioButton("Radio1");
r2=new JRadioButton("Radio2");
r3=new JRadioButton("Radio3");
r4=new JRadioButton("Radio4");
group.add(r1);
group.add(r2);

192
group.add(r3);
group.add(r4);
add(r1);
add(r2);
add(r3);
add(r4);
r1.addItemListener(this);
r2.addItemListener(this);
r3.addItemListener(this);
r4.addItemListener(this);
t1=new JTextField(10);
add(t1);
}

public void itemStateChanged(ItemEvent e)


{
if (e.getItemSelectable()==r1)
t1.setText("radio1 selected");
else if (e.getItemSelectable()==r2)
t1.setText("radio2 selected");
else if (e.getItemSelectable()==r3)
t1.setText("radio3 selected");
else if (e.getItemSelectable()==r4)
t1.setText("radio4 selected");
}
}

/*********Combo Box*************/
import java.awt.*;
import javax.swing.*;
class combobox
{
JFrame f;
JComboBox c;

combobox()
{
f=new JFrame("Combo Box ");
f.setSize(200,200);
f.setLayout(new FlowLayout());
c=new JComboBox();
c.addItem("Arial");
c.addItem("Comic");
c.addItem("Calibiri");

193
f.add(c);
f.setVisible(true);
}

public static void main(String args[])


{
combobox obj=new combobox();
}
}

/*****************ComboBox with Images********************/


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/*<applet code="combobox2" width=200 height=200></applet>*/


public class combobox2 extends JApplet implements ItemListener
{
JLabel l;
ImageIcon img1,img2,img3,img4;

public void init()


{
setLayout(new FlowLayout());

JComboBox jc=new JComboBox();


jc.addItem("a1");
jc.addItem("a2");
jc.addItem("a3");
jc.addItem("a4");
jc.addItemListener(this);
add(jc);

l=new JLabel(new ImageIcon("a1.gif"));


add(l);
}

public void itemStateChanged(ItemEvent e)


{
String s=(String)e.getItem();
l.setIcon(new ImageIcon(s+".gif"));
}
}

/***********Java Combo Box with event**********/

194
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//<applet code="jcom.class" height=400 width=400></applet>
public class jcom extends JApplet implements ActionListener
{
JComboBox jc=new JComboBox();
public void init()
{
jc.addItem("Item 1");
jc.addItem("Item 2");
jc.addItem("Item 3");
jc.addItem("Item 4");
jc.addItem("Item 5");
jc.addItem("Item 6");
jc.setEditable(true);
setLayout(new FlowLayout());
add(jc);
jc.getEditor().addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String outString=(String)jc.getSelectedItem()+ " Changed to " +
(String)jc.getEditor().getItem();
showStatus(outString);
}
}

Tabbed Pane
import javax.swing.*;
//<applet code="tabbedpane" width=400 height=400></applet>
public class tabbedpane extends JApplet
{
JPanel cities, colors, flavors;
public void init()
{
JTabbedPane tb=new JTabbedPane();

cities=new JPanel();
JLabel l1=new JLabel("New Delhi");
JLabel l2=new JLabel("Calcutta");
JLabel l3=new JLabel("Channai");
JLabel l4=new JLabel("Mumbai");
cities.add(l1);
cities.add(l2);

195
cities.add(l3);
cities.add(l4);
tb.addTab("Cities",cities);

colors=new JPanel();
JCheckBox chk1=new JCheckBox("Red");
JCheckBox chk2=new JCheckBox("Green");
JCheckBox chk3=new JCheckBox("Yellow");
colors.add(chk1);
colors.add(chk2);
colors.add(chk3);
tb.add("Colors",colors);

flavors=new JPanel();
JComboBox cmb=new JComboBox();
cmb.addItem("Mango");
cmb.addItem("Orange");
cmb.addItem("Pine Apple");
cmb.addItem("Banana");
flavors.add(cmb);
tb.add("Flavors",flavors);

add(tb);
}
}

/*****************OR WITH CLASS********************/


import javax.swing.*;
/*<applet code="tabbedpane" width=400 height=400></applet>*/
public class tabbedpane extends JApplet
{
public void init()
{
JTabbedPane tb=new JTabbedPane();
tb.addTab("Cities",new CitiesPanel());
tb.addTab("Color",new ColorsPanel());
tb.addTab("Flavors",new FlavorsPanel());
getContentPane().add(tb);
}
}
class CitiesPanel extends JPanel
{
public CitiesPanel()
{
JButton b1=new JButton("New York ");
add(b1);

196
JButton b2=new JButton("London");
add(b2);
JButton b3=new JButton("Hong Kong");
add(b3);
JButton b4=new JButton("Tokyo");
add(b4);
}
}
class ColorsPanel extends JPanel
{
public ColorsPanel()
{
JCheckBox c1=new JCheckBox("Red");
add(c1);
JCheckBox c2=new JCheckBox("Green");
add(c2);
JCheckBox c3=new JCheckBox("Cyan");
add(c3);
}
}
class FlavorsPanel extends JPanel
{
public FlavorsPanel()
{
JComboBox cb=new JComboBox();
cb.addItem("Vanila");
cb.addItem("Chocalate");
cb.addItem("Strawberry");
add(cb);
}
}

/*Tabbed Pane with Images*/


import java.awt.*;
import javax.swing.*;
//<applet code="tabbed" height=400 width=400></applet>
public class tabbed extends JApplet
{
public void init()
{
Container cp=getContentPane();
JTabbedPane tb=new JTabbedPane();

JPanel p1=new JPanel();


JPanel p2=new JPanel();

197
JPanel p3=new JPanel();

p1.add(new JLabel("This is Panel 1"));


p2.add(new JLabel("This is Panel 2"));
p3.add(new JLabel("This is Panel 3"));

p1.setBackground(Color.cyan);
p2.setBackground(Color.green);
p3.setBackground(Color.yellow);

tb.addTab("", new ImageIcon("Tab1.png"),p1);//with image


tb.addTab("", new ImageIcon("Tab2.png"),p2,"This is tab2");//with image
and string
tb.addTab("This is tab3",p3);//with string only

cp.setLayout(new BorderLayout());
cp.add(tb);
}
}

/********************use of two layout Pans ***********************/


import javax.swing.*;
import java.awt.*;
//<applet code="form.class" width=341 height=193></applet>
public class form extends JApplet
{
JButton e,w,s,c;
JLabel l1,l2,l3;
JTextField t1, t2, t3;
BorderLayout jb;
JPanel p;

public void init()


{
jb=new BorderLayout();
setLayout(jb);

e=new JButton("East");
w=new JButton("West");
s=new JButton("South");
c=new JButton("Center");

add(e,BorderLayout.EAST);
add(w,BorderLayout.WEST);
add(s,BorderLayout.SOUTH);

198
add(c,BorderLayout.CENTER);

p=new JPanel();
p.setBackground(Color.cyan);
p.setLayout(new GridLayout(3,2));
l1=new JLabel("Name ");
l2=new JLabel("Address ");
l3=new JLabel("Rollno ");

t1=new JTextField(10);
t2=new JTextField(10);
t3=new JTextField(10);

p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(l3);
p.add(t3);

add(p,BorderLayout.NORTH);
}
}

Scrolling
import java.awt.*;
import javax.swing.*;
//<applet code=scroll width=200 height=200></applet>
public class scroll extends JApplet
{
JTextField f;
int v,h;
public void init()
{
//setLayout(new FlowLayout());
JLabel l=new JLabel("Hello");
Panel p=new Panel();
p.add(l);

v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
JScrollPane js=new JScrollPane(p,v,h);
add(js);
}

199
}

/*************Scroll Pane***************/
import java.awt.*;
import javax.swing.*;
//<applet code=scrollpane width=500 height=500></applet>
public class scrollpane extends JApplet
{
public void init()
{
JPanel jp=new JPanel();
jp.setLayout(new GridLayout(20,20));
int b=0;
for(int i=0; i<20; i++)
{
for(int j=0; j<20;j++)
{
jp.add(new JButton("Button"+b));
b++;
}
}
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp=new JScrollPane(jp, v, h);
add(jsp);
}
}

/***************Java list*********************/
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
//<applet code="jlst.class" height=400 width=400></applet>
public class jlst extends JApplet implements ListSelectionListener
{
JList jlist;
public void init()
{
String []item=new String[10];
int i;
for(i=0;i<10;++i)
{
item[i]="Item "+i;
}

jlist=new JList(item);

200
JScrollPane jscrollpane=new JScrollPane(jlist);
jlist.setVisibleRowCount(5);
jlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
jlist.addListSelectionListener(this);
setLayout(new FlowLayout());
add(jscrollpane);
}
public void valueChanged(ListSelectionEvent e)
{
int indexs[]=jlist.getSelectedIndices();
String outString="You Choose : " ;
for(int i=0;i<indexs.length;++i)
{
outString=outString+indexs[i];
}
showStatus(outString);
}
}

/*****************java Tool Tip*****************


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//<applet code="jtool.class" height=400 width=400></applet>
public class jtool extends JApplet implements ActionListener
{
JButton button=new JButton("Click me");
JTextField text=new JTextField(10);
public void init()
{
setLayout(new FlowLayout());
button.setToolTipText("This is a button");
text.setToolTipText("Press Button and you can see message here");
add(button);
add(text);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
text.setText("Hello from swing");
}
}

/***************** Tree*******************/
201
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
//<applet code=trees width=400 height=400></applet>
public class trees extends JApplet
{
JTree tree;
JTextField jtf;

public void init()


{
setLayout(new BorderLayout());

DefaultMutableTreeNode top=new DefaultMutableTreeNode("Options");

DefaultMutableTreeNode a=new DefaultMutableTreeNode("A");


top.add(a);

DefaultMutableTreeNode a1=new DefaultMutableTreeNode("A1");


a.add(a1);

DefaultMutableTreeNode a2=new DefaultMutableTreeNode("A2");


a.add(a2);

DefaultMutableTreeNode b=new DefaultMutableTreeNode("B");


top.add(b);

DefaultMutableTreeNode b1=new DefaultMutableTreeNode("B1");


b.add(b1);

DefaultMutableTreeNode b2=new DefaultMutableTreeNode("B2");


b.add(b2);

DefaultMutableTreeNode b3=new DefaultMutableTreeNode("B3");


b.add(b3);

tree=new JTree(top);

int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int
h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp=new JScrollPane(tree,v,h);

add(jsp,BorderLayout.CENTER);
jtf=new JTextField(" ",20);

202
add(jtf, BorderLayout.SOUTH);

tree.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
doMouseClicked(me);
}
});
}

void doMouseClicked(MouseEvent me)


{
TreePath tp=tree.getPathForLocation(me.getX(), me.getY());
if(tp!=null)
jtf.setText(tp.toString());
else
jtf.setText(" ");
}
}

Table
import java.awt.*;
import javax.swing.*;
//<applet code=table height=500 width=500></applet>
public class table extends JApplet
{
public void init()
{
setLayout(new BorderLayout());
String[] colhead={"Name","Phone","Address"};
String [][]data={
{"Rahil","123","Dehradun"},
{"Sumit","456","Agra"},
{"Zakir","789","Kanpur"},
{"Arif","147","Dehradun"},
{"laxmi","258","Dehradun"}
};
JTable t=new JTable(data,colhead);

int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;

JScrollPane jsp=new JScrollPane(t,v,h);


add(jsp,BorderLayout.CENTER);

203
}
}

Slider
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
//<applet code=slider width=500 height=500></applet>
public class slider extends JApplet implements ChangeListener
{
JSlider slid;
JTextField t;

public void init()


{
setLayout(new BorderLayout());
slid=new JSlider(JSlider.HORIZONTAL, 0, 100,10);//0-->initial value,
100-->max value, 10-->position of slider
Panel p=new Panel();
t=new JTextField(10);
p.add(t);
slid.addChangeListener(this);
add(slid,BorderLayout.NORTH);
add(p,BorderLayout.CENTER);
}

public void stateChanged(ChangeEvent e)


{
t.setText(Integer.toString(slid.getValue()));
}
}

Progressbar
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//<applet code=progressbar width=400 height=400></applet>
public class progressbar extends JApplet
{
JProgressBar pb;
int sum;
int count;

204
public void init()
{
setLayout(new BorderLayout());
sum=count=0;
//pb=new JProgressBar();
//pb=new JProgressBar(JProgressBar.VERTICAL);
//pb=new JProgressBar(JProgressBar.HORIZONTAL);
pb=new JProgressBar(JProgressBar.HORIZONTAL,0,100);

pb.setStringPainted(true);
pb.setBackground(Color.white);
pb.setForeground(Color.black);
pb.setMinimum(0);
pb.setMaximum(100000000);
add(pb, BorderLayout.NORTH);
for(; count<100000000;count++)
{
sum=sum+count;
pb.setValue(count);
}
}
}

/**********Progress bar with functionality*****************/


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class progressbar extends JFrame
{
JProgressBar pb;
JButton btn;
int i=0;
JLabel lbl,lblpercent, lblorientation;

progressbar()
{
setSize(500,500);
setLayout(new FlowLayout());

pb=new JProgressBar(JProgressBar.HORIZONTAL,0,100);
pb.setStringPainted(true);
pb.setBackground(Color.white);
pb.setForeground(Color.black);
pb.setMinimum(0);
pb.setMaximum(100);
pb.setBorderPainted(false);//remove border from progress bar

205
pb.setString("Progress");//we can set our own text in progress bar
add(pb);

btn=new JButton("OK");
add(btn);
btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
i=i+10;
if(i>100)
i=0;

pb.setValue(i);
lbl.setText("Pregress : "+String.valueOf(pb.getValue()));

lblpercent.setText("Progress in % :
"+String.valueOf(pb.getPercentComplete()));

}
});

lbl=new JLabel("Progress ");


add(lbl);

lblpercent=new JLabel("Percent ");


add(lblpercent);

lblorientation=new JLabel("Orientation");
lblorientation.setText("Orientation :
"+String.valueOf(pb.getOrientation()));
add(lblorientation);

setVisible(true);
}

public static void main(String args[])


{
progressbar obj=new progressbar();
}

/***Slider and progressbar in combination****/


import java.awt.*;

206
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;//for slider
public class JSwingStarts extends Frame implements ChangeListener
{
JSlider slider = new JSlider(JSlider.VERTICAL, 0, 100, 60);
JProgressBar progressBar = new JProgressBar();
JPanel barPanel = new JPanel();

JSwingStarts()
{
setSize(500,500);
setupBarPanel();
add(barPanel);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
setVisible(false);
dispose();
}
});
setVisible(true);
}

void setupBarPanel()
{
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(5);
slider.addChangeListener(this);

progressBar.setOrientation(JProgressBar.HORIZONTAL);
progressBar.setMinimum(0);
progressBar.setMaximum(100);
progressBar.setValue(40);

barPanel.add(new JLabel("Slider"));
barPanel.add(slider);
barPanel.add(new JLabel("Progress Bar"));
barPanel.add(progressBar);
}

public void stateChanged(ChangeEvent e)


{
progressBar.setValue(slider.getValue());
}

207
public static void main(String[] args)
{
JSwingStarts app = new JSwingStarts();
}
}

Tool bar
//<applet code=toolbar width=300 height=300></applet>
import java.awt.*;
import javax.swing.*;
public class toolbar extends JApplet
{
public void init()
{
ImageIcon nw=new ImageIcon("a1.gif"); ImageIcon open=new
ImageIcon("a2.gif");
ImageIcon save=new ImageIcon("a3.gif");
ImageIcon copy=new ImageIcon("a4.gif");
ImageIcon close=new ImageIcon("a5.gif");

JButton newbut=new JButton(nw);


JButton openbut=new JButton(open);
JButton savebut=new JButton(save);
JButton copybut=new JButton(copy);
JButton closebut=new JButton(close);

setLayout(new BorderLayout());
JToolBar tool=new JToolBar();
tool.add(newbut);
tool.add(openbut);
tool.addSeparator();
tool.add(savebut);
tool.add(copybut);
tool.add(closebut);
add(tool, BorderLayout.NORTH);
}
}
/******************Color Application*********************/
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class colors extends JPanel

208
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D gd=(Graphics2D)g;
gd.setColor(new Color(12,16,116));
gd.fillRect(10,10,100,50);

gd.setColor(new Color(42,19,31));
gd.fillRect(120,10,100,50);

gd.setColor(new Color(70,7,23));
gd.fillRect(120,100,100,50);

gd.setColor(new Color(21,98,69));
gd.fillRect(10,100,100,50);

gd.setColor(new Color(10,10,84));
gd.fillRect(120,200,100,50);

gd.setColor(new Color(22,21,61));
gd.fillRect(10,200,100,50);

gd.setColor(new Color(217,146,54));
gd.fillRect(120,300,100,50);

gd.setColor(new Color(63,121,186));
gd.fillRect(10,300,100,50);

gd.setColor(new Color(131,121,11));
gd.fillRect(10,400,100,50);

public static void main(String args[])


{
JFrame f=new JFrame("Colors");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new colors());
f.setSize(360,300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

209
Dialog Box
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class dialog extends JFrame


{
JFrame f;

JButton b;
dialog()
{
setSize(500,500);
setLayout(new FlowLayout());
b=new JButton("OK");
add(b);
b.addActionListener(new ActionListener()

{
public void actionPerformed(ActionEvent e)
{

JDialog dig=new JDialog(f,"Hello",true);


dig.setSize(200,200);
dig.add(new JLabel("Hello"));
dig.show();
}
});
setVisible(true);
}

public static void main(String ar[])


{
new dialog();
}
}

Inbuild Dialog Boxes


import java.awt.*;
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.event.*;

210
public class dialogbox implements ActionListener
{
JFrame f;
JButton b1,b2,b3;

dialogbox()
{
f=new JFrame("Dialog Boxes");
f.setSize(400,400);
f.setLayout(new FlowLayout());

b1=new JButton("Message Box");


b2=new JButton("Input Box ");
b3=new JButton("Confirm Box");

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

f.add(b1);
f.add(b2);
f.add(b3);
f.setVisible(true);
}

public void actionPerformed(ActionEvent ae)


{
if(ae.getSource()==b1)
{
JOptionPane.showMessageDialog(null,"Message Box","Message",0); //0
for error
//JOptionPane.showMessageDialog(null,"Message Box","Message",1); //1
for information
//JOptionPane.showMessageDialog(null,"Message Box","Message",2); //
2 for warning
//JOptionPane.showMessageDialog(null,"Message Box","Message",3); //3
for question
//JOptionPane.showMessageDialog(null,"Message Box","Message",-1);//-
1 for no sign
}
else if(ae.getSource()==b2)
{
//JOptionPane.showInputDialog(null, "It is input Box",0);//with 0 text
JOptionPane.showInputDialog(null, "It is input Box"); //without text
JOptionPane.showInputDialog(null, "It is input Box","hello");
}

211
else if(ae.getSource()==b3)
{
//JOptionPane.showConfirmDialog(null,null,"It is Confirm Dialog
box",0,3);//0 for yes and no buttons
//JOptionPane.showConfirmDialog(null,"confirm","It is Confirm Dialog
box",0,3);
JOptionPane.showConfirmDialog(null,"confirm","It is Confirm Dialog
box",1,3);// 1 for yes, no, cancel buttons
//JOptionPane.showConfirmDialog(null,"confirm","It is Confirm Dialog
box",2,3);//2 for ok and cancel buttons
//JOptionPane.showConfirmDialog(null,"confirm","It is Confirm Dialog
box",-1,3);//-1 for ok
}
}
public static void main(String args[])
{
dialogbox obj=new dialogbox();
}
}

/******************Message Dialog Box*****************/


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class dialogbox extends JFrame implements ActionListener
{
JButton b1;
Object [] option={"yes", "Please","No","Thanks"};

dialogbox()
{
setSize(200,200);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1=new JButton("Ok");
b1.addActionListener(this);
add(b1);

setVisible(true);
}

public void actionPerformed(ActionEvent ae)


{
//JOptionPane.showMessageDialog(null,"Worning
Message","Message",JOptionPane.WARNING_MESSAGE);

212
//JOptionPane.showMessageDialog(this,"Error
Message","Message",JOptionPane.ERROR_MESSAGE);
//JOptionPane.showMessageDialog(null,"Plain
Message","Message",JOptionPane.PLAIN_MESSAGE);
//JOptionPane.showMessageDialog(this,"Plain Message");
JOptionPane.showMessageDialog(this,"Error
Message","Message",JOptionPane.INFORMATION_MESSAGE);

ImageIcon img=new ImageIcon("a1.gif");


//int n=JOptionPane.showOptionDialog(this,"Option Dialog",
"Option",JOptionPane.YES_NO_CANCEL_OPTION ,
JOptionPane.QUESTION_MESSAGE,null,option,option[2]);
int n=JOptionPane.showOptionDialog(this,"Option Dialog",
"Option",JOptionPane.YES_NO_CANCEL_OPTION ,
JOptionPane.QUESTION_MESSAGE,img,option,option[2]);
}

public static void main(String args[])


{
dialogbox obj=new dialogbox();
}
}

/*******************Java Menu ***********************/


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//<applet code="jmnu.class" height=400 width=400></applet>
public class jmnu extends JApplet implements ActionListener
{
public void init()
{
JMenuBar jmenubar=new JMenuBar();

JMenu jmenu0=new JMenu();//menu without string


JMenu jmenu1=new JMenu("File");//menu with string
JMenu jmenu2=new JMenu("Edit",true);//menu with string and turn-on condition
JMenu jmenu3=new JMenu("Images");//menu with images only

JMenuItem jmenuitem01=new JMenuItem("First");


JMenuItem jmenuitem02=new JMenuItem("Second");
JMenuItem jmenuitem03=new JMenuItem();

jmenu0.add(jmenuitem01);
jmenu0.add(jmenuitem02);

213
jmenu0.addSeparator();
jmenu0.add(jmenuitem03);

ImageIcon img1=new ImageIcon("a1.gif");


ImageIcon img2=new ImageIcon("a2.gif");
ImageIcon img3=new ImageIcon("a3.gif");

JMenuItem jmenuitem1=new JMenuItem("New...",img1); //menu item with images


JMenuItem jmenuitem2=new JMenuItem("Open...",img1);
JMenuItem jmenuitem3=new JMenuItem("Exit...",img3);

jmenu1.add(jmenuitem1);
jmenu1.add(jmenuitem2);
jmenu1.addSeparator();//adding separator to menu
jmenu1.add(jmenuitem3);
jmenuitem1.setActionCommand("You Select New");
jmenuitem2.setActionCommand("You Select Open");
jmenuitem3.setActionCommand("You Select Exit");
jmenuitem1.addActionListener(this);
jmenuitem2.addActionListener(this);
jmenuitem3.addActionListener(this);

JMenuItem jmenuitem4=new JMenuItem("Cut Ctr+X",88);//int are ASCII codes for


character
JMenuItem jmenuitem5=new JMenuItem("Copy Ctr+C",67);
JMenuItem jmenuitem6=new JMenuItem("Paste Ctr+V",85);

jmenu2.add(jmenuitem4);
jmenu2.add(jmenuitem5);
jmenu2.add(jmenuitem6);
jmenuitem4.setActionCommand("You Select Cut");
jmenuitem5.setActionCommand("You Select Copy");
jmenuitem6.setActionCommand("You Select Paste");
jmenuitem4.addActionListener(this);
jmenuitem5.addActionListener(this);
jmenuitem6.addActionListener(this);

JMenu sub=new JMenu("Sub Menu");


sub.add(new JMenuItem("First"));
sub.add(new JMenuItem("Second"));
sub.add(new JMenuItem("Third"));
jmenu2.addSeparator();
jmenu2.add(sub);

jmenu3.add(new JMenuItem(img1));
jmenu3.add(new JMenuItem(img2));

214
jmenu3.add(new JMenuItem(img3));

jmenubar.add(jmenu0);
jmenubar.add(jmenu1);
jmenubar.add(jmenu2);
jmenubar.add(jmenu3);

setJMenuBar(jmenubar);
}

public void actionPerformed(ActionEvent e)


{
JMenuItem jmenuitem=(JMenuItem)e.getSource();
showStatus(jmenuitem.getActionCommand());
}
}

Split Pane
import javax.swing.*;
import java.awt.*;
/*<applet code = "SplitPane" width = 600 height = 500></applet>*/
public class SplitPane extends JApplet
{
JLabel lbl1,lbl2;
JTextField txt1,txt2;
JButton btn1,btn2,btn3,btn4;
Panel p1,p2;

public void init()


{

// JSplitPane s1 = new JSplitPane();


// JSplitPane s1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
// JSplitPane s1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
// JSplitPane s1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,false);
lbl1=new JLabel("hello");
lbl2=new JLabel("Java");
txt1=new JTextField(10);
txt2=new JTextField("Good Morning");
btn1=new JButton("Ok");
btn2=new JButton("Cancel");
btn3=new JButton("Yes");
btn4=new JButton("NO");

p1=new Panel();

215
p1.add(lbl1);
p1.add(txt1);
p1.add(btn1);
p1.add(btn2);

p2=new Panel();
p2.add(lbl2);
p2.add(txt2);
p2.add(btn3);
p2.add(btn4);

JSplitPane s1 = new
JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,p1,p2);
s1.setDividerLocation(0.1); add(s1);
}
}
Split Pane
import javax.swing.*;
import java.awt.*;
/*<applet code = "UseSplitPane" width = 600 height = 500></applet>*/
public class UseSplitPane extends JApplet
{
public void init()
{
ImageIcon img1 = new ImageIcon("a1.gif");
ImageIcon img2 = new ImageIcon("a2.gif");
ImageIcon img3 = new ImageIcon("a3.gif");

JLabel l1 = new JLabel(img1);


JScrollPane c1 = new JScrollPane(l1);

JLabel l2 = new JLabel(img2);


JScrollPane c2 = new JScrollPane(l2);

JLabel l3 = new JLabel(img3);


JScrollPane c3 = new JScrollPane(l3);

JSplitPane s1 = new
JSplitPane(JSplitPane.VERTICAL_SPLIT,true,c1,c2);
JSplitPane s2 = new
JSplitPane(JSplitPane.HORIZONTAL_SPLIT,s1,c3);
add(s2);
}
}

216
Layered Pane (child form)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class layeredpane extends JFrame
{
JButton b1,b2,b3,b4,b5;
JInternalFrame f1,f2,f3,f4,f5;
JLayeredPane lp;
int x, y;

layeredpane()
{
setSize(500,500);

b1=new JButton("Added to default Layer ");


b2=new JButton("Added to Palette Layer ");
b3=new JButton("Added to Model Layer ");
b4=new JButton("Added to Popup Layer ");
b5=new JButton("Added to Drag Value ");

lp=this.getLayeredPane();

x=1;
y=1;
f1=new JInternalFrame("Frame 1",true,true);
f1.setLocation(x,y);
f1.setSize(200,250);
f1.add(b1);
lp.add(f1,JLayeredPane.DEFAULT_LAYER);
f1.setVisible(true);

x=20;
y=30;
f2=new JInternalFrame("Frame 2",true,true);
f2.setLocation(x,y);
f2.setSize(200,250);
f2.add(b2);
lp.add(f2,JLayeredPane.PALETTE_LAYER);
f2.setVisible(true);

x=50;
y=50;
f3=new JInternalFrame("Frame 3",true,true);
f3.setLocation(x,y);

217
f3.setSize(200,250);
f3.add(b3);
lp.add(f3,JLayeredPane.MODAL_LAYER);
f3.setVisible(true);

x=80;
y=70;
f4=new JInternalFrame("Frame 4",true,true);
f4.setLocation(x,y);
f4.setSize(200,250);
f4.add(b4);
lp.add(f4,JLayeredPane.POPUP_LAYER);
f4.setVisible(true);

x=110;
y=90;
f5=new JInternalFrame("Frame 5",true,true);
f5.setLocation(x,y);
f5.setSize(200,250);
f5.add(b5);
lp.add(f5,JLayeredPane.DRAG_LAYER);
f5.setVisible(true);

setVisible(true);
}

public static void main(String args[])


{
layeredpane obj=new layeredpane();
}
}

Connective of forms together


/********************First Form****************************/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class frmfirst extends JFrame


{
JLabel lbl1,lbl2;
JTextField txt1,txt2;
JButton btn;
String str="";

frmfirst()

218
{
setSize(500,500);
setLayout(new FlowLayout());

lbl1=new JLabel("Enter Name ");


add(lbl1);
txt1=new JTextField(10);
add(txt1);
lbl2=new JLabel("Enter age ");
add(lbl2);
txt2=new JTextField(10);
add(txt2);
btn=new JButton("Submit");
add(btn);

btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
str="Name : "+txt1.getText()+"\n Age :
"+Integer.parseInt(txt2.getText());
frmsecond obj=new frmsecond(str);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String args[])


{
frmfirst obj=new frmfirst();
}
}
/**************************Second Form***********************/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class frmsecond extends JFrame


{
JTextArea txt;

frmsecond(String str)
{
setSize(300,300);
setLayout(new FlowLayout());

219
txt=new JTextArea();
txt.setText(str);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}

Connected forms project


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class mainform extends JFrame implements ActionListener
{
JMenuItem sdetail,sfee,sexam,edetail,esalary;

mainform()
{
setSize(1500,1000);
setLayout(null);

JMenuBar mb=new JMenuBar();


JMenu mnustudent=new JMenu("Student");
JMenu mnuemployee=new JMenu("Employee");
/*****************************************/
sdetail=new JMenuItem("Student Detail");
sfee=new JMenuItem("Fees");
sexam=new JMenuItem("Exam");

mnustudent.add(sdetail);
mnustudent.add(sfee);
mnustudent.add(sexam);

sdetail.addActionListener(this);
sfee.addActionListener(this);
sexam.addActionListener(this);
/*---------------------------------*/
edetail=new JMenuItem("Employee Detail");
esalary=new JMenuItem("Salary");

220
mnuemployee.add(edetail);
mnuemployee.add(esalary);

edetail.addActionListener(this);
esalary.addActionListener(this);
/*----------------------*/

mb.add(mnustudent);
mb.add(mnuemployee);
add(mb);
setJMenuBar(mb);

setVisible(true);
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource()==sdetail)
{
frmstudent obj=new frmstudent();
}
else if(e.getSource()==edetail)
{
empform obj2=new empform();
}
}

public static void main(String args[])


{
mainform obj=new mainform();
}
}
Employee form with output form

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class employeeform extends JFrame implements ActionListener
{
JLabel lblemp,lblname,lblage,lblsalary,lblgender;
JTextField txtname,txtage,txtsalary;
Font fnt;
JRadioButton rdbmale,rdbfemale,rdbmr,rdbur;

221
ButtonGroup bg;
JComboBox cmbdsg;
JCheckBox chkug,chkpg,chkphd;
JButton btnsubmit, btnclose,btnclear;
frmoutput obj;

public employeeform()
{
setLayout(null);
fnt=new Font("Comic Sans Ms",Font.BOLD,20);
lblemp=new JLabel("Employee");
lblemp.setBounds(140,10,100,25);
lblemp.setFont(fnt);
add(lblemp);

fnt=new Font("Comic Sans MS",Font.PLAIN,15);


lblname=new JLabel("Name ");
lblname.setBounds(100,40,100,25);
lblname.setFont(fnt);
add(lblname);

txtname=new JTextField();
txtname.setBounds(180,40,150,25);
add(txtname);

lblage=new JLabel("Age ");


lblage.setBounds(100,70,100,25);
lblage.setFont(fnt);
add(lblage);

txtage=new JTextField();
txtage.setBounds(180,70,50,25);
add(txtage);

lblsalary=new JLabel("Salary ");


lblsalary.setBounds(100,100,100,25);
lblsalary.setFont(fnt);
add(lblsalary);

txtsalary=new JTextField();
txtsalary.setBounds(180,100,100,25);
add(txtsalary);

222
lblgender=new JLabel("Gender ");
lblgender.setBounds(100,130,100,25);
lblgender.setFont(fnt);
add(lblgender);

rdbmale=new JRadioButton("Male",true);
rdbmale.setBounds(120,160,70,25);
rdbmale.addActionListener(this);
add(rdbmale);

rdbfemale=new JRadioButton("Female");
rdbfemale.setBounds(200,160,70,25);
rdbfemale.setActionCommand("Female");
rdbfemale.addActionListener(this);
add(rdbfemale);

bg=new ButtonGroup();
bg.add(rdbmale);
bg.add(rdbfemale);

JLabel lblms=new JLabel("Marital Status");


lblms.setBounds(100,190,200,25);
lblms.setFont(fnt);
add(lblms);

rdbmr=new JRadioButton("Married");
rdbmr.setBounds(120,220,70,25);
rdbmr.addActionListener(this);
add(rdbmr);

rdbur=new JRadioButton("Unmarried",true);
rdbur.setBounds(200,220,100,25);
rdbur.addActionListener(this);
add(rdbur);

bg=new ButtonGroup();
bg.add(rdbmr);
bg.add(rdbur);

JLabel lbldesig=new JLabel("Designation");


lbldesig.setBounds(100,250,200,25);
lbldesig.setFont(fnt);

223
add(lbldesig);

cmbdsg=new JComboBox();
cmbdsg.addItem("Programmer");
cmbdsg.addItem("Designer");
cmbdsg.addItem("Developer");
cmbdsg.addItem("Analyser");
cmbdsg.setBounds(100,280,150,25);
cmbdsg.setFont(fnt);
add(cmbdsg);

JLabel lbled=new JLabel("Qualification");


lbled.setBounds(100,310,200,25);
lbled.setFont(fnt);
add(lbled);

chkug=new JCheckBox("Graduate");
chkug.setBounds(100,340,80,25);
add(chkug);

chkpg=new JCheckBox("Post Graduate");


chkpg.setBounds(180,340,110,25);
add(chkpg);

chkphd=new JCheckBox("Phd");
chkphd.setBounds(290,340,50,25);
add(chkphd);

btnsubmit=new JButton("Submit");
btnsubmit.setFont(fnt);
btnsubmit.setBounds(60,370,90,25);
btnsubmit.addActionListener(this);
add(btnsubmit);

btnclose=new JButton("Close");
btnclose.setFont(fnt);
btnclose.setBounds(160,370,80,25);
btnclose.addActionListener(this);
add(btnclose);

btnclear=new JButton("Clear");
btnclear.setFont(fnt);
btnclear.setBounds(260,370,80,25);

224
btnclear.addActionListener(this);
add(btnclear);
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource()==btnclose)
System.exit(1);
else if(e.getSource()==btnsubmit)
{
obj=new frmoutput();
obj.txtoutput.setText(getoutput());
}
else if(e.getSource()==btnclear)
{
txtname.setText("");
txtage.setText("");
txtsalary.setText("");
chkug.setSelected(false);
chkpg.setSelected(false);
chkphd.setSelected(false);
rdbmale.setSelected(true);
rdbur.setSelected(true);
}
}
public static void main(String args[])
{
employeeform p1=new employeeform();
p1.setSize(400,500);
p1.setVisible(true);
p1.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent winevt)
{
System.exit(0);
}
});
}
public String getoutput()
{
String s="Name \t:"+txtname.getText();
s+="\nAge \t:"+txtage.getText();
s+="\nSalary\t:"+txtsalary.getText();

225
if(rdbmale.isSelected()==true)
s+="\nGender\t:Male";
else
s+="\nGender\t:Female";
if(rdbmr.isSelected()==true)
s+="\nMarital Status:Married";
else
s+="\nMarital Status:Unmarried";
s+="\nDesignation\t:"+cmbdsg.getSelectedItem();
if(chkug.isSelected()==true && chkpg.isSelected()==true &&
chkphd.isSelected()==true)
s+="\nQualification\t:Graduate, Post Graduate, Phd";
else if(chkug.isSelected()==true && chkpg.isSelected()==true)
s+="\nQualification\t:Graduate, Post Graduate";
else if(chkug.isSelected()==true)
s+="\nQualification\t:Graduate";
return s;
}
}

class frmoutput extends JFrame


{
JTextField t;
JTextArea txtoutput;
Font fnt;
employeeform obj=new employeeform();

frmoutput()
{
setLayout(null);
setSize(500,300);

fnt=new Font("Comic Sans Ms",Font.BOLD,20);


txtoutput=new JTextArea();
txtoutput.setBounds(10,10,500,300);
txtoutput.setFont(fnt);
add(txtoutput);

setVisible(true);
}

}
Student form with output

226
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

class frmstudent extends JFrame implements ActionListener


{
JLabel lblstudent,lblname,lblrollno,lblage,lblclass,lblsection,lblgender;
JTextField txtname,txtrollno,txtage,txtclass;
JButton btnok,btncancel,btnclear;
JComboBox cmbsection;
JRadioButton rdbmale,rdbfemale;
Font fnt;
studentoutput obj1;

frmstudent()
{
setSize(400,500);
setLayout(null);
fnt=new Font("Comic Sans Ms",Font.BOLD,30);

lblstudent=new JLabel("Student");
lblstudent.setBounds(140,10,200,50);
lblstudent.setFont(fnt);
add(lblstudent);

fnt=new Font("Comic Sans MS",Font.PLAIN,20);


lblname=new JLabel("Name ");
lblname.setBounds(100,60,100,25);
lblname.setFont(fnt);
add(lblname);

txtname=new JTextField();
txtname.setBounds(220,60,100,25);
txtname.setFont(fnt);
add(txtname);

lblrollno=new JLabel("Roll No. ");


lblrollno.setBounds(100,100,100,25);
lblrollno.setFont(fnt);
add(lblrollno);

txtrollno=new JTextField();
txtrollno.setBounds(220,100,100,25);

227
txtrollno.setFont(fnt);
add(txtrollno);

lblage=new JLabel("Age ");


lblage.setBounds(100,140,100,25);
lblage.setFont(fnt);
add(lblage);

txtage=new JTextField();
txtage.setBounds(220,140,100,25);
txtage.setFont(fnt);
add(txtage);

lblclass=new JLabel("Class ");


lblclass.setBounds(100,180,100,25);
lblclass.setFont(fnt);
add(lblclass);

txtclass=new JTextField();
txtclass.setBounds(220,180,100,25);
txtclass.setFont(fnt);
add(txtclass);

lblsection=new JLabel("Section ");


lblsection.setBounds(100,220,100,25);
lblsection.setFont(fnt);
add(lblsection);

cmbsection=new JComboBox();
cmbsection.addItem("A");
cmbsection.addItem("B");
cmbsection.addItem("C");
cmbsection.addItem("D");

cmbsection.setBounds(220,220,50,25);
add(cmbsection);

fnt = new Font("Arial",Font.BOLD,15);


btnok = new JButton("OK");
btnok.setBounds(40,290,70,20);
btnok.setFont(fnt);
add(btnok);

228
btnclear = new JButton("CLEAR");
btnclear.setBounds(130,290,90,20);
btnclear.setFont(fnt);
add(btnclear);

btncancel = new JButton("CANCEL");


btncancel.setBounds(240,290,100,20);
btncancel.setFont(fnt);
add(btncancel);

btnok.addActionListener(this);
btnclear.addActionListener(this);
btncancel.addActionListener(this);

setVisible(true);
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource() == btnok)
{
obj1 = new studentoutput();
obj1.txtoutput.setText(getoutput());
}
else if(e.getSource() == btncancel)
{
System.exit(1);
}
else if(e.getSource() == btnclear)
{
txtname.setText("");
txtrollno.setText("");
txtage.setText("");
txtclass.setText("");
}
}

public String getoutput()


{
String s = "NAME OF STUDENT :\t"+txtname.getText()+"\nROLL NO. :\
t"+txtrollno.getText()+"\nAGE :\t"+txtage.getText()+"\nCLASS :\
t"+txtclass.getText();
return s;

229
}
}

class studentoutput extends JFrame


{
JTextArea txtoutput;
Font f;
studentoutput()
{
setLayout(null);
setSize(400,400);
f = new Font("Comic Sans Ms",Font.BOLD,20);
txtoutput = new JTextArea();
txtoutput.setBounds(10,10,400,400);
txtoutput.setFont(f);
add(txtoutput);
setVisible(true);
}
}

Connected form second example


/*Main Menu and Reservation (Contain reservation class also)*/
import java.awt.*;
import java.awt.event.*;
public class MainMenu extends Frame implements ActionListener
{
MenuBar mbar;
Menu m1,m2,m3;
MenuItem m11,m12,m21,m22,m31;
public MainMenu()
{
mbar=new MenuBar();
setMenuBar(mbar);
m1=new Menu("Booking");
mbar.add(m1);
m11=new MenuItem("Reservation");
m1.add(m11);
m12=new MenuItem("Cancelation");
m1.add(m12);

m2=new Menu("Report");
mbar.add(m2);
m21=new MenuItem("Confirmed Res.");

230
m2.add(m21);
m22=new MenuItem("Waiting");
m2.add(m22);

m3=new Menu("Close");
mbar.add(m3);
m31=new MenuItem("Exit");
m3.add(m31);
m11.addActionListener(this);
m12.addActionListener(this);
m21.addActionListener(this);
m22.addActionListener(this);
m31.addActionListener(this);
addWindowListener(new M());
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==m11)
{
Reservation r=new Reservation();
r.setSize(400,400);
r.setVisible(true);
r.setTitle("Reservation Screen");
}
if(e.getSource()==m31)
{
System.exit(0);
}
}
public static void main(String args[])
{
MainMenu m=new MainMenu();
m.setTitle("Main Menu");
m.setSize(400,400);
m.setVisible(true);
}

class M extends WindowAdapter


{
public void windowClosing(WindowEvent e)
{
setVisible(false);
dispose();
}
}
}

231
/*************Reservation (Connected to the MainMenu class)**********/
import java.awt.*;
import java.awt.event.*;
public class Reservation extends Frame implements ActionListener
{
Button b1,b2,b3;
Label l1,l2;
GridBagLayout gbl;
GridBagConstraints gbc;
Font f;
Reservation()
{
setBackground(Color.green);
f=new Font("Times New Roman",Font.BOLD,20);
gbl=new GridBagLayout();
gbc=new GridBagConstraints();
setLayout(gbl);
b1=new Button("Click Availability");
b1.setFont(f);
b2=new Button("Create Passengar");
b2.setFont(f);
b3=new Button("Fare Teller");
b3.setFont(f);
l1=new Label("");
l2=new Label("");

gbc.gridx=0;
gbc.gridy=0;
gbl.setConstraints(b1,gbc);
add(b1);

gbc.gridx=0;
gbc.gridy=4;
gbl.setConstraints(l1,gbc);
add(l1);

gbc.gridx=0;
gbc.gridy=8;
gbl.setConstraints(b2,gbc);
add(b2);

gbc.gridx=0;
gbc.gridy=12;
gbl.setConstraints(l2,gbc);
add(l2);

232
gbc.gridx=0;
gbc.gridy=16;
gbl.setConstraints(b3,gbc);
add(b3);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
addWindowListener(new w());
}

public void actionPerformed(ActionEvent e)


{
if (e.getSource()==b1)
{
}
}

class w extends WindowAdapter


{
public void windowClosing(WindowEvent e)
{
setVisible(false);
dispose();
}
}
}

/*A swing program with buttons, Slider, Table, Image List*/


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class JSwingStart extends Frame
{
public static int WIDTH = 450;
public static int HEIGHT = 450;
public static String TITLE = "SwingStart";
// Swing components
JTabbedPane tabbedPane = new
JTabbedPane();
JPanel buttonPanel = new JPanel();
JPanel barPanel = new JPanel();
JPanel listPanel = new JPanel();
JPanel tablePanel = new JPanel();

233
JPanel[] panels ={buttonPanel,barPanel,listPanel,tablePanel};
Icon worldIcon = new
ImageIcon("nb2.gif");
Icon printerIcon = new
ImageIcon("nb2.gif");
Icon leaf1Icon = new
ImageIcon("nb2.gif");
Icon leaf2Icon = new
ImageIcon("nb2.gif");
Icon leaf3Icon = new
ImageIcon("nb2.gif");
Icon[] leaves ={leaf1Icon, leaf2Icon,leaf3Icon};
JButton printerButton = new JButton("Print",printerIcon);
JToggleButton worldButton = new JToggleButton("Connect",worldIcon,true);
JList leafList = new JList(leaves);
JSlider slider = new JSlider(JSlider.VERTICAL, 0, 100, 60);
JProgressBar progressBar = new JProgressBar();
String[] columns = {"Product ID","Description","Price"};
Object[][] cells ={columns,{"zvga-1234","Video Card","$50"},
{"56m-11","56K Modem","$315"},{"dc-10","Net Card","$499"}};
JTable table = new JTable(cells,columns);
public JSwingStart()
{
super(TITLE);
addWindowListener(new WindowHandler());
buildGUI();
setSize(WIDTH,HEIGHT);
setBackground(Color.darkGray);
show();
}
void buildGUI()
{
// Set up tabbed pane
String[] tabs ={"Buttons","Bars","Lists","Table"};
String[] tabTips = {"A Button and a Toggle Button", "A Slider and a Progress Bar", "An
Icon List", "A Cost Table"};
for(int i=0;i<tabs.length;++i)
{
panels[i].setBackground(Color.lightGray);
panels[i].setBorder(new
TitledBorder(tabTips[i]));
tabbedPane.addTab(tabs[i],null,panels[i],tabTips[i]);
}
addComponentsToTabs();
add("Center",tabbedPane);
}

234
void addComponentsToTabs()
{
setupButtonPanel();
setupBarPanel();
setupListPanel();
setupTablePanel();
}
void setupButtonPanel()
{
printerButton.setBackground(Color.white);
worldButton.setBackground(Color.white);
buttonPanel.add(printerButton);
buttonPanel.add(worldButton);
}
void setupBarPanel()
{
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.addChangeListener(new
SliderHandler());
progressBar.setOrientation(JProgressBar.HORIZONTAL);
progressBar.setMinimum(0);
progressBar.setMaximum(100);
progressBar.setValue(60);
progressBar.setBorderPainted(true);
barPanel.add(new JLabel("Slider"));
barPanel.add(slider);
barPanel.add(new JLabel("Progress Bar"));
barPanel.add(progressBar);
}
void setupListPanel()
{
leafList.setFixedCellHeight(123);
listPanel.add(leafList);
}
void setupTablePanel()
{
tablePanel.add(table);
}
public static void main(String[] args)
{
JSwingStart app = new JSwingStart();
}
public class WindowHandler extends WindowAdapter
{

235
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
public class SliderHandler implements ChangeListener
{
public void stateChanged(ChangeEvent e)
{
progressBar.setValue(slider.getValue());
}
}
}

Dialog Boxes
/************Open File Dialog********************/
//import java.awt.BorderLayout;
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
//import java.io.BufferedReader;
//import java.io.File;
//import java.io.FileReader;
//import java.io.IOException;
/*import javax.swing.BorderFactory;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.awt.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

class opendialog extends JFrame


{
JTextArea txt;
JButton btn;

opendialog()
{
setSize(500,500);
setLayout(new FlowLayout());

txt=new JTextArea(10,10);
btn=new JButton("OK");

236
add(txt);

btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
JFileChooser fileopen=new JFileChooser();
FileFilter filter=new FileNameExtensionFilter("c files","c");
fileopen.addChoosableFileFilter(filter);

int ret=fileopen.showDialog(null,"Open File");


//open button will return 0 and cancel button will return 1

if(ret==JFileChooser.APPROVE_OPTION)
{
File file=fileopen.getSelectedFile();
String text=readFile(file);
txt.setText(text);
}
}
});

add(btn);
setVisible(true);
}

public String readFile(File file)


{
StringBuffer fileBuffer =null;
String fileString=null;
String line=null;

try
{
FileReader in=new FileReader(file);
BufferedReader brd=new BufferedReader(in);
fileBuffer = new StringBuffer();

while((line=brd.readLine())!=null)
{

fileBuffer.append(line).append(System.getProperty("line.seperator"));
}

in.close();
fileString=fileBuffer.toString();

237
}
catch(IOException e)
{
return null;
}
return fileString;
}

public static void main(String args[])


{
opendialog obj=new opendialog();
}
}

Color Dialog Box


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class colordialog extends JFrame


{
JPanel pnl;
colordialog()
{
setLayout(new FlowLayout());
setTitle("ColorChooserDialog");
setSize(400, 300);
setLocationRelativeTo(null); //this option will show form in center
of screen
setDefaultCloseOperation(EXIT_ON_CLOSE);

pnl=new JPanel();
pnl.setBorder(BorderFactory.createEmptyBorder(50, 50, 100,
100));//this option will set the size of panel

JButton openb = new JButton("OK");


add(openb);
openb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
JColorChooser clr = new JColorChooser();
Color color = clr.showDialog(null, "Choose Color",Color.white);

238
pnl.setBackground(color);
}
});

add(pnl);
setVisible(true);
}

public static void main(String args[])


{
colordialog obj=new colordialog();
}
}

Images
/****************A Simple Image Programe************/
/*<applet code=simpleimage width=248 height=146>
<param name="img1" value="a1.gif">
<param name="img2" value="a2.gif">
</applet>*/

import java.awt.*;
import java.applet.*;
import java.awt.Image;

public class simpleimage extends Applet


{
Image imgs1,imgs2;

public void init()


{
imgs1=getImage(getCodeBase(),getParameter("img1"));
imgs2=getImage(getDocumentBase(),getParameter("img2"));
}

public void paint(Graphics g)


{

239
g.drawImage(imgs1,0,0,this);
g.drawImage(imgs2,100,100,this);
}
}

/**************Image with Update Method***************/


/*<applet code="SimpleImage" width=248 height=146>
<param name="img" value="a1.gif"> </applet>*/
import java.awt.*;
import java.applet.*;
import java.awt.Image;
public class SimpleImage extends Applet
{
Image img;
public void init()
{
img = getImage(getDocumentBase(), getParameter("img"));
}
public void paint(Graphics g)
{
g.drawImage(img, 0, 0, this);
}
public boolean imageUpdate(Image img, int flags,int x, int y, int w, int h)
{
if ((flags & ALLBITS) == 0)
{
System.out.println("Still processing the image.");
return true;
}
else
{
System.out.println("Done processing the image.");
return false;
}
}
}

ImageObserver Example
/*<applet code="ObservedImage" width=248 height=146>
<param name="img" value="a1.gif"></applet>*/
import java.awt.*;
import java.applet.*;
import java.awt.Image;
public class ObservedImage extends Applet

240
{
Image img;
boolean error = false;
String imgname;

public void init()


{
setBackground(Color.blue);
imgname = getParameter("img");
img = getImage(getDocumentBase(), imgname);
}

public void paint(Graphics g)


{
if (error)
{
setBackground(Color.red);
g.drawString("Image not found: " + imgname, 10, 100);
}
else
g.drawImage(img, 0, 0, this);
}
public void update(Graphics g)
{
paint(g);
}
public boolean imageUpdate(Image img, int flags,int x, int y, int w, int h)
{
if ((flags & SOMEBITS) != 0)
{ // new partial data
repaint(x, y, w, h); // paint new pixels
}
else if ((flags & ABORT) != 0)
{
error = true; // file not found
repaint(); // paint whole applet
}
return true;
}
}

/******************Scrolling Image*****************/
import java.awt.*;
import java.applet.*;
import java.awt.Image;
/*<applet code=ScrollingImageDemo width=200 height=200></applet>*/

241
public class ScrollingImageDemo extends Applet
{
public void init()
{
setLayout(new BorderLayout());
ScrollPane SC = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);
Image mg = getImage(getCodeBase(), "d6.jpg");
SC.add(new Scrollpane(mg));
add(SC, BorderLayout.CENTER);
}
}

Double Buffere
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.Image;
//<applet code=DoubleBuffer width=500 height=500></applet>
public class DoubleBuffer extends Applet
{
int mx,my;
Image buffer=null;
int w,h;

public void init()


{
Dimension d=getSize();
w=d.width;
h=d.height;
buffer=createImage(w,h);

addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent me)
{
mx=me.getX();
my=me.getY();
repaint();
}

public void mouseMoved(MouseEvent me)


{
mx=me.getX();
my=me.getY();
repaint();

242
}
});
}

public void paint(Graphics g)


{
g.setColor(Color.blue);
g.fillRect(0,0,w,h);
g.setColor(Color.red);
for(int i=0;i<w;i=i+3)
g.drawLine(i,0,w-i,h);
for(int i=0;i<h;i=i+3)
g.drawLine(0,i,w,h-i);
g.setColor(Color.yellow);
g.fillOval(mx-3,my-3,10,10);
}

public void update(Graphics g)


{
paint(g);
}
}

Image Screen Saver


/*<applet code=TrackImage width=300 height=300>
<param name="img" value="d1+d2+d3+d4+d5+d6+d7+d8+d9"></applet>*/
import java.util.*;
import java.applet.*;

import java.awt.*;
import java.awt.Image;

public class TrackImage extends Applet implements Runnable


{
MediaTracker tracker;
int i;
int currentimg=0;
Thread t;
Image img[]=new Image[10];
String name[]=new String[10];

public void init()


{

243
tracker =new MediaTracker(this);
StringTokenizer st=new StringTokenizer(getParameter("img"),"+");
while(st.hasMoreTokens() && i<10)
{
name[i]=st.nextToken();
img[i]=getImage(getDocumentBase(),name[i]+".jpg");
tracker.addImage(img[i],i);
i++;
}
t=new Thread(this);
t.start();
}

public void paint(Graphics g)


{
String loaded="";
for(int j=0;j<i;j++)
{
if(tracker.checkID(j,true))
loaded+=name[i]+" ";
}

Dimension d=getSize();
int w=d.width;
int h=d.height;
Image im=img[currentimg++];
g.drawImage(im,50,50,null);
if(currentimg>=i)
currentimg=0;
}

public void run()


{
while(true)
{
repaint();
try
{
Thread.sleep(1000);
}
catch(Exception e){}
}
}
}

244
Image Consumer
/*<applet code="MemoryImage" width=256 height=256></applet>*/
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.Image;

public class MemoryImage extends Applet


{
Image img;

public void init()


{
Dimension d = getSize();
int w = d.width;
int h = d.height;
int pixels[] = new int[w * h];
int i = 0;
for(int y=0; y<h; y++)
{
for(int x=0; x<w; x++)
{
int r = (x^y);
int g = (x*2^y*2);
int b = (x*4^y*4);
//pixels[i++] = (255 << 24) | (r << 0) | (g << 0) | b;
//pixels[i++] = (255 << 24) | (r << 8) | (g << 0) | b;
pixels[i++] = (255 << 24) | (r <<16 ) | (g <<8) | b;
}
}
img = createImage(new MemoryImageSource(w, h, pixels, 0, w));
}

public void paint(Graphics g)


{
g.drawImage(img, 0, 0, this);
}
}

Pixel Graber
/*<applet code=HistoGrab.class width=341 height=400>
<param name=img value=d8.jpg></applet> */
import java.applet.*;

245
import java.awt.* ;
import java.awt.image.* ;
import java.awt.Image;

public class HistoGrab extends Applet


{
Dimension d;
Image img;
int iw, ih;
int pixels[];
int w, h;
int hist[] = new int[256];
int max_hist = 0;

public void init()


{
d = getSize();
w = d.width;
h = d.height;
try
{
img = getImage(getDocumentBase(), getParameter("img"));
MediaTracker t = new MediaTracker(this);
t.addImage(img, 0);
t.waitForID(0);
iw = img.getWidth(null);
ih = img.getHeight(null);
pixels = new int[iw * ih];
PixelGrabber pg = new PixelGrabber(img, 0, 0, iw, ih,
pixels, 0, iw);
pg.grabPixels();
} catch (InterruptedException e) { };
for (int i=0; i<iw*ih; i++)
{
int p = pixels[i];
int r = 0xff & (p >> 16);
int g = 0xff & (p >> 8);
int b = 0xff & (p);
int y = (int) (.33 * r + .56 * g + .11 * b);
hist[y]++;
}
for (int i=0; i<256; i++)
{
if (hist[i] > max_hist)
max_hi st = hist[i];
}

246
}
public void update() {}

public void paint(Graphics g)


{
g.drawImage(img, 0, 0, null);
int x = (w - 256) / 2;
int lasty = h - h * hist[0] / max_hist;
for (int i=0; i<256; i++, x++)
{
int y = h - h * hist[i] / max_hist;
g.setColor(new Color(i, i, i));
g.fillRect(x, y, 1, h);
g.setColor(Color.red);
g.drawLine(x-1,lasty,x,y);
lasty = y;
}
}
}

CropImageFilter
//<applet code=TileImage.class width=288
height=399></applet>
import java.applet.*;
import java.awt.*;
import java.awt.image.*;

public class TileImage extends Applet


{
Image img;
Image cell[] = new Image[4*4];
int iw, ih;
int tw, th;

public void init()


{
try
{
img = getImage(getDocumentBase(),
"waterfall.jpg");
MediaTracker t = new MediaTracker(this);
t.addImage(img, 0);
t.waitForID(0);
iw = img.getWidth(null);
ih = img.getHeight(null);

247
tw = iw / 4;
th = ih / 4;
CropImageFilter f;
FilteredImageSource fis;
t = new MediaTracker(this);
int j=-1;
for (int y=0; y<4; y++)
{
for (int x=0; x<4; x++)
{
f = new CropImageFilter(tw*x, th*y, tw, th);
fis = new FilteredImageSource(img.getSource(), f);
cell[++j] = createImage(fis);
t.addImage(cell[j], j);
}
}
t.waitForAll();
for (int i=0; i<32; i++)
{
int si = (int)(Math.random() * 16);
int di = (int)(Math.random() * 16);
Image tmp = cell[si];
cell[si] = cell[di];
cell[di] = tmp;
}
} catch (InterruptedException e) { };
}

public void update(Graphics g)


{
paint(g);
}

public void paint(Graphics g)


{
int i=-1;
for (int y=0; y<4; y++)
{
for (int x=0; x<4; x++)
{
g.drawImage(cell[++i], x * tw, y * th, null);
}
}
}
}

248
Tile Image

/*<applet code=TileImage.class width=288 height=399>


<param name=img value=d1.jpg></applet>*/
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
public class TileImage extends Applet
{
Image img;
Image cell[] = new Image[4*4];
int iw, ih;
int tw, th;

public void init()


{
try
{
img = getImage(getDocumentBase(), getParameter("img"));
MediaTracker t = new MediaTracker(this);
t.addImage(img, 0);
t.waitForID(0);
iw = img.getWidth(null);
ih = img.getHeight(null);
tw = iw / 4;
th = ih / 4;
CropImageFilter f;
FilteredImageSource fis;
t = new MediaTracker(this);

249
for (int y=0; y<4; y++)
{
for (int x=0; x<4; x++)
{
f = new CropImageFilter(tw*x, th*y, tw, th);
fis = new FilteredImageSource(img.getSource(), f);
int i = y*4+x;
cell[i] = createImage(fis);
t.addImage(cell[i], i);
}
}
t.waitForAll();
for (int i=0; i<32; i++)
{
int si = (int)(Math.random() * 16);
int di = (int)(Math.random() * 16);
Image tmp = cell[si];
cell[si] = cell[di];
cell[di] = tmp;
}
} catch (InterruptedException e) { };
}

public void update(Graphics g)


{
paint(g);
}

public void paint(Graphics g)


{
for (int y=0; y<4; y++)
{
for (int x=0; x<4; x++)
{
g.drawImage(cell[y*4+x], x * tw, y * th, null);
}
}
}
}

Image Animation
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
import java.util.*;

250
public class Animation extends Applet implements Runnable
{
Image cell[];
int MAXSEQ;
int sequence[];
int j;
int idx;

public void init()


{
int tilex = 4;
int tiley = 3;
cell = new Image[tilex*tiley];
StringTokenizer st = new StringTokenizer(getParameter("sequence"), ",");
MAXSEQ=st.countTokens();
sequence = new int[MAXSEQ];
j = 0;
int k=0;
while(st.hasMoreTokens() && j < MAXSEQ)
{
sequence[j++] =k++;
}
try
{
Image img = getImage(getDocumentBase(), getParameter("img"));
MediaTracker t = new MediaTracker(this);
t.addImage(img, 0);
t.waitForID(0);
int iw = img.getWidth(null);
int ih = img.getHeight(null);
int tw = iw / tilex;
int th = ih / tiley;
CropImageFilter f;
FilteredImageSource fis;
int i=-1;
for (int y=0; y<tiley; y++)
{
for (int x=0; x<tilex; x++)
{
f = new CropImageFilter(tw*x, th*y, tw, th);
fis = new FilteredImageSource(img.getSource(), f);
cell[++i] = createImage(fis);
t.addImage(cell[i], i);
}
}
t.waitForAll();

251
}
catch (InterruptedException e) { };
Thread t = new Thread(this);
t.start();
}

public void paint(Graphics g)


{
g.drawImage(cell[sequence[idx]], 0, 0, null);
}

public void run()


{
idx = 0;
while (true)
{
paint(getGraphics());
idx = ++idx % j;
try
{
Thread.sleep(1000);
}
catch (Exception e) { }
}
}
}
/*<applet code=Animation width=67 height=48>
<param name=img value=waterfall.jpg>
<param name=sequence value=1,2,3,4,5,6,7,8,9,10,11,12>
</applet>*/

Migrting From
C++ to Java
1. C++ Version
// Reverse the signs of a coordinate - C++ version.
#include<iostream>
#include<conio.h>

252
class Coord
{
public:
int x;
int y;
};

void reverseSign(Coord *ob)


{
ob->x = -ob->x;
ob->y = -ob->y;
}
void main()
{
Coord ob;
ob.x = 10;
ob.y = 20;
cout << "Original values for ob: ";
cout << ob.x << ", " << ob.y << "\n";
reverseSign(&ob);
cout << "Sign reversed values for ob: ";
cout << ob.x << ", " << ob.y << "\n";
getch();
}

1. Java version (C++ pointer has been convert into objects of java)
class Coord
{
int x;
int y;
}
class DropPointers
{
static void reverseCoord(Coord ob)
{
ob.x = -ob.x;
ob.y = -ob.y;
}
public static void main(String args[])
{
Coord ob = new Coord();
ob.x = 10;
ob.y = 20;
System.out.println("Original values for ob: " + ob.x + ", " + ob.y);
reverseCoord(ob);
System.out.println("Sign reversed values for ob: " + ob.x + ", " + ob.y);

253
}
}
/*************************************************/
2. C++ version

Copy Array by pointer


#include <iostream>
#include <conio.h>
void main()
{
int nums[] = {10, 12, 24, 45, 23, 19, 44, 88, 99, 65, 76, 12, 89, 0};
int copy[20];
int *p1, *p2;

p1 = nums;
p2 = copy;

while(*p1)
*p2++ = *p1++;

*p2 = 0; // terminate copy with zero

cout << "Here is the original array:\n";


p1 = nums;
while(*p1)
cout << *p1++ << " ";
cout << endl;

cout << "Here is the copy:\n";


p1 = copy;
while(*p1)
cout << *p1++ << " ";
cout << endl;

getch();
}

2. Java Version
Copy array
class CopyArray
{
public static void main(String args[])
{
int nums[] = {10, 12, 24, 45, 23, 19, 44, 88, 99, 65, 76, 12, 89, 0};
int copy[] = new int[14];
int i;

254
for(i=0; nums[i]!=0; i++)
copy[i] = nums[i];

nums[i] = 0; // terminate copy with zero

System.out.println("Here is the original array:");


for(i=0; nums[i]!=0; i++)
System.out.print(nums[i] + " ");
System.out.println();

System.out.println("Here is the copy:");


for(i=0; nums[i]!=0; i++)
System.out.print(copy[i] + " ");
System.out.println();
}
}

3. C++ version
Swaping of values

#include <iostream>
#include <conio.h>

class Coord
{
public:
int x;
int y;
};

void swap(Coord &a, Coord &b)


{
Coord temp;
temp = a;
a = b;
b = temp;
}

void main()
{
Coord ob1, ob2;
ob1.x = 10;
ob1.y = 20;
ob2.x = 88;

255
ob2.y = 99;
cout << "Original values:\n";
cout << "ob1: " << ob1.x << ", " << ob1.y << "\n";
cout << "ob2: " << ob2.x << ", " << ob2.y << "\n";
cout << "\n";
swap(ob1, ob2);
cout << "Swapped values:\n";
cout << "ob1: " << ob1.x << ", " << ob1.y << "\n";
cout << "ob2: " << ob2.x << ", " << ob2.y << "\n";
getch();
}

3. Java version
Swaping values
class Coord
{
int x;
int y;
};
class SwapDemo
{
static void swap(Coord a, Coord b)
{
Coord temp = new Coord();
temp.x = a.x;
temp.y = a.y;
a.x = b.x;
a.y = b.y;
b.x = temp.x;
b.y = temp.y;
}
public static void main(String args[])
{
Coord ob1 = new Coord();
Coord ob2 = new Coord();
ob1.x = 10;
ob1.y = 20;
ob2.x = 88;
ob2.y = 99;
System.out.println("Original values:");
System.out.println("ob1: " + ob1.x + ", " + ob1.y);
System.out.println("ob2: " + ob2.x + ", " + ob2.y + "\n");
swap(ob1, ob2);
System.out.println("Swapped values:");
System.out.println("ob1: " + ob1.x + ", " + ob1.y);
System.out.println("ob2: " + ob2.x + ", " + ob2.y + "\n");

256
}
}

4. C++ version
Abstract class
#include <iostream>
#include <stdlib>
#include <conio.h>
class IntList //abstract class
{
public:
virtual int getNext() = 0; // pure virtual functions or abstraction function
virtual void putOnList(int i) = 0;
};

class IntArray : public IntList


{
int storage[100];
int putIndex, getIndex;
public:
IntArray()
{
putIndex = 0;
getIndex = 0;
}

int getNext()
{
if(getIndex >= 100)
{
cout << "List Underflow";
exit(1);
}
getIndex++;
return storage[getIndex-1];
}

void putOnList(int i)
{
if(putIndex < 100)
{
storage[putIndex] = i;
putIndex++;
}
else

257
{
cout << "List Overflow";
exit(1);
}
}
};

void main()
{
IntArray nums;
int i;
for(i=0; i<10; i++)
nums.putOnList(i);
for(i=0; i<10; i++)
cout << nums.getNext() << endl;
getch();
}

4. Java version
Abstract class demo

interface IntListIF
{
int getNext();
void putOnList(int i);
}

class IntArray implements IntListIF


{
private int storage[];
private int putIndex, getIndex;
IntArray()
{
storage = new int[100];
putIndex = 0;
getIndex = 0;
}

public int getNext()


{
if(getIndex >= 100)
{
System.out.println("List Underflow");
System.exit(1);
}
getIndex++;

258
return storage[getIndex-1];
}

public void putOnList(int i)


{
if(putIndex < 100)
{
storage[putIndex] = i;
putIndex++;
}
else
{
System.out.println("List Overflow");
System.exit(1);
}
}
}
class ListDemo
{
public static void main(String args[])
{
IntArray nums = new IntArray();
int i;
for(i=0; i<10; i++)
nums.putOnList(i);
for(i=0; i<10; i++)
System.out.println(nums.getNext());
}
}

5. C++ version
Default argument
#include <iostream>
#include <conio.h>

double area(double l, double w=0)


{
if(w==0)
return l * l;
else
return l * w;
}

void main()
{

259
cout << "Area of 2.2 by 3.4 rectangle: ";
cout << area(2.2, 3.4) << endl;
cout << "Area of 3.0 by 3.0 square: ";
cout << area(3.0) << endl;
getch();
}

5. Java version
Default argument

class Area
{
static double area(double l, double w)
{
if(w==0)
return l * l;
else
return l * w;
}
static double area(double l)
{
return l * l;
}
public static void main(String args[])
{
System.out.println("Area of 2.2 by 3.4 rectangle: " +
area(2.2, 3.4));
System.out.println("Area of 3.0 by 3.0 square: " +
area(3.0));
}
}

6. C++ version
Destructor demo
#include <iostream>
#include <stdlib>
#include <conio.h>

const int MAX = 5;


int count = 0;

class X
{
public:

X()

260
{
if(count<MAX)
{
count++;
}
else
{
cout << "Error -- can't construct";
exit(1);
}
}

~X()
{
count--;
}
};

void f()
{
X ob;
}

void main()
{
int i;
for(i=0; i < (MAX*2); i++)
{
f();
cout << "Current count is: " << count << endl;
}
getch();
}

6. Java version
Finalization vs destrcutor
class X
{
static final int MAX = 5;
static int count = 0;

X()
{
if(count<MAX)
{
count++;

261
}
else
{
System.out.println("Error -- can't construct");
System.exit(1);
}
}

protected void finalize()


{
count--;
}

static void f()


{
X ob = new X();
}
public static void main(String args[])
{
int i;
for(i=0; i < (MAX*2); i++)
{
f();
System.out.println("Current count is: " + count);
}
}
}

JDBC
1. Startcontrol paneladministrative toolData Source (ODBC)user DSN for
local server and System DSN for Remote server like in case of JSP and
ServeletMS Access DatabaseaddMicrosoft Access Driver (*.mdb,
*.accdb)finishData Source Name (Vision)selectsearch directory where
data base is located as soon as you selecte directory data base will display in
dastabase name listselect itokokok
2. Now write following code:

262
/******insert demo (initialize way)******/
import java.sql.*;
class insertdemo
{
public static void main(String args[])
{
Connection cn;
Statement stmt;
String qry="insert into emp values('arif',1,'ddun')";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e)
{
System.out.println("Class Not Found");
}
try
{
cn=DriverManager.getConnection("jdbc:odbc:ece");
stmt=cn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
cn.close();
}
catch(SQLException e)
{
System.out.println("SQL error");
}
}
}

/*****insert by keyboard****/
import java.sql.*;
import java.io.*;
class insertdemo2
{
public static void main(String args[]) throws IOException
{
DataInputStream in=new DataInputStream(System.in);

Connection cn;
Statement stmt;

String name,address;
int code;

263
int ch=1;
do
{
System.out.println("Enter name ");
name=in.readLine();
System.out.println("enter code ");
code=Integer.parseInt(in.readLine());
System.out.println("Enter address ");
address=in.readLine();

String qry="insert into tblemployee values ('"+name+"','"+code+"','"+address+"')";

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(Exception e)
{
System.out.println("Bridge creation faile");
}

try
{
cn=DriverManager.getConnection("jdbc:odbc:vision");
stmt=cn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
cn.close();
System.out.println("Records Inserted");
}
catch(Exception e)
{
System.out.println("SQl Error");
}
System.out.println("Do you want to enter more records (1) for yes ");
ch=Integer.parseInt(in.readLine());
}while(ch==1);
}
}

/**************Display******************/
import java.sql.*;
class display
{
public static void main(String args[])

264
{
Connection cn;
Statement stmt;
String qry="select * from tblemployee";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(Exception e)
{
System.out.println("Bridge connection Fialed");
}
try
{
cn=DriverManager.getConnection("jdbc:odbc:vision");
stmt=cn.createStatement();
ResultSet rs=stmt.executeQuery(qry);
System.out.println("Name\tCode\tAddress\n");
while(rs.next())
{
String name=rs.getString("name");
int code=rs.getInt("code");
String address=rs.getString("address");
System.out.println(name+"\t"+code+"\t"+address);
}
stmt.close();
cn.close();
}
catch(Exception e)
{
System.out.println("SQL Error");
}
}
}

/********************Delete*******************/
import java.io.*;
import java.sql.*;
class delete
{
public static void main(String args[]) throws IOException
{
DataInputStream in=new DataInputStream(System.in);

Connection cn;
Statement stmt;

265
System.out.println("Enter code from where you want to delete ");
int code=Integer.parseInt(in.readLine());
String qry="delete from tblemployee where code="+code;

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(Exception e)
{
System.out.println("Bridg Failed");
}
try
{
cn=DriverManager.getConnection("jdbc:odbc:vision");
stmt=cn.createStatement();
stmt.executeUpdate(qry);
System.out.println("Records Deleted");
cn.close();
stmt.close();
}
catch(Exception e)
{
System.out.println("SQL Error");
}

}
}

/*************Update **********************/
import java.io.*;
import java.sql.*;
class update
{
public static void main(String args[]) throws IOException
{
DataInputStream in=new DataInputStream(System.in);

Connection cn;
Statement stmt;

System.out.println("Enter code from where you want to udpate ");


int code=Integer.parseInt(in.readLine());
System.out.println("Enter name and address ");
String name=in.readLine();

266
String address=in.readLine();

String qry="update tblemployee set name='"+name+"',"+"address='"+address+"'"+"where


code="+code;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(Exception e)
{
System.out.println("Bridg Failed");
}
try
{
cn=DriverManager.getConnection("jdbc:odbc:vision");
stmt=cn.createStatement();
stmt.executeUpdate(qry);
System.out.println("Records Updated");
cn.close();
stmt.close();
}
catch(Exception e)
{
System.out.println("SQL Error");
}

}
}

/**********display and insertion in a table******/


import java.sql.*;
class jdbcpro
{
public static void main(String args[])
{
Connection conn;
Statement stmt;
String query="select * from emp";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e)

267
{
System.out.println("Class not found");
}
try
{
conn=DriverManager.getConnection("jdbc:odbc:ece");
stmt=conn.createStatement();
stmt.executeUpdate("Insert into emp values(149,'Rajiv','Director',21000)");
ResultSet rs=stmt.executeQuery(query);
System.out.println("Empno \t Ename \t Job \t Salary");
while(rs.next())
{
int en=rs.getInt("empno");
String na=rs.getString("ename");
String jo=rs.getString("job");
int sa=rs.getInt("salary");
System.out.println(en+"\t"+na+"\t"+jo+"\t"+sa);
}
stmt.close();
conn.close();
}
catch(SQLException ee)
{
System.out.println("SQL error");
}
}
}

/*********Insert, Delete, update, Display operation on


database*******/
import java.sql.*;
import java.io.*;
class jdbcpro2
{
public static void main(String args[]) throws IOException
{
DataInputStream in=new DataInputStream(System.in);

Connection conn;
Statement stmt;
String query="select * from tblemp";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e)

268
{
System.out.println("Class not found");
}
try
{
conn=DriverManager.getConnection("jdbc:odbc:ece");
stmt=conn.createStatement();
int ch=1;
do
{
System.out.println("\n");
System.out.println(" 1: for insert ");
System.out.println(" 2: for delete ");
System.out.println(" 3: for update ");
System.out.println(" 4: for display ");
System.out.println(" 5: for exit ");
System.out.println(" Enter your choice ");
ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1:
System.out.println("Enter EmpNo, Ename, Job, Salary ");
int empno=Integer.parseInt(in.readLine());
String ename=in.readLine();
String job=in.readLine();
double salary=Double.parseDouble(in.readLine());

//stmt.executeUpdate("Insert into tblemp values(149,'Rajiv','Director',21000)");


stmt.executeUpdate("Insert into tblemp
values("+empno+",'"+ename+"','"+job+"',"+salary+")");
System.out.println("Records Inserted");
break;

case 2:
System.out.println("Enter the employee number whose records is to delete ");
int eno=Integer.parseInt(in.readLine());
stmt.executeUpdate("delete from tblemp where Empno="+eno);
System.out.println("Records Deleted ");
break;
case 3:
System.out.println("Enter the employee number whose records is to update ");
eno=Integer.parseInt(in.readLine());
System.out.println("Enter new salary ");
double sal=Double.parseDouble(in.readLine());
stmt.executeUpdate("update tblemp set salary="+sal+" where Empno="+eno);
System.out.println("Records Update ");

269
break;

case 4:
ResultSet rs=stmt.executeQuery(query);
System.out.println("Empno \t Ename \t Job \t\t Salary");
while(rs.next())
{
int en=rs.getInt("empno");
String na=rs.getString("ename");
String jo=rs.getString("job");
int sa=rs.getInt("salary");
System.out.println(en+"\t"+na+"\t"+jo+" \t"+sa);
}
break;
case 5:
System.out.println("Good by");
System.exit(0);
}
}while(ch>=1 && ch<=5);
stmt.close();
conn.close();
}
catch(SQLException ee)
{
System.out.println("SQL error");
}
}
}

Or
import java.io.*;
import java.sql.*;
class jdbcpro
{
public static void main(String args[]) throws IOException
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(r);
Connection conn;
Statement stmt;
String query="select * from emp";
int ch;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}

270
catch(ClassNotFoundException e)
{
System.out.println("Class not found");
}
try
{
conn=DriverManager.getConnection("jdbc:odbc:ece");
stmt=conn.createStatement();
int eno,sal;
String nam,job;
do
{
System.out.println("Enter 1 for insert");
System.out.println("Enter 2 for update");
System.out.println("Enter 3 for delete");
System.out.println("Enter 4 for display");
System.out.println("Enter 5 for quit");
System.out.print("Enter your choice :- ");
ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1 : System.out.print("Enter new empno :- ");
eno=Integer.parseInt(in.readLine());
System.out.print("Enter new name :- ");
nam=in.readLine();
System.out.print("Enter new job :- ");
job=in.readLine();
System.out.print("Enter new salary :- ");
sal=Integer.parseInt(in.readLine());
stmt.executeUpdate("Insert into emp values("+eno+",'"+nam+ " ',' "+job+
"',"+sal+")");
System.out.println("Record Inserted");
System.out.println("");

break;
case 2: System.out.print("Enter the empno that you want to update :- ");
eno=Integer.parseInt(in.readLine());
System.out.print("Enter new Salary :- ");
sal=Integer.parseInt(in.readLine());
stmt.executeUpdate("update emp set salary=" +sal+" where empno="+ eno);
System.out.println("Record Updated");
System.out.println("");

break;
case 3:System.out.print("Enter the empno that you want to delete :- ");
eno=Integer.parseInt(in.readLine());

271
stmt.executeUpdate("delete from emp where empno="+ eno);
System.out.println("Record Deleted");
System.out.println("");

break;
case 4:ResultSet rs=stmt.executeQuery(query);
System.out.println("Empno \t Ename \t Job \t Salary");
while(rs.next())
{
int en=rs.getInt("empno");
String na=rs.getString("ename");
String jo=rs.getString("job");
int sa=rs.getInt("salary");
System.out.println(en+"\t"+na+"\t"+jo+"\t"+sa);
}

break;
case 5: System.out.println("Good bye");
break;
}
}while(ch!=5);
stmt.close();
conn.close();
}
catch(SQLException ee)
{
System.out.println("SQL error");
}
}
}

/*****************connectivity with sql*************/


Steps: Control paneladministrative tool-->ODBCuser DSNaddSQL
ServerFinishenter DSN Name and Server Name (.\sqlexpress)nextnextchange
the default setting (checked)select the database namefinishokok.

import java.sql.*;
import java.io.*;
import java.util.*;
class jdbcpro4
{
public static void main(String args[]) throws IOException
{
DataInputStream in=new DataInputStream(System.in);
Connection conn;
Statement stmt;

272
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e)
{
System.out.println("Class not found");
}
try
{
conn=DriverManager.getConnection("jdbc:odbc:arif");
System.out.println("Enter designation, desginationid ");
String designation=in.readLine();
int designationid=Integer.parseInt(in.readLine());

PreparedStatement pst;
pst=conn.prepareStatement("insert into tbldesignation
values(?,?)");//chat1 is table name
pst.setString(1,designation);
pst.setInt(2,designationid);
boolean b1=pst.execute();
System.out.println(b1);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

JDBC by frame
import java.sql.*;
import java.awt.*;
import java.awt.event.*;

public class framewithjdbc extends Frame implements ActionListener


{
public static Connection con;
public static Statement st;

Label l1,l2;
TextField t1,t2;
Button b1,b2,b3,b4,b5;
TextArea txt;

273
framewithjdbc()
{
l1=new Label("Name");
l2=new Label("Code");

t1=new TextField(15);
t2=new TextField(10);

b1=new Button("Save");
b2=new Button("Exit");
b3=new Button("Update");
b4=new Button("Delete");
b5=new Button("Display");

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);

setLayout(new FlowLayout());
setBackground(Color.cyan);

add(l1);
add(t1);
add(l2);
add(t2);

add(b1);
add(b2);
add(b3);
add(b4);
add(b5);

txt=new TextArea();
add(txt);
}

public int connect(String qry)


{
int ans=0;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e)

274
{
System.out.println("Error is "+e.getMessage());
}
try
{

//con=DriverManager.getConnection("jdbc:odbc:prod","system","ma");//when
password is provided to database
con=DriverManager.getConnection("jdbc:odbc:prod");
st=con.createStatement();
ans=st.executeUpdate(qry);
}
catch(SQLException e)
{
System.out.println("Error is : "+e.getMessage());
}
return ans;
}

public void actionPerformed(ActionEvent ae)


{
String qry="";
if(ae.getSource()==b1)
{
qry="insert into tblemp values (' "+t1.getText()+"
',"+Integer.parseInt(t2.getText())+")";
if(connect(qry)==1)
System.out.println("Records Inserted Successfully .");
else
System.out.println("Records Could not inserted");
}

if(ae.getSource()==b2)
System.exit(0);

if(ae.getSource()==b3)
{
qry="update tblemp set Name='"+t1.getText()+"' where
code="+Integer.parseInt(t2.getText());
if(connect(qry)==1)
System.out.println("Records Updated Successfully .");
else
System.out.println("Records could not updated");
}

275
if(ae.getSource()==b4)
{
qry="Delete from tblemp where
code="+Integer.parseInt(t2.getText());
if(connect(qry)==1)
System.out.println("Records Deleted Successfully .");
else
System.out.println("Records could not deleted");
}

if(ae.getSource()==b5)
{
String s="";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e)
{
System.out.println("Error is "+e.getMessage());
}
try
{
con=DriverManager.getConnection("jdbc:odbc:prod");
st=con.createStatement();
ResultSet rs=st.executeQuery("select * from tblemp");

while(rs.next())
{
String name=rs.getString("name");
int code=rs.getInt("code");
s+=name.trim()+"\t\t"+String.valueOf(code).trim()+"\n";
}
st.close();
con.close();
}
catch(SQLException e)
{
System.out.println("Error is : "+e.getMessage());
}
txt.setText(s);
}//if
}//function

public static void main(String args[])


{
framewithjdbc s=new framewithjdbc();

276
s.setSize(400,400);
s.setVisible(true);
}
}

/*JDBC with swing Frame window


(insert, delete, display , update)*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.JOptionPane;

public class jdbcswi extends JFrame implements ActionListener


{
public static Connection con;
public static Statement st;
public static ResultSet rs;

JLabel l1,l2;
JTextField t1,t2;
JTable jtable;
String colhead[]={"Name","Code"};
String data[][]=new String[20][20];
JButton btninsert,btndelete,btnupdate,btndisplay,btnclose;

jdbcswi()
{
setSize(200,300);
setLayout(new FlowLayout());
l1=new JLabel("Enter Name");
l2=new JLabel("Enter Code");
t1=new JTextField(10);
t2=new JTextField(10);
btninsert=new JButton("Insert");
btndelete=new JButton("Delete");
btnupdate=new JButton("Update");
btndisplay=new JButton("Display");
btnclose=new JButton("Close");

add(l1);

277
add(t1);
add(l2);
add(t2);
add(btninsert);
add(btndelete);
add(btnupdate);
add(btndisplay);
add(btnclose);

jtable=new JTable(data, colhead);


add(jtable);

btninsert.addActionListener(this);
btndelete.addActionListener(this);
btnupdate.addActionListener(this);
btnclose.addActionListener(this);
btndisplay.addActionListener(this);

setVisible(true);
}

public int connect(String qry)


{
int ans=0;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e)
{
System.out.println("Error is "+e.getMessage());
}
try
{

//con=DriverManager.getConnection("jdbc:odbc:prod","system","ma");//when
password is provided to database
con=DriverManager.getConnection("jdbc:odbc:prod");
st=con.createStatement();
ans=st.executeUpdate(qry);
}
catch(SQLException e)
{
System.out.println("Error is : "+e.getMessage());
}
return ans;
}

278
public void actionPerformed(ActionEvent e)
{
String n=t1.getText().trim();;
int a=Integer.parseInt(t2.getText());
String qry="";

if(e.getSource()==btnclose)
System.exit(0);

else if (e.getSource()==btninsert)
{
qry="insert into tblemp values('"+ n + "'," + a + ")";
if(connect(qry)==1)
JOptionPane.showMessageDialog(null,"Records Inserted","Message",1);
else
JOptionPane.showMessageDialog(null,"Records could not
Inserted","Message",0);
}
else if(e.getSource()==btndelete)
{
qry="delete from tblemp where code="+a;
//qry="Delete from tblemp where Name='"+t1.getText().trim()+"'";
if(connect(qry)==1)
JOptionPane.showMessageDialog(null,"Records Deleted","Message",1);
else
JOptionPane.showMessageDialog(null,"Records Could Not
Delete","Message",0);
}

else if(e.getSource()==btnupdate)
{
qry="update tblemp set name='"+n+"' where code="+a;
if(connect(qry)==1)
JOptionPane.showMessageDialog(null,"Records Updated","Message",1);
else
JOptionPane.showMessageDialog(null,"Records Could Not
Updated","Message",0);
}

else if(e.getSource()==btndisplay)
{
String qrye="select * from tblemp";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

279
}
catch(Exception ex)
{
System.out.println("Bridge connection Fialed");
}
try
{
con=DriverManager.getConnection("jdbc:odbc:prod");
st=con.createStatement();
ResultSet rs=st.executeQuery(qrye);
int i=-1,j=0;
while(rs.next())
{
i++;
j=0;
String name=rs.getString("name");
int code=rs.getInt("code");
data[i][j++]=name;
data[i][j]=String.valueOf(code);
}
st.close();
con.close();
}
catch(Exception ee)
{
System.out.println("SQL Error");
}
}
}

public static void main(String args[])


{
jdbcswi obj= new jdbcswi();
obj.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent winevt)
{
System.exit(0);
}
});

}
}

/*****************JDBC by Frame window****************************/

280
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
//<applet code="jdbcswi.class" height=400 width=400></applet>
public class jdbcswi extends JApplet implements ActionListener
{
Connection conn;
Statement stmt;
JLabel l1,l2;
JTextField t1,t2;
JButton b1;
public void init()
{
setLayout(new FlowLayout());
l1=new JLabel("Enter Name");
l2=new JLabel("Enter age");
t1=new JTextField(10);
t2=new JTextField(10);
b1=new JButton("Insert");
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
b1.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{

String n;
int a;

if (e.getSource()==b1)
{
n=t1.getText();
a=Integer.parseInt(t2.getText());
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException ee1)
{
System.out.println("Class not found");

281
}

try
{
conn=DriverManager.getConnection("jdbc:odbc:swidb");
stmt=conn.createStatement();
stmt.executeUpdate("insert into em values('"+ n + "'," + a+")");
stmt.close();
conn.close();
}
catch(SQLException ee)
{
System.out.println("SQL error");
}
}
}
}

/***********PACKAGE FOR CONNECTIVITY*****/


package connecttoora;
import java.sql.*;

public class connector


{
public static Connection con;
public static Statement st;
public static ResultSet rs;
public static String qry;
public static int ans;

public void connect()


{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e)
{
System.out.println("Error is "+e.getMessage());
}
try
{
con=DriverManager.getConnection("jdbc:odbc:prod","system","ma");
st=con.createStatement();
}
catch(SQLException e)

282
{
System.out.println("Error is : "+e.getMessage());
}
}
}

/************CLASS FOR CONNECTIVITY****************/


import java.awt.*;
import java.awt.event.*;
import connecttoora.connector;

public class sale extends Frame implements ActionListener


{
Label l1,l2;
TextField t1,t2;
Button b1,b2,b3,b4;
connector cnn;
sale()
{
cnn=new connector();

l1=new Label("Name");
l2=new Label("Code");

t1=new TextField(15);
t2=new TextField(10);

b1=new Button("Save");
b2=new Button("Exit");
b3=new Button("Update");
b4=new Button("Delete");

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

setLayout(new FlowLayout());
setBackground(Color.cyan);

add(l1);
add(t1);
add(l2);
add(t2);

283
add(b1);
add(b2);
add(b3);
add(b4);
}

public void actionPerformed(ActionEvent ae)


{
if(ae.getSource()==b1)
{
try{
cnn.connect();
connector.qry="insert into tblemp values (' "+t1.getText()+"
',"+Integer.parseInt(t2.getText())+")";
connector.ans=connector.st.executeUpdate(connector.qry);
if(connector.ans==1)
System.out.println("Records Inserted Successfully .");
}
catch(Exception e)
{
System.out.println("Error is :"+e.getMessage());
}
}
if(ae.getSource()==b2)
System.exit(0);

if(ae.getSource()==b3)
{
try{
cnn.connect();
connector.qry="update tblemp set code=100 where
code="+Integer.parseInt(t2.getText());
connector.ans=connector.st.executeUpdate(connector.qry);
if(connector.ans==1)
System.out.println("Records Updated Successfully .");
}
catch(Exception e)
{
System.out.println("Error is :"+e.getMessage());
}
}

if(ae.getSource()==b4)
{
try{
cnn.connect();

284
connector.qry="Delete from tblemp where Name='"+t1.getText()+"'";
connector.ans=connector.st.executeUpdate(connector.qry);
if(connector.ans==1)
System.out.println("Records Deleted Successfully .");
}
catch(Exception e)
{
System.out.println("Error is :"+e.getMessage());
}
}
}

public static void main(String args[])


{
sale s=new sale();
s.setSize(400,400);
s.setVisible(true);
}
}

Servlet
1. create a folder demo
2. create one folder WEB-INF in demo folder

285
3. create two folder classes and lib in WEB-INF folder
4. create a html file (welcome.html) in demo folder
5. create a java file (MyServlet.java) in classes file
6. compile this file by java and store its .class file in the same folder(classes folder)
7. create a xml file (web.xml) in WEB-INF folder

****************** Demo ********************************************


First File
***********************************************************************
<html>
<head>
<title>My First Page</title>
</head>

<body>
<form method=GET action="http://localhost:80/practis1/MyServlet">
<h1>Welcome to Servlet</h1>
<input type="submit">
</body>
</html>

************************************************************************
second file
************************************************************************
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html>");
pw.println("<head><title>My First Program output</title></head>");
pw.println("<body>");
pw.println("<h1>Welcome to Servlet</h1>");
pw.println("</body></html>");
}
}

*********************************************************************
Third file
*********************************************************************

286
<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>

</web-app>
******************************************************************

This application will take two values from text box and will
display that value by java file on server
************************************************************************
*******
1. create a folder demo
2. create one folder WEB-INF in demo folder
3. create two folder classes and lib in WEB-INF folder
4. create a html file (welcome.html) in demo folder
5. create a java file (MyServlet.java) in classes file
6. compile this file by java and store its .class file in the same folder(classes folder)
7. create a xml file (web.xml) in WEB-INF folder
***********************************************************************
<html>
<head>
<title>My First Form</title>
</head>
<body>
<form method=Get action="http://localhost:80/practis2/MyServlet">
<h3>
Please Enter your Name :<input type="text" name="name"><br>
Plseas Enter your Age :<input type="text" age ="age"><br>
</h3>
<br><br>
<input type="submit">
</form>
</body>
</html>

**********************************************************************
import java.io.*;
import javax.servlet.*;

287
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
, ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String n=req.getParameter("name");
int a=Integer.parseInt(req.getParameter("age"));
out.println("<html>");
out.println("<head><title>Hello</title></head>");
out.println("<body>");
out.println("<h1>This is the server Response</h1>");
out.println("<br>Name : "+n);
out.println("<br>Age : "+a);
out.println("</body>");
out.println("</html>");
}
}

**************************************************************
<web-app>
<welcome-file-list>
<welcome-file>welcome.html</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>

</web-app>
***********************************************************************

/*************Insert***************/
<html>
<head>
<title>My Servlet</title>

288
</head>
<body>
<form method="get" action="MyServlet">
<h1> Add Records </h1>
Empno <input type="text" name="empno" size=15 maxlength=15><br><br>
Ename <input type="text" name="ename" size=15 maxlength=15><br><br>
<input type="submit" value="Add Data">
</form>
</body>
</html>

/**********************************************************************/
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
Connection cn;
Statement stmt;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException ex)
{
out.println("Class Not found");
}
try
{
cn=DriverManager.getConnection("jdbc:odbc:emp1");
stmt=cn.createStatement();
int en;
String na;
en=Integer.parseInt(req.getParameter("empno"));
na=req.getParameter("ename");
stmt.executeUpdate("insert into emp values("+en+", '"+na+"')");
out.println("<html>");
out.println("<head><title>Data Accept</title></head>");
out.println("<body><h1>Your Record Accepted Succesfully</h1></body>");
out.println("</html>");

289
cn.close();
}
catch(SQLException e)
{
out.println("SQLError ....");
}
}
}

/**********************************************************************/
<web-app>
<welcome-file-list>
<welcome-file>add.html</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
/**********************************************************************/

/******Delete***************/
<html>
<head>
<title>Delet Demo</title>
</head>
<body>
<form method=GET action="http://localhost:80/delete/MyServlet">
<h3>
Please Enter code :<input type="text" name="empno">
</h3>
<input type="submit">
</form>
</body>
</html>

/*******************************************************************/

import java.io.*;
import java.sql.*;

290
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
Connection cn;
Statement stmt;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
, ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException ex)
{
out.println("Class not Found");
}
try
{
cn=DriverManager.getConnection("jdbc:odbc:emp1");
stmt=cn.createStatement();
int en=Integer.parseInt(req.getParameter("empno"));
stmt.executeUpdate("delete from emp where empno="+en);
out.println("<html>");
out.println("<head><title>Data Delete</title></head>");
out.println("<body><h1>Records has been Deleted</h1></body>");
out.println("</html>");
cn.close();
}
catch(SQLException e)
{
out.println("SQLError.......");
}
}
}

/******************************************************************/

<web-app>
<welcome-file-list>
<welcome-file>delete.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyServlet</servlet-name>

291
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>

/*********Update*********/
<html>
<head>
<title>Update Demo</title>
</head>
<body>
<form method=GET action="http://localhost:80/update/update">
<h3>
Please Enter code :<input type="text" name="empno">
Please Enter name :<input type="text" name="ename">
</h3>
<input type="submit">
</form>
</body>
</html>

/***********************************************************/
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class update extends HttpServlet
{
Connection cn;
Statement stmt;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
, ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException ex)
{

292
out.println("Class not Found");
}
try
{
cn=DriverManager.getConnection("jdbc:odbc:emp1");
stmt=cn.createStatement();
int en=Integer.parseInt(req.getParameter("empno"));
String na=req.getParameter("ename");
stmt.executeUpdate("update emp set ename='"+na+"' where empno="+en);
out.println("<html>");
out.println("<head><title>Data Updated</title></head>");
out.println("<body><h1>Records has been Updated</h1></body>");
out.println("</html>");
cn.close();
}
catch(SQLException e)
{
out.println("SQLError.......");
}
}
}

/*********************************************************************/

<web-app>
<welcome-file-list>
<welcome-file>update.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>update</servlet-name>
<servlet-class>update</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>update</servlet-name>
<url-pattern>/update</url-pattern>
</servlet-mapping>
</web-app>

This application will display values of database by


servlet file on server
**************************** Display **************************
1. create a folder demo

293
2. create one folder WEB-INF in demo folder
3. create two folder classes and lib in WEB-INF folder
4. create a html file (display.html) in demo folder
5. create a java file (showdata.java) in classes file
6. compile this file by java and store its .class file in the same folder(classes folder)
7. create a xml file (web.xml) in WEB-INF folder
************************************************************************
*******
<html>
<head>
<title> My First form</title>
</head>
<body>
<form method=GET action="http://localhost:80/displaydata/showdata">
<input type="Submit">
</form>
</body>
</html>

*******************************************************************

import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class showdata extends HttpServlet
{
Connection con;
Statement stmt;
String qry="select * from emp";
public void service(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
{
ServletOutputStream out=res.getOutputStream();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException ex)
{
out.println("class not found");
}
try
{
con=DriverManager.getConnection("jdbc:odbc:emp1");
stmt=con.createStatement();

294
res.setContentType("text/html");
ResultSet rs=stmt.executeQuery(qry);
out.println("<html>");
out.println("<body>");
out.println("<table border>");
out.println("<tr><td>empno</td><td>ename</td></tr>");
while(rs.next())
{
int eno=rs.getInt("empno");
String name=rs.getString("ename");
out.println("<tr><td>"+eno+"</td><td>"+name+"</td></tr>");
}
con.close();
}
catch(SQLException e)
{
out.println("SQLError");
}
}
}

******************************************************************
<web-app>

<welcome-file-list>
<welcome-file>display.html</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>showdata</servlet-name>
<servlet-class>showdata</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showdata</servlet-name>
<url-pattern>/showdata</url-pattern>
</servlet-mapping>
</web-app>
********************************************************************

/***Insert-Delete-Update-Display***/
<html>
<head>
<title>Welcome</title>
</head>

295
<body>
<h1><Marquee behavior ="Alternate" bgcolor="Gray">Welcome to Excess
Computer</marquee></h1>
<hr size=10 color="Green">
<p align="Justify"> This is a welcome page through which you can see and add the new
records.
This is your first database program that will help you to see the records also.</p>

<table width=100% cellspacing=10>


<tr>
<td width=20% align="center" bgcolor="ffaaaa"><a href="Insert.html">Insert</a></td>
<td width=20% align="center" bgcolor="aaaaff"><a href="delete.html">Delete</a></td>
<td width=20% align="center" bgcolor="aaffaa"><a
href="update.html">Update</a></td>
</tr>
</table>
</body>
</html>

296

You might also like