Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
1
RAJEEV GANDHI MEMORIAL COLLEGE OF ENNG&TECH
(Autonomous)
NANDYAL
Department of Computer Science and Engineering
Advanced Java Programming Lab Manual
For
III B.TECH I SEM CSE
Regulation:R15
RAJEEV GANDHI MEMORIAL COLLEGE OF ENGINEERING & TECHNOLOGY
(AUTONOMOUS)
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
VISION OF THE DEPARTMENT
To empower students with cutting edge technologies in computer science
and engineering
To train the students as entrepreneurs in computer science and
engineering to address the needs of the society
To develop smart applications to disseminate information to rural people
MISSION OF THE DEPARTMENT
To become the best computer science and engineering department in the
region offering undergraduate, post graduate and research programs in
collaboration with industry
To incubate, apply and spread innovative ideas by collaborating with
relevant industries and R & D labs through focused research groups.
To provide exposure to the students in the latest tools and technologies to
develop smart applications for the society
RGM-R-2015
RAJEEV GANDHI MEMORIAL COLLEGE OF ENGG.& TECH., NANDYAL-518 501
AUTONOMOUS
COMPUTER SCIENCE AND ENGINEERING
Detailed Syllabus
III B. Tech. I- Sem (CSE) P C
3 2
(A0581155) ADVANCED JAVA PROGRAMMING LAB
OBJECTIVE:
To create a fully functional window based applications. To develop GUI applications like Calculator,
Notepad, Simple user forms, and Designing and implementing Component based application like Jelly
Beans, Color bean, and also designing of server side pages, client server interactions with TCP.
OUTCOMES:
Student can able to Designing of window based applications.
Student can able to create a client and server communication using net package.
Student can able to design reusable software components using java beans.
Able to develop server side programming.
Able to develop the dynamic web pages using JSP.
CO-PO MAPPING:
CO/PO
PO1
PO2
PO3
PO4
PO5
PO6
PO7
PO8
PO9
PO10
PO11
PO12
PSO 1
PSO 2
PSO 3
CO1
2
1
1
1
2
2
3
2
1
CO2
2
1
2
2
2
1
2
2
CO3
2
3
1
1
1
2
2
1
CO4
2
2
2
1
2
3
2
CO5
2
2
2
2
1
2
1
HARDWARE AND SOFTWARE REQUIRED:
A working computer system with either Windows or Linux (with minimum configurations- HDD:40
GB, RAM: 512MB) .
Simple Editor Notepad or other editor tools like Edit plus or notepad++.
A web browser IE/ Firefox/ chrome.
Apache Tomcat web server.
JVM(Java virtual machine) must be installed on your system
BDK(Bean development kit) must be also be installed
1.
A) Write a Java Program to create an applet that show a simple message along with background and
foreground colors?
B)
Write a Java Program to create an applet that scrolls a message from left to right?
2.
A) Write a Java Program to create an applet that receives an integer in one text field, and computes its
factorial value and returns it in another text field, when the button named “Compute is clicked.
B)
Write a Java Program to create an applet that receives a string and returns either it Uppercase or
Lowercase, Reverse of given string, and length of a given String.
3.
A) Write a java program to draw Lines, ovals, filled ovals and arcs, filled arcs?
B)
Write a java program to draw rectangle, filled rectangle and rounded rectangle and filled rounded
rectangle with any two colors?
C)
Write a java program to draw a smiley face?
4.
A) Write a Java program to demonstrate the mouse event handlers.
B)
Write a Java program to demonstrate the key event handlers.
5.
Write a Java program that creates a user interface to perform integer divisions. The user enters two numbers
in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed in the Result field when
the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw a Number
Format Exception. If Num2 were Zero, the program would throw an Arithmetic Exception Display the
exception in a message dialog box.
6.
Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits
and for the +, -,*, % operations. Add a text field to display the result.
7.
A) Write a Java Program to create 4 push Buttons bearing the names of 4 colors. When a button is licked,
that particular color is set as background color in a frame?
B. Write a Java Program that simulates a traffic light. The program lets the user select one of three lights:
red, yellow, or green. When a radio button is selected, the light is turned on, and only one light can be on at
a time No light is on when the program starts.
RGM-R-2015
RAJEEV GANDHI MEMORIAL COLLEGE OF ENGG.& TECH., NANDYAL-518 501
AUTONOMOUS
COMPUTER SCIENCE AND ENGINEERING
Detailed Syllabus
8.
Write a Java Program a simple user form which reads the name of a user and mail id in Text fields, select
gender with radio buttons, and selects some Known languages using checkboxes, and also enters an address
in a text area. After filling details whenever a user press the “submit” button, then displays all the
information about the user input.
9.
Write a Java Program to create multiple frames, which create a Frame2 with a ‘back ‘button, such that when
a user click ‘back’ button, Frame 2 is closed and we see the Frame1 only?
10.
A) Write a Java Program to create an applet using Swings which contains two push buttons. If a user
presses a particular button then display a message ‘selected’ button is pressed.
B)
Write a Java Program to create a frame using swing in which create a push button with a label and
image. When the button is clicked an image is displayed in the Frame?
11.
Write a Java Program to create a student table, which includes name, roll no, branch and age or DOB?
12.
Write a Java Program to create a tabbed pane with two tabs. In the first tab sheet, display some push buttons
with names of Branches. In second tab sheet, display checkboxes with names of subjects.
13.
A) Write a java program to create a menu with several menu items by implementing JMenu.
B)
Write a java program to create a combo box with some name of some places. The user can select any
one name from the list and the selected country name is displayed in the frame? (Use JComboBox)
C)
Write a java program to select multiple places and displayed in Frame using JList?
14.
Write a java program to create a simple visual bean with a area filled with a color. The shape of the area
depends on the property shape. If it is set to true then the shape of the area is Square and it is Circle, if it is
false. The color of the area should be changed dynamically for every mouse click. The color should also be
changed if we change the color in the “property window “.
15.
Write a java program to create a bean that performs conversion of American dollar to Indian rupee.
16.
Write a java program to create a bean that counts the number of button clicks?
17.
A) Write a Java program that implements a simple client/server application. The client sends data to a
server. The server receives the data, uses it to produce a result, and then sends the result back to the client.
The client displays the result on the console. For ex: The data sent from the client is the radius of a circle,
and the result produced by the server is the area of the circle. (Use java.net)
B)
Write a Java program to retrieve the information from the given URL? (Note: Read the URL from
Command Line Arguments).
18.
Write a java program to create a sample TCP chat application where client and server can chat with each
other?
19.
Installation of Apache Tomcat webserver.
20.
A) Write a java Program to create a simple servlet and run it using tomcat server.
B)
Write a java Program to create a servlet to read information from client Registration page?
21.
A) Write a java Program to create a JSP page to display a simple message along with current Date?
B)
Write a java Program to create a JSP page to display the random number?
22.
Write a java Program to create a User request page in JSP?
REFERENCES:
1.
Java; the complete reference, 7th editon, Herbert schildt, TMH.
2.
Introduction to Java programming 6th edition, Y. Daniel Liang, pearson education.
3.
An introduction to Java programming and object oriented application development, R.A. Johnson-
Thomson.
4.
Core Servlets and Java Server pages volume1: Core Technologies By Marty Hall and Larry Brown
Pearson.
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
2
List of Experiments
SNO
EXPERIMENT
PAGE NO
1
a) Write a Java program to create an Applet that displays
student information and also set foreground and backgrounds.
b)Write a Java Program to create an applet that scrolls a
message from left to right?
c) Write a Java program to create an Applet that reads
Employee information using parameters and displays name of
employee ,designation ,salary and tax.
6
8
11
2
a. Write a java program to draw Lines, ovals, filled ovals and
arcs, filled arcs?
b. Write a java program to draw rectangle, filled rectangle and
rounded rectangle and filled rounded rectangle with any two
colors.
c) . Write a java program to draw a smiley face?
13
15
17
3
a .Write a Java program to create an Applet that displays
4buttons each represents different colors.if a user click on
particular button then that color is set as back ground to applet.
b . Write a Java program to create an Applet that displays
2buttons .if a user click on one button then change name of
another button and display the button clicked and vice-versa?
c. Write a Java program to create an Applet that displays
2TextFields and labels User Name and Password . Display Text
Field entered and display selected text in username &display
password?
d.write a Java program that displays 4buttons and also count
Number of button clicks on each button?
19
21
24
27
4
a. 4A. Write a Java Program to create an applet that receives an
integer in one text field, and computes its factorial value and
returns it in another text field, when the button named
“Compute” is clicked.
b.Write a Java Program to create an applet that receives a
string and returns either it Uppercase or Lowercase, Reverse of
30
33
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
3
given string, and length of a given String.
c. Write a Java program to find reverse of a given number and
also checks whether it is palindrome or not and display a status
message.
36
5
a. Write a Java program to demonstrate the mouse event
handlers.
b. Write a Java program to demonstrate the key event handlers.
39
42
6
a.Write a Java Program that simulates a traffic light. The
program lets the user select one of three lights: red, yellow, or
green. When a radio button is selected, the light is turned on,
and only one light can be on at a time No light is on when the
program starts.
b. Write a Java Program to create multiple frames, which create
a Frame2 with a „back „button, such that when a user click
„back‟ button, Frame 2 is closed and we see the Frame1 only?
44
46
7
Write a Java Program a simple user form which reads the name
of a user and mail id in Text fields, select gender with radio
buttons, and selects some Known languages using checkboxes,
and also enters an address in a text area. After filling details
whenever a user press the “submit” button, then displays all the
information about the user input.
49
8
Write a Java program that works as a simple calculator. Use a
grid layout to arrange buttons for the digits and for the +, -,*, %
operations. Add a text field to display the resu1lt.
52
9
a. Write a Java program to create buttons with different
borders?
b. Write a Java Program to create a frame using swing in which
create a push button with a label and image. When the button is
clicked an image is displayed in the Frame?
56
58
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
4
c.Write a Java Program to choose courses with check boxes and
gender through radio buttons , display selected items in text
area?
60
10
a. write a Java program to implement JcomboBox where we can
select state and language and display selected items using lables?
b.write a Java program to implement a JList where we can
select multiple courses and display them in Text area.
c.Write a Java program that creates a user interface to perform
integer divisions. The user enters two numbers in the text fields,
Num1 and Num2. The division of Num1 and Num2 is displayed
in the Result field when the Divide button is clicked. If Num1 or
Num2 were not an integer, the program would throw a Number
Format Exception. If Num2 were Zero, the program would
throw an Arithmetic Exception Display the exception in a
message dialog box.
62
64
68
11
a.write a Java program to create three tabs which includes push
buttons,check boxes and comboBox in each tab respectively
which represents color buttons,list of courses with check boxes
and places with combo box?
11b.Write a Java Program to create a student table, which
includes name, roll no, branch and age or DOB?
11C. Write a java program to create a menu with several menu
items by implementing JMenu?
69
72
74
12
a.. Write a Java program to retrieve the information from the
given URL? (Note: Read the URL from Command Line
Arguments).
b.Write a Java program that implements a simple client/server
application. The client sends data to a server. The server
receives the data, uses it to produce a result, and then sends the
77
78
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
5
result back to the client. The client displays the result on the
console. For ex: The data sent from the client is the radius of a
circle, and the result produced by the server is the area of the
circle. (Use java.net)
13
a. Write a java program to create a sample TCP chat
application where client and server can chat with each other?
b.Write a java program to perform a simple conversation with
UDP model?
80
82
14
a.Write a java program to create a bean that counts the number
of mouse clicks?
B Write a java program to create a bean that counts the number
of button clicks?
C.Write a Java program to create a bean that display employee
name, salary, designation and company?
84
86
87
15
A. Write a Java Program to create a bean to convert the Indian
Rupee to American dollar and to pound?
B. Write a Java Program to create a bean to stimulate Traffic
signals?
C.Write a Java Program to create bean to implement color
bean?
90
93
95
16
Installation of Apache Tomcat webserver
97
1 7
a)Write a servlet program to create a simple servlet and test it?
b.Write a servlet program to read the client request parameters.
104
105
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
6
WEEK 1:
A. Write a Java program to create an Applet that displays student information and also set
foreground and backgrounds.
1. Source:
import java.awt.*;
import java.applet.*;
/*<Applet code="MsgApplet",height="150",width="300">
</Applet>*/
public class MsgApplet extends Applet
{
String name,branch,sec;
int rno;
public void init()
{
name="abc";
branch="CSE";
sec="A";
rno=500;
setBackground(Color.gray);
setForeground(Color.green);
}
public void paint(Graphics g)
{
g.drawString("Name of Student:"+name,50,40);
g.drawString("BRANCH :"+branch,50,60);
g.drawString("RNO :"+rno,50,70);
g.drawString("SECTION :"+sec,50,80);
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
7
Output:
In cmd prompt:
D:\cse>javac MsgApplet.java
D:\cse>appletviewer MsgApplet.java
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
8
1. B. Write a Java Program to create an applet that scrolls a message from left to right?
Source:
import java.awt.*;
import java.applet.*;
/* <applet code="Scroll" height= 200 width=500></applet> */
public class Scroll extends Applet implements Runnable
{
String msg=" *****Moving Text***** ";
Thread t=null;
int l;
boolean flag;
public void init()
{
setBackground(Color.pink);
setForeground(Color.blue);
}
public void start()
{
t= new Thread(this);
flag=false;
t.start();
}
public void run()
{
char ch;
for(;;)
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
9
{
try
{
repaint();
Thread.sleep(250);
ch=msg.charAt(0);
l=msg.length();
msg=msg.substring(1,l);
msg+=ch;
if(flag)
break;
}
catch(InterruptedException e) { }
}
}
public void stop()
{
flag=true;
t=null;
}
public void paint(Graphics g)
{
g.drawString(msg,120,80);
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
10
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
11
1 C .Write a Java program to create an Applet that reads Employee information using parameters
and displays name of employee ,designation ,salary and tax.
SOURCE:
import java.awt.*;
import java.applet.*;
/* <applet code ="EmpDetails" height=100 width=200>
<param name="e1" value="Ram">
<param name="e2" value="Manager">
<param name="e3" value=160000.50>
</applet>
*/
public class EmpDetails extends Applet
{
String name,desg,str;
float sal,tax;
public void start()
{
name=getParameter("e1");
desg=getParameter("e2");
str=getParameter("e3");
sal=Float.parseFloat(str);
caltax(sal);
}
public void caltax(float sal)
{
if(sal<=100000)
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
12
tax=0.0f;
else if (sal>100000 && sal<=200000)
tax= sal*0.01f;
else
tax=sal*0.02f;
}
public void paint(Graphics g)
{
g.drawString("Name of Emp:"+name,20,30);
g.drawString("Designation:"+desg,20,60);
g.drawString("Salary :"+sal,20,90);
g.drawString("Tax :"+tax,20,120);
}
}
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
13
WEEK 2:
2 a. Write a java program to draw Lines, ovals, filled ovals and arcs, filled arcs?
SOURCE:
import java.awt.*;
import java.applet.*;
/*<Applet code="TwoA",height="300",width="300"></Applet>*/
public class TwoA extends Applet
{
public void paint(Graphics g)
{
g.drawLine(20,0,20,40);
g.drawLine(0,20,40,20);
g.drawOval(40,40,100,50);
g.setColor(Color.green);
g.fillOval(140,40,100,50);
g.drawOval(40,140,100,100);
g.setColor(Color.orange);
g.fillOval(140,140,100,100);
g.drawArc(40,240,50,50,0,-180);
g.drawArc(100,265,50,50,0,180);
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
14
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
15
2b. Write a java program to draw rectangle, filled rectangle and rounded rectangle and filled
rounded rectangle with any two colors?
SOURCE:
import java.awt.*;
import java.applet.*;
/*<Applet code="TwoB",height="300",width="300"></Applet>*/
public class TwoB extends Applet
{
public void paint(Graphics g)
{
g.drawRect(20,0,100,50);
g.setColor(Color.green);
g.fillRect(140,0,100,50);
g.drawRoundRect(20,70,100,50,10,10);
g.setColor(Color.blue);
g.fillRoundRect(140,70,100,50,20,20);
g.drawRect(20,140,100,100);
g.setColor(Color.red);
g.fillRect(140,140,100,100);
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
16
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
17
2c. Write a java program to draw a smiley face?
SOURCE:
import java.awt.*;
import java.applet.*;
/*<Applet code="TwoC",height="300",width="300"></Applet>*/
public class TwoC extends Applet
{
public void paint(Graphics g)
{
g.drawRect(40,40,200,200);
g.setColor(Color.yellow);
g.drawOval(90,70,80,80);
g.drawOval(110,95,5,5);
g.drawLine(130,95,130,115);
g.drawArc(113,115,35,20,0,-180);
g.drawOval(145,95,5,5);
}
}
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
18
WEEK 3:
3a .Write a Java program to create an Applet that displays 4buttons each represents different
colors.if a user click on particular button then that color is set as back ground to applet.
SOURCE:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<Applet code="ThreeA",height="300",width="300"></Applet>*/
public class ThreeA extends Applet implements ActionListener
{
Button b1,b2,b3,b4;
public void init()
{
b1=new Button("Red");
b2=new Button("Green");
b3=new Button("Orange");
b4=new Button("Blue");
add(b1);
add(b2);
add(b3);
add(b4);
}
public void start()
{
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
19
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String name=ae.getActionCommand();
if(name.equals("Red"))
setBackground(Color.red);
else if(name.equals("Green"))
setBackground(Color.green);
else if(name.equals("Orange"))
setBackground(Color.orange);
else
setBackground(Color.blue);
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
20
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
21
3 b . Write a Java program to create an Applet that displays 2buttons .if a user click on one button
then change name of another button and display the button clicked and vice-versa?
SOURCE:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<Applet code="ThreeB",height="300",width="300"></Applet>*/
public class ThreeB extends Applet implements ActionListener
{
Button b1,b2;
String str="";
public void init()
{
b1=new Button("Button1");
b2=new Button("Button2");
add(b1);
add(b2);
}
public void start()
{
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String name=ae.getActionCommand();
if(name.equals("Button1"))
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
22
{
b2.setLabel("Name changed");
str="The button clicked is:"+name;
}
else
{
b1.setLabel("Name Changed");
str="The button clicked is:"+name;
}
repaint();
}
public void paint(Graphics g)
{
g.drawString(str,100,100);
}
}
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
23
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
24
3c. Write a Java program to create an Applet that displays 2TextFields and labels User Name and
Password . Display Text Field entered and display selected text in username &display password?
SOURCE:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code="ThreeC",height="300",width="300"></Applet>*/
public class ThreeC extends Applet implements ActionListener
{
TextField t1,t2;
Label l1,l2;
public void init()
{
l1=new Label("UserName",Label.LEFT);
t1=new TextField(20);
l2=new Label("Password",Label.LEFT);
t2=new TextField(10);
add(l1);
add(t1);
add(l2);
add(t2);
}
public void start()
{
t1.addActionListener(this);
t2.addActionListener(this);
t2.setEchoChar('*');
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
25
}
public void actionPerformed(ActionEvent ae)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString("UserName:"+t1.getText(),60,80);
g.drawString("Password:"+t2.getText(),60,100);
g.drawString("Selected Text:"+t1.getSelectedText(),60,120);
}
}
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
26
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
27
3d.write a Java program that displays 4buttons and also count Number of button clicks on each
button?
Source:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<Applet code="ThreeD",height="300",width="300"></Applet>*/
public class ThreeD extends Applet implements ActionListener
{
Button b1,b2,b3,b4;
int a=0,b=0,c=0,d=0;
public void init()
{
b1=new Button("Red");
b2=new Button("Green");
b3=new Button("Orange");
b4=new Button("Blue");
add(b1);
add(b2);
add(b3);
add(b4);
}
public void start()
{
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
28
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String name=ae.getActionCommand();
if(b1==ae.getSource())
a++;
else if(b2==ae.getSource())
b++;
else if(b3==ae.getSource())
c++;
else
d++;
repaint();
}
public void paint(Graphics g)
{
g.drawString("The red button is clicked"+a+"times",50,50);
g.drawString("The green button is clicked"+b+"times",50,70);
g.drawString("The orange button is clicked"+c+"times",50,90);
g.drawString("The blue button is clicked"+d+"times",50,110);
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
29
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
30
WEEK 4:
4A. Write a Java Program to create an applet that receives an integer in one text field,
and computes its factorial value and returns it in another text field, when the button
named “Compute” is clicked.
Source:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code="FactApplet" height= 200 width=500></applet> */
public class FactApplet extends Applet
{
TextField t1,t2;
Label l1,l2;
Button b1,b2;
public void init()
{
setBackground(Color.pink);
setForeground(Color.blue);
t1= new TextField(20);
t2= new TextField(20);
l1= new Label("Enter a Number", Label.LEFT);
l2= new Label("Factorial", Label.LEFT);
b1= new Button("compute");
b2= new Button("cancel");
add(l1);
add(t1);
add(l2);
add(t2);
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
31
add(b1);
add(b2);
}
public void start()
{
b1.addActionListener(new MyCompute());
b2.addActionListener(new MyCompute());
}
public class MyCompute implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("compute"))
{
int n=Integer.parseInt(t1.getText());
int fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
t2.setText(String.valueOf(fact));
}
if(str.equals("cancel"))
{
t1.setText("");
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
32
t2.setText("");
}
}
} //class MyCompute
}// class FactApplet
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
33
4B. Write a Java Program to create an applet that receives a string and returns
either it Uppercase or Lowercase, Reverse of given string, and length of a given
String.
Source:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code="StringEx2b" height= 200 width=500></applet> */
public class StringEx2b extends Applet implements ActionListener
{
String str,str1=null;
StringBuffer sb,sb1;
TextField t1;
Label l1;
Button b1,b2;
public void init()
{
setBackground(Color.pink);
setForeground(Color.blue);
t1= new TextField(20);
l1= new Label("Enter a String", Label.LEFT);
b1= new Button("Convert");
b2= new Button("Cancel");
add(l1);
add(t1);
add(b1);
add(b2);
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
34
public void start()
{
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("Convert"))
{
str1 =t1.getText();
sb=new StringBuffer(str1);
sb1=sb.reverse();
repaint();
}
if(str.equals("cancel"))
{
t1.setText("");
}
}
public void paint(Graphics g)
{ g.drawString(str1.toUpperCase(),50,60);
g.drawString(str1.toLowerCase(),50,80);
g.drawString(sb1.toString(),50,100);
g.drawString("Length:"+str1.length(),50,120);
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
35
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
36
4c.Write a Java program to find reverse of a given number and also checks whether it is
palindrome or not and display a status message.
SOURCE:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<Applet code="FourC",height="300",width="300"></Applet>*/
public class FourC extends Applet implements ActionListener
{
Label l1;
TextField t1;
Button b1,b2;
String msg="";
int sum=0;
public void init()
{
l1=new Label("Enter string");
t1=new TextField(10);
b1=new Button("Find");
b2=new Button("Cancel");
add(l1);
add(t1);
add(b1);
add(b2);
}
public void start()
{
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
37
t1.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(b1==ae.getSource())
{
String str=t1.getText();
int n=Integer.parseInt(str);
int m,r;
m=n;
while(n>0)
{
r=n%10;
sum=sum*10+r;
n=n/10;
}
if(m==sum)
msg="given no is palindrome:"+m;
else
msg="given no is not palindrome:"+m;
}
else
{
t1.setText(" ");
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
38
repaint();
}
public void paint(Graphics g)
{
g.drawString("REVERSE of a Given Numebr is :"+sum,50,50);
g.drawString(msg,50,70);
}
}
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
39
WEEK 5:
5A. Write a Java program to demonstrate the mouse event handlers.
Source:
// Demonstrate the mouse event handlers.
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 mouseX = 0, mouseY = 0; // coordinates of mouse
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
40
public void mousePressed(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me)
{
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
41
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
42
5B. Write a Java program to demonstrate the key event handlers.
Source:
// Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEvents" width=300 height=100>
</applet>
*/
public class KeyEvents extends Applet implements KeyListener
{
String msg = "";
int keycode;
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
//showStatus("Key Pressed");
keycode=ke.getKeyCode();
switch(keycode)
{
case KeyEvent.VK_ENTER: msg="Enter key is Pressed"; break;
case KeyEvent.VK_SHIFT: msg=" Shift Key is Pressed"; break;
case KeyEvent.VK_PAGE_UP: msg=" Page Up Key is Pressed"; break;
case KeyEvent.VK_F2: msg="F2 Key is Pressed"; break;
case KeyEvent.VK_A: msg=" Letter-A Key is Pressed"; break;
case KeyEvent.VK_K: msg=" Letter-K Key is Pressed"; break;
case KeyEvent.VK_1: msg=" Number-1 Key is Pressed"; break;
case KeyEvent.VK_8: msg=" Number-8 Key is Pressed"; break;
}
repaint();
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Released");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, 50, 50);
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
43
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
44
WEEK 6:
6A. Write a Java Program that simulates a traffic light. The program lets the user select
one of three lights: red, yellow, or green. When a radio button is selected, the light is
turned on, and only one light can be on at a time No light is on when the program starts.
Source:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code="TrafficLights" height= 250 width=500></applet> */
public class TrafficLights extends Applet implements ItemListener
{
CheckboxGroup cbg;
Checkbox c1,c2,c3;
TextField t1;
public void init()
{
cbg=new CheckboxGroup();
c1=new Checkbox("Red",cbg,false);
c2=new Checkbox("Yellow",cbg,false);
c3=new Checkbox("Green",cbg,false);
t1=new TextField(30);
add(c1);
add(c2);
add(c3);
add(t1);
}
public void start()
{
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawOval(10, 50, 30, 30);
g.setColor(Color.yellow);
g.drawOval(10, 100, 30, 30);
g.setColor(Color.green);
g.drawOval(10, 150, 30, 30);
String s1=cbg.getSelectedCheckbox().getLabel();
if(s1=="Red")
{
g.setColor(Color.red);
g.fillOval(10, 50, 30, 30);
t1.setText("Stop The Vehicle");
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
45
else if(s1=="Yellow")
{
g.setColor(Color.yellow);
g.fillOval(10, 100, 30, 30);
t1.setText("Be Ready to Go");
}
else if(s1=="Green")
{
g.setColor(Color.green);
g.fillOval(10, 150, 30, 30);
t1.setText(" You Can Go Now");
}
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
}
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
46
6B.Write a Java Program to create multiple frames, which create a Frame2 with a
„back „button, such that when a user click „back‟ button, Frame 2 is closed and we see
the Frame1 only?
Source:
Save as: MyFrame1.java
import java.awt.*;
import java.awt.event.*;
public class MyFrame1 extends Frame implements ActionListener
{
Button b1,b2;
MyFrame1()
{
b1=new Button("Next");
add(b1);
b2=new Button("cancel");
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(b1==ae.getSource())
{
MyFrame2 f1=new MyFrame2();
f1.setSize(100,100);
f1.setVisible(true);
f1.setTitle("second Frame");
}
}
public static void main (String argsv[])
{
MyFrame1 f=new MyFrame1();
f.setTitle("first frame");
f.setSize(500,500);
f.setVisible(true);
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
47
Save as: MyFrame2.java
class MyFrame2 extends Frame implements ActionListener
{
Button b1;
MyFrame2()
{
b1 =new Button("Back");
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
this.dispose();
}
}
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
48
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
49
WEEK7:
7.Write a Java Program a simple user form which reads the name of a user and mail id in
Text fields, select gender with radio buttons, and selects some Known languages using
checkboxes, and also enters an address in a text area. After filling details whenever a user
press the “submit” button, then displays all the information about the user input.
Source:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<Applet code="us",height="525", width="230">
</Applet>*/
public class us extends Applet implements ActionListener,ItemListener
{
Label ad,lo,l1,l2,l3,pa,gn,dob;
TextField fn,mn,ln,ps;
Choice w,l,d,m,y;
Button b1;
TextArea t;
public void init()
{
setLayout(new FlowLayout(FlowLayout.LEFT,3,3));
l1=new Label("FIRST NAME :",Label.LEFT);
l2=new Label("MIDDLE NAME :",Label.LEFT);
l3=new Label("LAST NAME :",Label.LEFT);
pa=new Label("PASSWORD :",Label.LEFT);
fn=new TextField(10);
mn=new TextField(10);
ln=new TextField(10);
ps=new TextField(10);
ps.setEchoChar('*');
gn=new Label("GENDER",Label.LEFT);
w=new Choice();
w.add(" ");
w.add("MALE ");
w.add("FEMALE");
lo=new Label(" LANGS",Label.LEFT);
l=new Choice();
l.add(" ");
l.add("Telugu");
l.add("English");
l.add("Tamil");
l.add("Kannada");
dob=new Label(" DOB :",Label.LEFT);
d=new Choice();
d.add(" ");
for(int i=1;i<=31;i++)
{
d.add(" "+i);
}
m=new Choice();
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
50
m.add(" ");
String
md[]={"JAN","FEB","MAR","APR","MAY","JUN","JULY","AUG","SEP","OCT","NOV","DEC"};
for(int j=0;j<=11;j++)
{
m.add(" "+md[j]);
}
y=new Choice();
y.add(" ");
for(int k=1980;k<=2999;k++)
{
y.add(" "+k);
}
ad=new Label("\nADRS :",Label.LEFT);
t=new TextArea(5,10);
b1=new Button("SUBMIT");
add(l1);
add(fn);
add(l2);
add(mn);
add(l3);
add(ln);
add(pa);
add(ps);
add(gn);
add(w);
add(lo);
add(l);
add(dob);
add(d);
add(m);
add(y);
add(ad);
add(t);
add(b1);
}
public void start()
{
fn.addActionListener(this);
mn.addActionListener(this);
ln.addActionListener(this);
ps.addActionListener(this);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(b1==ae.getSource())
{
}
repaint();
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
51
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
Font f1=new Font("Arial Black",Font.PLAIN,10);
g.setFont(f1);
g.setColor(Color.yellow);
g.drawRoundRect(0,305,175,225,45,45);
g.fillRoundRect(0,305,175,225,45,45);
g.setColor(Color.black);
g.drawString("first name :"+fn.getText(),5,345);
g.drawString("middle name :"+mn.getText(),5,365);
g.drawString("last name :"+ln.getText(),5,385);
g.drawString("password :"+ps.getText(),5,405);
g.drawString("GENDER :"+w.getSelectedItem(),5,425);
g.drawString("LAGS :"+l.getSelectedItem(),5,445);
g.drawString("DOB:"+d.getSelectedItem()+"_"+m.getSelectedItem()+"_"+y.getSelectedItem(),5,4
65);
g.drawString("ADRS :"+t.getText(),5,485);
}
}
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
52
WEEK 8:
8. Write a Java program that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the +, -,*, % operations. Add a text field to display the
resu1lt.
Source:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Cal" width=300 height=300>
</applet>
*/
public class Cal extends Applet
implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
53
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
54
OP='%';
t1.setText("");
}
if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
}
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
55
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
56
WEEK 9:
9a. Write a Java program to create buttons with different borders?
SOURCE:
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class NineA extends JFrame
{
JButton b1,b2,b3,b4,b5,b6,b7;
NineA()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
b1=new JButton("BevelRaised");
b2=new JButton("BevelLowered");
b3=new JButton("LineBorder");
b4=new JButton("EtechedRaised");
b5=new JButton("EtechedLowered");
b6=new JButton("CompoundBorder");
b7=new JButton("EmptyBorder");
Border bd=BorderFactory.createBevelBorder(BevelBorder.RAISED,Color.red,Color.yellow);
b1.setBorder(bd);
bd=BorderFactory.createBevelBorder(BevelBorder.LOWERED,Color.red,Color.green);
b2.setBorder(bd);
bd=BorderFactory.createLineBorder(Color.green,10);
b3.setBorder(bd);
bd=BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
b4.setBorder(bd);
bd=BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
b5.setBorder(bd);
bd=BorderFactory.createCompoundBorder();
b6.setBorder(bd);
bd=BorderFactory.createEmptyBorder();
b7.setBorder(bd);
c.add(b1);
c.add(b2);
c.add(b3);
c.add(b4);
c.add(b5);
c.add(b6);
c.add(b7);
}
public static void main(String args[])
{
NineA ob=new NineA();
ob.setSize(200,200);
ob.setVisible(true);
ob.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
57
}
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
58
9B. Write a Java Program to create a frame using swing in which create a push button
with a label and image. When the button is clicked an image is displayed in the Frame?
Source:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
class ButtonDemo extends JFrame implements ActionListener
{
JButton b1;
JLabel l;
ButtonDemo()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
ImageIcon img=new ImageIcon("img1.PNG");
b1=new JButton("click here",img);
b1.setBackground(Color.yellow);
b1.setForeground(Color.red);
b1.setFont(new Font("Times New Roman",Font.BOLD,25));
b1.setToolTipText("This is Image Button");
b1.setMnemonic('(');
Border ob=BorderFactory.createBevelBorder(BevelBorder.RAISED);
b1.setBorder(ob);
c.add(b1);
l=new JLabel("click on Button");
c.add(l);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
ImageIcon i=new ImageIcon("img1.PNG");
l.setIcon(i);
}
public static void main(String argsv[])
{
ButtonDemo ob1=new ButtonDemo();
ob1.setVisible(true);
ob1.setSize(100,100);
ob1.setTitle("JBUTTON");
ob1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
59
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
60
9C.Write a Java Program to choose courses with check boxes and gender through radio buttons ,
display selected items in text area?
SOURCE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NineC extends JFrame implements ActionListener
{
JCheckBox c1,c2,c3;
JRadioButton r1,r2;
JTextArea ta;
String msg="";
NineC()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
c1=new JCheckBox("Java");
c2=new JCheckBox("C#");
c3=new JCheckBox("C");
r1=new JRadioButton("Male");
r2=new JRadioButton("Female");
ButtonGroup bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
ta=new JTextArea("Select options",10,20);
c.add(c1);
c.add(c2);
c.add(c3);
c.add(r1);
c.add(r2);
c.add(ta);
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
r1.addActionListener(this);
r2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(c1.getModel().isSelected())
msg+=c1.getText()+"\n";
if(c2.getModel().isSelected())
msg+=c2.getText()+"\n";
if(c3.getModel().isSelected())
msg+=c3.getText()+"\n";
if(r1.getModel().isSelected())
msg+=r1.getText()+"\n";
else if(r2.getModel().isSelected())
msg+=r2.getText()+"\n";
ta.setText(msg);
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
61
msg="";
}
public static void main(String args[])
{
NineC ob=new NineC();
ob.setVisible(true);
ob.setSize(200,200);
ob.setTitle("Check&Radio");
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
62
WEEK 10:
10 a.write a Java program to implement JcomboBox where we can select state and language and
display selected items using lables?
SOURCE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class TenA extends JFrame implements ItemListener
{
JComboBox b1,b2;
JLabel l1,l2;
TenA()
{
Container c=getContentPane();
c.setLayout(null);
b1=new JComboBox();
b2=new JComboBox();
b1.addItem("Andhra");
b1.addItem("Karnataka");
b1.addItem("Maharastra");
b1.addItem("Tamilnadu");
b1.addItem("Kerala");
b2.addItem("Telugu");
b2.addItem("Tamil");
b2.addItem("Malayalam");
b2.addItem("Marati");
b2.addItem("Kannada");
b1.setBounds(100,50,100,40);
b2.setBounds(200,50,100,40);
c.add(b1);
c.add(b2);
l1=new JLabel("State");
l1.setBounds(100,200,200,40);
c.add(l1);
l2=new JLabel("Language");
l2.setBounds(150,250,200,40);
c.add(l2);
b1.addItemListener(this);
b2.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
String str=(String)b1.getSelectedItem();
l1.setText("You selected:"+str);
str=(String)b2.getSelectedItem();
l2.setText("You selected:"+str);
}
public static void main(String args[])
{
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
63
TenA t=new TenA();
t.setTitle("ComboBox");
t.setVisible(true);
t.setSize(200,200);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
64
10b. write a Java program to implement a JList where we can select multiple courses
and display them in Text area.
SOURCE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class TenB extends JFrame implements ListSelectionListener
{
JList jl;
JLabel l;
Object arr[];
String msg="";
TenB()
{
Container c=getContentPane();
c.setLayout(null);
String items[]={"Java","C#","C++","C"};
jl=new JList(items);
jl.setBounds(100,50,100,100);
c.add(jl);
l=new JLabel();
l.setBounds(50,200,400,40);
c.add(l);
jl.addListSelectionListener(this);
}
public void valueChanged(ListSelectionEvent le)
{
arr=jl.getSelectedValues();
for(int i=0;i<arr.length;i++)
msg+=(String)arr[i];
l.setText("Selected:"+msg);
msg="";
}
public static void main(String args[])
{
TenB t=new TenB();
t.setTitle("List");
t.setSize(200,200);
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
65
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
66
10C. Write a Java program that creates a user interface to perform integer divisions.
The user enters two numbers in the text fields, Num1 and Num2. The division of Num1
and Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or
Num2 were not an integer, the program would throw a Number Format Exception. If
Num2 were Zero, the program would throw an Arithmetic Exception Display the
exception in a message dialog box.
Source:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
/* <applet code="IntDivision" height= 200 width=500></applet> */
public class IntDivision extends Applet implements ActionListener
{
TextField t1,t2,t3;
Label l1,l2,l3;
Button b1;
public void init()
{
setBackground(Color.gray);
setForeground(Color.red);
t1= new TextField(20);
t2= new TextField(20);
t3= new TextField(20);
l1= new Label("Enter First Number :", Label.LEFT);
l2= new Label("Enter Second Number :", Label.LEFT);
l3= new Label("Result :", Label.LEFT);
b1= new Button("Division");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
}
public void start()
{
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
try
{
int x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
String str=ae.getActionCommand();
if(str.equals("Division"))
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
67
{
int div=x/y;
t3.setText(String.valueOf(div));
}
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null, "Please Enter the Correct Format");
}
catch(ArithmeticException are)
{
JOptionPane.showMessageDialog(null, "Please don't Enter the 2nd number as ZERO");
}
}
}
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
68
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
69
WEEK 11:
11a.write a Java program to create three tabs which includes push buttons,check boxes and
comboBox in each tab respectively which represents color buttons,list of courses with check boxes
and places with combo box?
SOURCE:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*<Applet code="ElevenA",height="300",width="300"></Applet>*/
public class ElevenA extends JApplet
{
JTabbedPane jp;
public void init()
{
try{
SwingUtilities.invokeLater(
new Runnable()
{
public void run(){makeGUI();}});
}
catch(Exception e){ }
}
public void makeGUI()
{
jp=new JTabbedPane();
jp.addTab("Colors",new Colors());
jp.addTab("Courses",new Courses());
jp.addTab("Places",new Places());
add(jp);
}
}
class Colors extends JPanel
{
JButton b1,b2,b3;
Colors()
{
b1=new JButton("Red");
b2=new JButton("Green");
b3=new JButton("Orange");
add(b1);
add(b2);
add(b3);
}
}
class Courses extends JPanel
{
JCheckBox cb1,cb2,cb3;
Courses()
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
70
{
cb1=new JCheckBox("Java");
cb2=new JCheckBox("C#");
cb3=new JCheckBox("C");
add(cb1);
add(cb2);
add(cb3);
}
}
class Places extends JPanel
{
JComboBox c1;
Places()
{
c1=new JComboBox();
c1.addItem("HYD");
c1.addItem("BGL");
c1.addItem("CTY");
add(c1);
}
}
OUTPUT
:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
71
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
72
11b.Write a Java Program to create a student table, which includes name, roll no, branch and age
or DOB?
Source:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.*;
public class EmpTable extends JFrame
{
JTable tb;
EmpTable()
{
Container c=getContentPane();
Vector<Vector> row=new Vector<Vector>();
Vector<String> rowdata=new Vector<String>();
//1st row
rowdata.add("Rama");
rowdata.add("CSE");
rowdata.add("549");
row.add(rowdata);
//2nd row
rowdata=new Vector<String>();
rowdata.add("Krishna");
rowdata.add("CSE");
rowdata.add("542");
row.add(rowdata);
//3rd row
rowdata=new Vector<String>();
rowdata.add("Hanuma");
rowdata.add("CSE");
rowdata.add("532");
row.add(rowdata);
//4th row
rowdata=new Vector<String>();
rowdata.add("Laxman");
rowdata.add("CSE");
rowdata.add("542");
row.add(rowdata);
//cols Heads
Vector<String> cols=new Vector<String>();
cols.add("NAME");
cols.add("BRANCH");
cols.add("REG.NO");
//cols.setFont(new Font("Arial",Font.BOLD,30));
// table creation
tb=new JTable(row,cols);
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
73
Border bd= BorderFactory.createLineBorder(Color.orange,4);
tb.setBorder(bd);
tb.setRowHeight(30);
tb.setGridColor(Color.red);
JScrollPane sp=new JScrollPane(tb);
c.add(sp);
}
public static void main(String a[])
{
EmpTable et=new EmpTable();
et.setSize(500,500);
et.setVisible(true);
et.setTitle("STUDENT Table");
et.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
74
11C. Write a java program to create a menu with several menu items by implementing JMenu?
Source:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ElevenC extends JFrame implements ActionListener
{
JMenuBar mb;
JMenu fmenu,emenu,font_menu;
JMenuItem op,sa,cl,f1,f2,f3,co,pa,cu;
JCheckBoxMenuItem pr;
JLabel l;
ElevenC()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
mb=new JMenuBar();
c.add(mb,BorderLayout.NORTH);
fmenu=new JMenu("File");
emenu=new JMenu("Edit");
font_menu=new JMenu("Font");
op=new JMenuItem("Open");
sa=new JMenuItem("Save");
cl=new JMenuItem("Close");
pr=new JCheckBoxMenuItem("Print");
fmenu.add(op);
fmenu.add(sa);
fmenu.add(cl);
fmenu.add(pr);
fmenu.addSeparator();
f1=new JMenuItem("ArialBlack");
f2=new JMenuItem("TimesNewRoman");
f3=new JMenuItem("MonoTypeCoresia");
font_menu.add(f1);
font_menu.add(f2);
font_menu.add(f3);
fmenu.add(font_menu);
co=new JMenuItem("Copy");
pa=new JMenuItem("Paste");
cu=new JMenuItem("Cut");
emenu.add(co);
emenu.add(pa);
emenu.add(cu);
mb.add(fmenu);
mb.add(emenu);
c.add(mb);
op.addActionListener(this);
sa.addActionListener(this);
cl.addActionListener(this);
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
75
pr.addActionListener(this);
f1.addActionListener(this);
f2.addActionListener(this);
f3.addActionListener(this);
co.addActionListener(this);
pa.addActionListener(this);
cu.addActionListener(this);
l=new JLabel("Display",Label.LEFT);
c.add(l);
}
public void actionPerformed(ActionEvent ae)
{
if(op.isArmed())
l.setText("Open option is selected in File menu");
else if(sa.isArmed())
l.setText("Save option is selected in File menu");
else if(cl.isArmed())
l.setText("Close option is selected in File menu");
else if(pr.getModel().isSelected())
l.setText("Print option is selected in File menu");
else if(f1.isArmed())
l.setText("ArialBlack option is selected in Font menu");
else if(f2.isArmed())
l.setText("TimesNewRoman option is selected in Font menu");
else if(f3.isArmed())
l.setText("MonoTypeCoresia option is selected in Font menu");
else if(co.isArmed())
l.setText("Copy option is selected in Edit menu");
else if(pa.isArmed())
l.setText("Paste option is selected in Edit menu");
else if(cu.isArmed())
l.setText("Cut option is selected in Edit menu");
else
l.setText("Select any option");
}
public static void main(String args[])
{
ElevenC e=new ElevenC();
e.setVisible(true);
e.setSize(300,300);
e.setTitle("MenuBar");
e.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
76
Output:
nln;nk.n.b k;;
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
77
WEEK 12:
12A. Write a Java program to retrieve the information from the given URL? (Note: Read the
URL from Command Line Arguments).
Source:
import java.net.*;
import java.io.*;
class TwelveA
{
public static void main(String args[]) throws Exception
{
URL hp=new URL("http://www.yahoo.com/index.html");
System.out.println("Get protocol:"+hp.getProtocol());
System.out.println("Get Domain name:"+hp.getHost());
System.out.println("Port number:"+hp.getPort());
System.out.println("File:"+hp.getPath());
System.out.println("URL is:"+hp.toExternalForm());
System.out.println("File name:"+hp.getFile());
}
}
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
78
12B. Write a Java program that implements a simple client/server application. The client sends
data to a server. The server receives the data, uses it to produce a result, and then sends the result
back to the client. The client displays the result on the console. For ex: The data sent from the
client is the radius of a circle, and the result produced by the server is the area of the circle. (Use
java.net)
Source:
Cient code:
import java.io.*;
import java.net.*;
import java.lang.*;
class TwelveB1
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(888);
Socket s=ss.accept();
PrintStream ps=new PrintStream(s.getOutputStream());
System.out.println("Connection Established");
BufferedReader br1=new BufferedReader(new InputStreamReader(s.getInputStream()));
int r=Integer.parseInt(br1.readLine());
System.out.println("The radius received from client is:"+r);
Double area=Math.PI*r*r;
System.out.println("The area is:"+area);
ps.println(area);
ps.close();
br1.close();
ss.close();
s.close();
}
}
SERVER CODE:
import java.io.*;
import java.net.*;
class TwelveB2
{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",888);
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter radius:");
int r=Integer.parseInt(br.readLine());
dos.writeBytes(""+r);
BufferedReader br1=new BufferedReader(new InputStreamReader(s.getInputStream()));
double area=Double.parseDouble(br1.readLine());
System.out.println("The area is:"+area);
br1.close();
dos.close();
br.close();
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
79
s.close();
}
}
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
80
WEEK 13:
13a.Write a java program to create a sample TCP chat application where client and server can chat
with each other?
Source:
CLIENT CODE:
import java.net.*;
import java.io.*;
class ThirteenA1
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(888);
Socket s=ss.accept();
System.out.println("Connection established");
PrintStream ps=new PrintStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String str="",str1="";
while((str=br.readLine())!=null)
{
System.out.println(""+str);
//System.out.println("Sending to client:");
str1=br1.readLine();
ps.println(str1);
}
ps.close();
br.close();
br1.close();
ss.close();
s.close();
System.exit(0);
}
}
}
SERVER CODE:
import java.net.*;
import java.io.*;
class ThirteenA2
{
public static void main(String args[]) throws Exception
{
Socket s=new Socket("localhost",888);
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
81
String str="",str1="";
while(!(str1=br1.readLine()).equals("exit"))
{
//System.out.println("Sending to server:"+str1);
dos.writeBytes(str1+"\n");
str=br.readLine();
System.out.println(""+str);
}
dos.close();
br.close();
br1.close();
s.close();
}
}
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
82
13b.Write a java program to perform a simple conversation with UDP model?
SOURCE:
SERVER:
import java.net.*;
import java.io.*;
class ThriteenB1
{
public static void main(String args[])throws Exception
{
DatagramSocket ds=new DatagramSocket(8);
byte b[]=new byte[50];
DatagramPacket in=new DatagramPacket(b,b.length);
ds.receive(in);
System.out.println("in server_receiving from client:"+new String(b));
String str="hello client------";
byte buff[]=str.getBytes();
System.out.println("sending address to client---"+new String(buff));
DatagramPacket out=
new
DatagramPacket(buff,buff.length,in.getAddress(),in.getPort());
ds.send(out);
ds.close();
}
}
Client code:
import java.net.*;
import java.io.*;
public class ThirteenB2
{
public static void main(String args[])throws Exception
{
InetAddress ia=InetAddress.getLocalHost();
DatagramSocket ds=new DatagramSocket(1024,ia);
String str1="";
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
while(!(str1=br1.readLine()).equals("exit"))
{
byte b[]=str1.getBytes();
DatagramPacket out=new DatagramPacket(b,b.length,ia,8);
ds.send(out);
System.out.println("Sending to server...:"+(new String(b)));
byte buff[]=new byte[50];
DatagramPacket in=new DatagramPacket(buff,buff.length);
ds.receive(in);
System.out.println("Received from server...:"+new String(buff));
}
ds.close();
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
83
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
84
WEEK 14:
14A. Write a java program to create a bean that counts the number of mouse clicks?
Source:
import java.beans.*;
import java.io.Serializable;
import java.awt.*;
import java.awt.event.*;
public class Mouseclick extends Canvas
{
private int count=0;
public Mouseclick()
{
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
count++;
repaint();
}
});
setSize(50,80);
setBackground(Color.green);
setForeground(Color.red);
}
public void paint(Graphics g)
{
g.drawString("NO of MouseClicks :"+count,40,60);
}
}
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
85
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
86
14 B Write a java program to create a bean that counts the number of button
clicks?
Source:
import java.awt.*;
import java.awt.event.*;
public class fourteenB extends Panel implements ActionListener
{
int count;
Button but;
public fourteenB()
{
count = 0;
setSize(200, 100);
but = new Button("Click me");
but.addActionListener(this);
add(but);
}
public void actionPerformed(ActionEvent e)
{
count++;
repaint();
}
public void paint(Graphics g)
{
Dimension d = getSize();
Font f=new Font("Courier",Font.BOLD,30);
int h = d.height;
int w = d.width;
g.setColor(Color.pink);
g.fillRect(0, 0, w-1, h-1);
g.setFont(f);
g.setColor(new Color(0, 0, 0));
g.drawString("Click count = " + count, 50, 50);
}
}
Output:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
87
14c.Write a Java program to create a bean that display employee name, salary,
designation and company?
SOURCE:
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
public class Emp extends Canvas
{
private String ename,designation,address;
private double salary;
private int age;
public Emp()
{
ename= "Hemanth";
designation="DataBase Manager";
address="kurnool";
salary=50000;
age=24;
}
public void setEname(String name)
{
ename=name;
}
public void setDesignation(String desg)
{
designation=desg;
}
public void setAddress(String adr)
{
address=adr;
}
public void setSalary(double sal)
{
salary=sal;
}
public void setAge(int ag)
{
age=ag;
}
public String getEname()
{
return ename;
}
public String getDesignation()
{
return designation;
}
public double getSalary()
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
88
{
return salary;
}
public int getAge()
{
return age;
}
public void paint(Graphics g)
{
g.drawString("Name:"+ename,20,20);
g.drawString("Address:"+address,20,40);
g.drawString("Designation:"+designation,20,70);
g.drawString("salary:"+salary,20,80);
}
}
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
89
WEEK 15:
15A. Write a Java Program to create a bean to convert the Indian Rupee to American dollar and to
pound?
SOURCE:
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import java.io.Serializable;
import java.beans.*;
import java.util.*;
class converter
{
public converter()
{
System.out.println("The following are the converted of INR");
}
public double convertToDollar(double inr)
{
return(inr/65.57);
}
public double convertToPound(double inr)
{
return(inr/99.36);
}
}
class fifteenC
{
public static void main(String args[])
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
90
{
double inr=Double.parseDouble(JOptionPane.showInputDialog("Enter Indian
rupee(inr)"));
converter con=new converter();
DecimalFormat df=new DecimalFormat("0.00");
double dollar=con.convertToDollar(inr);
double pound=con.convertToPound(inr);
JOptionPane.showMessageDialog(null,"dollar value:"+df.format(dollar)+"\npound
value:"+df.format(pound));
}
}
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
91
15B. Write a Java Program to create a bean to stimulate Traffic signals?
SOURCE:
import java.awt.*;
import java.lang.String;
import java.awt.event.*;
import java.applet.Applet;
import java.applet.*;
/*<applet code="fifteenA.class",height="300",width="200"></applet>*/
public class fifteenA extends Applet implements ItemListener
{
boolean c1,c2,c3;
String s1;
Checkbox r1,r2,r3;
CheckboxGroup cbg;
public void init(){
cbg=new CheckboxGroup();
Panel p=new Panel();
p.setLayout(new GridLayout());
add(r1=new Checkbox("red",cbg,false));
add(r2=new Checkbox("yellow",cbg,false));
add(r3=new Checkbox("green",cbg,false));
r1.addItemListener(this);
r2.addItemListener(this);
r3.addItemListener(this);
}
public void paint(Graphics g) {
g.setColor(Color.red);
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
92
g.drawOval(10, 30, 20, 20);
//System.out.println(s1);
g.setColor(Color.yellow);
g.drawOval(10, 60, 20, 20);
g.setColor(Color.green);
g.drawOval(10, 90, 20, 20);
s1=cbg.getSelectedCheckbox().getLabel();
if(s1=="red")
{
g.setColor(Color.red);
g.fillOval(10, 30, 20, 20);
}
else if(s1=="yellow")
{
g.setColor(Color.yellow);
g.fillOval(10, 60, 20, 20);
}
else if(s1=="green")
{
g.setColor(Color.green);
g.fillOval(10, 90, 20, 20);
}
} public void itemStateChanged(ItemEvent ie)
{
repaint();
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
93
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
94
15C.Write a Java Program to create bean to implement color bean?
SOURCE:
import java.awt.*;
import java.beans.*;
import java.awt.event.*;
import java.io.Serializable;
public class Crb extends Canvas implements Serializable
{
private Color clr;
private boolean rectangular=true;
public Crb()
{
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
Change();
} });
setSize(100,120);
repaint();
}
public void Change()
{
clr=randomColor();
repaint();
}
public void setRectangular(boolean rect)
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
95
{
rectangular=rect;
repaint();
}
public boolean getRectangular()
{
return rectangular;
}
public Color randomColor()
{
int r=(int)(255*Math.random());
int g=(int) (255*Math.random());
int b=(int)(255*Math.random());
return(new Color(r,g,b));
}
public void paint(Graphics g)
{
Dimension d=getSize();
int h=(int)d.getHeight();
int w=(int)d.getWidth();
g.setColor(clr);
if(rectangular)
g.fillRect(10,10,w-1,h-1);
else
g.fillOval(10,10,w-1,h-1);
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
96
OUTPUT:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
97
WEEK 16:
16. Installation of Apache Tomcat webserver.
Source:
Download Apache Tomcat Application from Apache Tomcat website
Run the application file.
STEP 1: Simply click on the „Next„button to continue installation process.
STEP 2: Accept the terms of the agreement by clicking on „I Agree„button.
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
98
STEP 3:
Choose the features of Apache Tomcat you want to install by checking the components and
click „Next„.
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
99
STEP 4:
The default port number for Tomcat to process HTTP requests is 8080. You can either
change the port number here or change it later after the installation in server.xml which
is located in /conf/server.xml. We recommend to have the default value.
You can provide the username and password for Administrator login but here, we leave
it as blank.
Now, click on the „Next„ button.
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
100
STEP 5:
The installer uses the registry to determine the base path of a Java 5 or later JRE,
including the JRE installed as part of the full JDK.
When running on a 64-bit operating system, the installer will first look for a 64-bit JRE
and only look for a 32-bit JRE if a 64-bit JRE is not found.
It is not mandatory to use the default JRE detected by the installer. Any installed Java 5
or later JRE (32-bit or 64-bit) may be used by clicking on the browse button and click
Next„.
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
101
STEP 6:
In Windows, by default the location will be provided as „C:\Program Files\Apache
Software Foundation\Tomcat 6.0′. But for simplicity, we recommend you to use
C:\Tomcat6„ as shown below and click „Install„.
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
102
STEP 7: Installing window is displayed.
STEP 8:
Tomcat setup completion window is displayed as shown below and click on Finish
button.
STEP 9:
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
103
Apache Service Manager window appears which is attempting to start the Tomcat service.
STEP 10:
Open browser and type http://localhost:8080. You should see the Apache Tomcat home page as
shown below.
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
104
WEEK 17:
17. A. Write a Java Program to create a simple Servlet and test it on tomcat server?
18. FirstServlet.java:
import java.io.*;
import javax.servlet.*;
public class FirstServlet extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html><head><title>First Servlet</title></head>");
pw.println("<body><center><h1>This Message came from a servlet</h1>");
pw.println("</center></body></html>");
pw.close();
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
105
Output
17. B. Write a Java Program to create a Servlet that Reads Request Parameter(s) and Display their
value(s)?
<html>
<head>
<title>Servlet Parameters</title>
</head>
<body>
<center>
<form name="form1" method="POST" action="http://localhost:9401/rpar/rparam">
<table>
<tr>
<td><b>Employee</td>
<td><input type="text" name="ename" value=""></td>
</tr>
<tr>
<td><b>Id</td>
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
106
<td><input type="text" name="id" value=""></td>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
<td><input type="reset" value="clear"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
Rparam.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class Rparam extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
Enumeration e=req.getParameterNames();
while(e.hasMoreElements()){
String pname=(String)e.nextElement();
pw.println("<b>"+pname+"=");
String pvalue=req.getParameter(pname);
pw.println("<b>"+pvalue);
}
pw.close();
}
}
Advanced Java Programming Lab
III B.Tech I Sem | Department of Computer Science & Engineering
107
Web.xml:
<web-app>
<servlet>
<servlet-name>rp</servlet-name>
<servlet-class>Rparam</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rp</servlet-name>
<url-pattern>/rparam</url-pattern>
</servlet-mapping>
</web-app>
OutPut:
RAJEEV GANDHI MEMORIAL COLLEGE OF ENGINEERING & TECHNOLOGY
(AUTONOMOUS)
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Evaluation Procedure for Internal Laboratory Examinations:
1. Of the 25 marks for internal, 10 marks will be awarded for day-to-day work and 10 marks
to be awarded for the Record work and 5 marks to be awarded by conducting an internal
laboratory test.
2. Concerned Teachers have to do necessary corrections with explanations.
3. Concerned Lab teachers should enter marks in index page.
4. Internal exam will be conducted by two Staff members.
Dr.K. Subba Reddy
Professor & Head Dept. of CSE.
RAJEEV GANDHI MEMORIAL COLLEGE OF ENGINEERING & TECHNOLOGY
(AUTONOMOUS)
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Evaluation Procedure for External Laboratory Examinations:
1. For Practical subjects there is a continuous evaluation during the semester for 25 Sessional
marks and 50 end examination marks.
2. The end examination shall be conducted by the teacher concerned (Internal Examiner) and
another External Examiner, recommended by Head of the Department with the approval of
principal.
Evaluation procedure for external lab examination:
1. Procedure for the program ---------- 20M
2. Execution of the program ---------- 15M
3. Viva voce ---------- 15M
----------------------------
Total 50M
-----------------------------
Dr.K. Subba Reddy
Professor & Head Dept. of CSE.