Advanve Java Book
Advanve Java Book
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
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.
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>*/
4
}
public void stop()
{
msg=msg+" stop()-->";
}
public void paint(Graphics g)
{
msg=msg+"paint() method ";
g.drawString(msg,20,50);
}
}
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>*/
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);
}
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>*/
7
import java.awt.*;
import java.applet.*;
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();
}
8
g.drawString("Account Active : "+active,0,58);
}
}
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){}
}
9
<param name="columns" value="4">
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>
11
<head><title>Welcome to java Applets</title> </head>
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.>
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-->";
}
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>
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>
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>
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)
16
}
17
{
TextField Name,Age,Salary,Bonus;
Label l1,l2,l3,l4;
TextArea t;
String s;
Button Submit, Close, Clear;
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("");
}
});
}
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.
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> */
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);
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);
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>*/
(100, 100)
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>*/
(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>*/
(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:
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>
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);
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.
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);
/*********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);
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);
}
/*************Umrella by Laxmi*************/
import java.awt.*;
import java.applet.*;
34
g.fillArc(490,38,18,30,0,180);
}
}
/*
<applet code = "umbrella.class" width=1000 height=1000></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.
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:
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);
}
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;
38
{
x=me.getX();
y=me.getY();
msg="Down";
repaint();
}
39
t2=new TextField(10);
t3=new TextField(10);
add(l1);
add(t1);
add(t2);
add(t3);
l1.addMouseListener(this);
}
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();
}
/***********************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.*;
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);
}
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();
}
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;
}
46
adapterdemo adp;
public mymousemotionadapter(adapterdemo obj)
{
adp=obj;
}
Inner Class
An inner class is a class defined within other class, or event within an expression.
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;
}
48
import java.applet.*;
import java.awt.event.*;
Controls-> Controls are the components that allow a user to interact with your
application in various ways-for example, Button, Label, Check box etc.
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)
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);
l4=new Label();
add(l4);
}
}
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);
}
}
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.
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.
//TextField Demo
import java.awt.*;
import java.applet.*;
add(t1);
add(t2);
add(t3);
add(t4);
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>*/
add(f1);
add(f2);
b1=f1.isEditable();
b2=f2.isEditable();
}
54
{
TextField t1,t2,t3;
boolean b1,b2,b3;
char ch;
t1.setEditable(true);
t2.setEditable(false);
add(t1);
add(t2);
add(t3);
b1=t1.isEditable();
b2=t2.isEditable();
b3=t3.echoCharIsSet();
ch=t3.getEchoChar();
}
/**********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);
}
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
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.
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();
}
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";
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();
}
Example:/*************Button Demo****************************/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
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();
}
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;
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>*/
add(winXP);
add(winNT);
63
add(winVista);
add(win7);
winXP.addItemListener(this);
winNT.addItemListener(this);
winVista.addItemListener(this);
win7.addItemListener(this);
}
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();
}
}
/* <applet code="check.class" width=200 height=200>
</applet> */
65
import java.awt.event.*;
import java.applet.*;
/*<applet code=cbgroup width=600 height=600></applet>*/
add(winXP);
add(winNT);
add(winVista);
add(win7);
winXP.addItemListener(this);
winNT.addItemListener(this);
winVista.addItemListener(this);
win7.addItemListener(this);
}
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> */
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.
/*choice controls*/
import java.awt.*;
import java.applet.*;
public class choice_control extends Applet
{
Choice c;
String s1,str;
int index,count=0;
add(c);
68
}
/*<applet code=choice_control width=500 height=500></applet>*/
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);
}
}
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;
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;
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");
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.
/*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;
add(s1);
add(s2);
add(s3);
}
g.drawString(String.valueOf(i),100,100);
g.drawString(String.valueOf(j),200,200);
}
}
75
Scrollbar hr,vr;
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);
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.
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(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>*/
//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
78
Checkbox winxp, win7, winvista;
add(winxp);
add(win7);
add(winvista);
winxp.addItemListener(this);
win7.addItemListener(this);
winvista.addItemListener(this);
}
/*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);
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);
81
male=new Checkbox("Male");
female=new Checkbox("Female");
p6.add(lblgender);
p6.add(male);
p6.add(female);
add(p6);
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
Here compobj is the component to be added, and region specifies where the component
will be added.
add(b1, BorderLayout.EAST);
add(b2, BorderLayout.WEST);
add(b3, BorderLayout.SOUTH);
add(b4, BorderLayout.NORTH);
add(b5, BorderLayout.CENTER);
}
}
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";
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.
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.
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";
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");
}
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);
}
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;
87
}
}
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);
}
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);
}
}
2. Second Form
import java.awt.*;
public class demoform extends Frame
{
String str;
demoform(String s)
{
90
str=s;
}
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);
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);
}
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);
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);
}
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.
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.
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.
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);
}
98
other=new Button("Other");
add(win);
add(other);
card=new CardLayout();
oscards=new Panel();
oscards.setLayout(card); //set panel layout to card layout
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);
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
}
102
{
System.exit(0);
}
});
}
/********************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);
}
});
}
}
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
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();
105
Panel p5=new Panel();
designation=new Label("Designation");
p5.add(designation);
tdesignation=new TextField(15);
p5.add(tdesignation);
add(p5);
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.
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().
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)
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:
Object getItem()
108
{
MenuBar mb=new MenuBar();
Frame f=new Frame("Menu Bar");
f.setSize(250,250);
f.setVisible(true);
f.setMenuBar(mb);
}
}
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);
}
}
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();
f.setSize(250,250);
f.setVisible(true);
f.setMenuBar(mb);
}
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);
}
}
/*******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);
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);
}
}
file.add(open);
file.add(close);
file.add(exit);
open.addActionListener(this);
close.addActionListener(this);
exit.addActionListener(this);
addWindowListener(new WindowAdapter()
{
114
public void windowClosing(WindowEvent e)
{
System.exit(1);
}
});
}
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();
}
}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=menudemo width=250 height=250></applet>*/
menuframe(String title)
{
super(title);
MenuBar mbar=new MenuBar();
setMenuBar(mbar);
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);
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);
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);
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;
}
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();
}
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);
}
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);
}
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
}
events()
{
f=new Frame("Events Test");
b=new Button("Press Me");
b.setActionCommand("ButtonPressed");
}
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();
}
}
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
}
});
/*******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="";
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);
}
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> */
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;
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
/**************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
}
Dialog Boxes
/*File Dialog Box*/
import java.awt.*;
import java.awt.event.*;
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);
}
});
132
class sampledialog extends Dialog implements ActionListener
{
sampledialog(Frame parent, String title)
{
super(parent, title, false);
setLayout(new FlowLayout());
setSize(300,200);
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);
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("-"));
debug=new CheckboxMenuItem("Debug");
edit.add(debug);
test=new CheckboxMenuItem("Testing");
edit.add(test);
mbar.add(edit);
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);
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 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();
}
136
}
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()
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);
}
}
138
//FileDialog fd=new FileDialog(f, "File Dialog",FileDialog.SAVE);
//FileDialog fd=new FileDialog(f);
fd.setVisible(true);
}
}
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()
140
add(txt);
}
}
/*******************************************/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code=showfonts width=500 height=500></applet>
GraphicsEnvironment
ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
FontList=ge.getAvailableFontFamilyNames();
for(int i=0;i<FontList.length;i++)
c.add(FontList[i]);
add(c);
c.addItemListener(this);
}
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.
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();
}
}
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();
/*if(fontstyle==Font.BOLD)
msg+="Bold";*/
g.drawString(msg,4,16);
}
}
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.
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;
}
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);
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.
/* <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>
*/
147
}
catch(NumberFormatException e)
{
fontsize=4;
}
align=LEFT;
addMouseListener(new mymouseadapter(this));
}
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();
}
}
}
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> */
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
}
}
160
int x=(w-fm.stringWidth(s))/2;
g.drawString(s,x,h-20);
}
repaint();
Thread.sleep(500);
}catch(Exception ex){}
}
}
}
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.
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.
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.
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.
getHostName() : It returns the host name that the invoking InetAddress object
represents.
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.
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.*;
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....");
}
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
}
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);
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];
while(true)
{
DatagramPacket request = new DatagramPacket(buffer,buffer.length);
ds.receive(request);
System.out.println(new
String(request.getData(),0,request.getLength()));
171
-------------------------------------Client-----------------------------
import java.net.*;
import java.io.*;
class client1
{
public static DatagramSocket ds;
byte buffer[]=new byte[1024];
********************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));
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();
System.out.println(dis.readUTF());
//br.close();
s1.close();
}
catch(ConnectException connExc)
{
System.err.println("Could not connect");
}
catch(IOException e)
{
}
}
}
175
Server Program
import java.net.*;
class udpip_server
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
Client Program
import java.net.*;
class udpip_client
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
176
{
DatagramPacket p=new DatagramPacket(buffer,buffer.length);
ds.receive(p);
System.out.println(new String(p.getData(),0,p.getLength()));
}
}
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();
}
}
frame2()
{
JLabel l=new JLabel("Hello java Swing");
add(l);
}
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);
}
}
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",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);
}
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);
}
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);
}
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;
t=new JTextField(10);
t.setText(Calendar.getInstance().getTime().toString());
t.setActionCommand("Time : ");
t.addActionListener(this);
add(t);
setVisible(true);
}
182
{
System.out.println(ae.getActionCommand());
System.out.println(t.getText());
}
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);
}
/***************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);
add(t1);
add(t2);
add(t3);
add(t4);
setVisible(true);
}
/************************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;
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());
f.add(btnok);
f.add(btncancel);
f.add(btn);
f.setVisible(true);
}
public static void main(String args[])
{
button obj=new button();
}
}
185
JTextField jtf;
jtf=new JTextField(15);
contentPane.add(jtf);
}
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;
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);
}
/*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());
f.add(c1);
f.add(c2);
f.add(c3);
f.add(c4);
f.add(c5);
f.add(c6);
f.setVisible(true);
}
189
import javax.swing.*;
/*<applet code=checkbox2 width=400 height=400></applet>*/
public class checkbox2 extends JApplet implements ItemListener
{
JTextField jtf;
jtf=new JTextField(15);
add(jtf);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb=(JCheckBox)ie.getItem();
jtf.setText(cb.getText());
}
}
radiobutton()
{
f=new JFrame("Radio Buttons");
f.setSize(400,400);
f.setLayout(new FlowLayout());
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);
}
img=new ImageIcon("a1.gif");
191
b1.addActionListener(this);
add(b1);
t=new JTextField(5);
add(t);
}
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);
}
/*********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);
}
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);
}
}
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);
}
}
197
JPanel p3=new JPanel();
p1.setBackground(Color.cyan);
p2.setBackground(Color.green);
p3.setBackground(Color.yellow);
cp.setLayout(new BorderLayout());
cp.add(tb);
}
}
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);
}
}
/***************** 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;
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);
}
});
}
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;
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;
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);
}
}
}
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()));
}
});
lblorientation=new JLabel("Orientation");
lblorientation.setText("Orientation :
"+String.valueOf(pb.getOrientation()));
add(lblorientation);
setVisible(true);
}
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);
}
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");
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;
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);
209
Dialog Box
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JButton b;
dialog()
{
setSize(500,500);
setLayout(new FlowLayout());
b=new JButton("OK");
add(b);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
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.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
f.add(b1);
f.add(b2);
f.add(b3);
f.setVisible(true);
}
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();
}
}
dialogbox()
{
setSize(200,200);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1=new JButton("Ok");
b1.addActionListener(this);
add(b1);
setVisible(true);
}
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);
jmenu0.add(jmenuitem01);
jmenu0.add(jmenuitem02);
213
jmenu0.addSeparator();
jmenu0.add(jmenuitem03);
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);
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);
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);
}
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;
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");
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);
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);
}
frmfirst()
218
{
setSize(500,500);
setLayout(new FlowLayout());
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);
}
frmsecond(String str)
{
setSize(300,300);
setLayout(new FlowLayout());
219
txt=new JTextArea();
txt.setText(str);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
mainform()
{
setSize(1500,1000);
setLayout(null);
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);
}
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);
txtname=new JTextField();
txtname.setBounds(180,40,150,25);
add(txtname);
txtage=new JTextField();
txtage.setBounds(180,70,50,25);
add(txtage);
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);
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);
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);
chkug=new JCheckBox("Graduate");
chkug.setBounds(100,340,80,25);
add(chkug);
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);
}
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;
}
}
frmoutput()
{
setLayout(null);
setSize(500,300);
setVisible(true);
}
}
Student form with output
226
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
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);
txtname=new JTextField();
txtname.setBounds(220,60,100,25);
txtname.setFont(fnt);
add(txtname);
txtrollno=new JTextField();
txtrollno.setBounds(220,100,100,25);
227
txtrollno.setFont(fnt);
add(txtrollno);
txtage=new JTextField();
txtage.setBounds(220,140,100,25);
txtage.setFont(fnt);
add(txtage);
txtclass=new JTextField();
txtclass.setBounds(220,180,100,25);
txtclass.setFont(fnt);
add(txtclass);
cmbsection=new JComboBox();
cmbsection.addItem("A");
cmbsection.addItem("B");
cmbsection.addItem("C");
cmbsection.addItem("D");
cmbsection.setBounds(220,220,50,25);
add(cmbsection);
228
btnclear = new JButton("CLEAR");
btnclear.setBounds(130,290,90,20);
btnclear.setFont(fnt);
add(btnclear);
btnok.addActionListener(this);
btnclear.addActionListener(this);
btncancel.addActionListener(this);
setVisible(true);
}
229
}
}
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);
}
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());
}
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;
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);
if(ret==JFileChooser.APPROVE_OPTION)
{
File file=fileopen.getSelectedFile();
String text=readFile(file);
txt.setText(text);
}
}
});
add(btn);
setVisible(true);
}
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;
}
pnl=new JPanel();
pnl.setBorder(BorderFactory.createEmptyBorder(50, 50, 100,
100));//this option will set the size of panel
238
pnl.setBackground(color);
}
});
add(pnl);
setVisible(true);
}
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;
239
g.drawImage(imgs1,0,0,this);
g.drawImage(imgs2,100,100,this);
}
}
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;
/******************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;
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent me)
{
mx=me.getX();
my=me.getY();
repaint();
}
242
}
});
}
import java.awt.*;
import java.awt.Image;
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();
}
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;
}
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;
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;
246
}
public void update() {}
CropImageFilter
//<applet code=TileImage.class width=288
height=399></applet>
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
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) { };
}
248
Tile Image
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) { };
}
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;
251
}
catch (InterruptedException e) { };
Thread t = new Thread(this);
t.start();
}
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;
};
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
p1 = nums;
p2 = copy;
while(*p1)
*p2++ = *p1++;
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];
3. C++ version
Swaping of values
#include <iostream>
#include <conio.h>
class Coord
{
public:
int x;
int y;
};
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;
};
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);
}
258
return storage[getIndex-1];
}
5. C++ version
Default argument
#include <iostream>
#include <conio.h>
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>
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);
}
}
JDBC
1. Startcontrol paneladministrative toolData Source (ODBC)user DSN for
local server and System DSN for Remote server like in case of JSP and
ServeletMS Access DatabaseaddMicrosoft Access Driver (*.mdb,
*.accdb)finishData Source Name (Vision)selectsearch directory where
data base is located as soon as you selecte directory data base will display in
dastabase name listselect itokokok
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();
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;
266
String address=in.readLine();
}
}
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");
}
}
}
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());
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");
}
}
}
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.*;
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);
}
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;
}
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
276
s.setSize(400,400);
s.setVisible(true);
}
}
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);
btninsert.addActionListener(this);
btndelete.addActionListener(this);
btnupdate.addActionListener(this);
btnclose.addActionListener(this);
btndisplay.addActionListener(this);
setVisible(true);
}
//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");
}
}
}
}
}
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);
}
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");
}
}
}
}
282
{
System.out.println("Error is : "+e.getMessage());
}
}
}
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);
}
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());
}
}
}
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
<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>
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>
296