You are on page 1of 70

Advance Java Programming(3360701) 186020307026

Practical-1: Java Applet


1. Draw an applet size of 300 X 200 that prints “hello world”.

/*<applet code="p1_1_helloworld.class"
height="300" width="200" ></applet>*/

import java.applet.Applet;
import java.awt.Graphics;
public class p1_1_helloworld extends Applet{

public void paint(Graphics g){


g.drawString("HELLO WORLD",10,10);
}
}

Computer Department A. V. Parekh Technical Institute 1|Pag e


Advance Java Programming(3360701) 186020307026

2. Java Program to print message passed using <PARAM> tag.

/*
<applet code="p1_2_param.class" height="300"
width="300" >
<param name="parameter" value="26">
</applet>
*/
import java.applet.Applet;
import java.awt.Graphics;

public class p1_2_param extends


Applet{ public void paint(Graphics
g){
String
str=getParameter("parameter");
g.drawString(str,10,10);

Computer Department A. V. Parekh Technical Institute 2|Pag e


Advance Java Programming(3360701) 186020307026

3. Java applet to draw a Rainbow.

/*<applet code="p1_3_rainbow.class" height=800


width=700>
</applet> */
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;

public class p1_3_rainbow extends Applet{


public void paint(Graphics g){
g.setColor(Color.red);
g.fillArc(10, 15, 500,495, 0,
180);
g.setColor(Color.orange);
g.fillArc(15, 20, 490,485, 0, 180);
g.setColor(Color.yellow);
g.fillArc(20, 25, 480, 475, 0, 180);
g.setColor(Color.green);
g.fillArc(25, 30, 470, 465, 0, 180);
g.setColor(Color.blue);
g.fillArc(30, 35, 460, 455, 0, 180);
g.setColor(Color.green);
g.fillArc(35, 40,450,445, 0, 180);
g.setColor(Color.red);
g.fillArc(40, 45, 440, 435, 0,
180);
g.setColor(Color.white);
g.fillArc(45, 50, 430, 425, 0,
180);
}
}
Computer Department A. V. Parekh Technical Institute 3|Pag e
Advance Java Programming(3360701) 186020307026

4. Java applet to draw a Chess board.

/*<applet code="p1_4_chess.class" height=800


width=700>
</applet> */
import java.awt.*;
import java.applet.*;

public class p1_4_chess extends Applet {


int N = 8;
public void paint(Graphics g)
{
int x, y;
for (int row = 0; row < N; row++) {

for (int col = 0; col < N; col++)

{ x = row * 20;

y = col * 20;

if ((row % 2 == 0) == (col % 2 == 0))


g.setColor(Color.BLACK);
else
g.setColor(Color.WHITE);

g.fillRect(x, y, 20, 20);


}
}
} }

Computer Department A. V. Parekh Technical Institute 4|Pag e


Advance Java Programming(3360701) 186020307026

5. Java applet to draw smiley emoji with colors.

/*<applet code="p1_5_smiley.class" height=500


width=500>
</applet> */

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;

public class p1_5_smiley extends Applet{


public void paint(Graphics g){

g.setColor(Color.yellow);
g.fillOval(50, 50, 300, 300);

g.setColor(Color.white);
g.fillOval(100, 100, 100, 80);
g.fillOval(225, 100, 100, 80);

g.setColor(Color.BLACK);
g.fillOval(115,140, 50,
40);
g.fillOval(245,140, 50, 40);

g.setColor(Color.red);
g.fillArc(125, 250, 160, 50, 180, 180);
} }

Computer Department A. V. Parekh Technical Institute 5|Pag e


Advance Java Programming(3360701) 186020307026

6. Java applet to create a House using different shapes.

/*<applet code="p1_6_home.class" height=500


width=500>
</applet> */

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;

public class p1_6_home extends


Applet{ public void paint(Graphics g){
g.setColor(Color.yellow);
g.fillRect(100, 50, 200, 200);

g.setColor(Color.red);
int []nXpts = {50,230,330};
int []nYpts = {50,0,50};
g.setColor(Color.red);
g.fillPolygon(nXpts,nYpts,3)
;

g.setColor(Color.BLACK);
g.fillRect(170, 170, 50, 80);
}
}

Computer Department A. V. Parekh Technical Institute 6|Pag e


Advance Java Programming(3360701) 186020307026

Practical-2:ABSTRACT WINDOW TOOLKIT


7. Develop a java applet to design a log in form having Fields Username
and Password and buttons for Log-in and Cancel.

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

public class p2_7 extends Applet{


TextField tf1 = new TextField(30);
TextField tf2 = new TextField(30);

Label l1 = new Label("Name");


Label l2 = new
Label("Password");

Button b1 = new Button("LOGIN");


Button b2 = new
Button("CANCEL");

public void init() {


tf1.setEditable(true);
tf2.setEditable(true);

add(l1);
add(tf1);

add(l2);
tf2.setEchoCharacter('*')
; add(tf2);

add(b1);
add(b2);
}

}
//
//<APPLET CODE="p2_7.java" width="320"
height="450"></APPLET>
Computer Department A. V. Parekh Technical Institute 7|Pag e
Advance Java Programming(3360701) 186020307026

Computer Department A. V. Parekh Technical Institute 8|Pag e


Advance Java Programming(3360701) 186020307026

8. Create a Java applet to Enter product name in one TextField, Base


Price in another TextField and third TextField having rate of GST.
Place a button Calculate. Upon Clicking that the final price of the
product should be dispplayed along with the product name.

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

public class p2_8 extends Applet{

TextField tf1 = new


TextField(20); TextField tf2 =
new TextField(20); TextField tf3
= new TextField(20);

Button b1 = new Button("CALCULATE");

Label l1 = new Label("PRODUCT NAME");


Label l2 = new Label("PRODUCT
PRICE"); Label l3 = new Label("GST
RATE");
Label l4 = new Label("ANSWER WILL COME HERE");

public void init()


{ add(l1);
add(tf1);

add(l2);
add(tf2);

add(l3);
add(tf3);

add(b1);

add(l4);
b1.addActionListener(new ActionListener(){
public void
actionPerformed(ActionEvent
Computer Department A. V. Parekh Technical Institute 9|Pag e
Advance Java Programming(3360701) 186020307026

Integer amount
= Integer.parseInt(tf2.getText());
Integer rate =
Integer.parseInt(tf3.getText());

price = amount + (amount * rate/100);

l4.setText(tf1.getText() + " price =


" + price);
}
});
}
}

//
//<APPLET CODE="p2_8.java" width="320"
height="200"></APPLET>
//

Computer Department A. V. Parekh Technical Institute 10 | P a g e


Advance Java Programming(3360701) 186020307026

9. Develop a program to launch an appplet from a Frame.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="p2_9.class" width=300 height=50>
</applet>
*/
class SampleFrame extends Frame
{
SampleFrame()
{
setTitle("Frame Window");
MyWindowAdapter adapter = new
MyWindowAdapter(this);
addWindowListener(adapter);
}
public void paint(Graphics g)
{
g.drawString("This is in frame window", 50,
50);
}
}
class MyWindowAdapter extends WindowAdapter
{ SampleFrame sampleFrame;
public MyWindowAdapter(SampleFrame
sampleFrame)
{
this.sampleFrame = sampleFrame;
}
public void windowClosing(WindowEvent we)
{
sampleFrame.setVisible(false);
}
}

public class p2_9 extends Applet


{

Computer Department A. V. Parekh Technical Institute 11 | P a g e


Advance Java Programming(3360701) 186020307026

Frame f;
public void init()
{
f = new SampleFrame();
f.setSize(250, 250);
f.setVisible(true);
}
public void start()
{
f.setVisible(true);
}

public void stop()


{
f.setVisible(false);
}

public void paint(Graphics g)


{
g.drawString("This is in applet window",
10,
20);
}
}

Computer Department A. V. Parekh Technical Institute 12 | P a g e


Advance Java Programming(3360701) 186020307026

Computer Department A. V. Parekh Technical Institute 13 | P a g e


Advance Java Programming(3360701) 186020307026

10.Create an Applet having 2 ListBox "List1" and "List2". Data can be


added in "List1" using a TextField and and "Add Item" button.
Then we can move items between two ListBoxes using Move to List2
and Move to List1 Buttons.

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

public class p2_10 extends


Applet{ List l1 = new
List(5,true); List l2 = new
List(5,true);

Button b = new Button("Add Item");


Button b1 = new Button("MOVE TO
LIST2"); Button b2 = new Button("MOVE TO
LIST1");

TextField tf=new TextField(30);

public void init(){


add(tf);
add(b);

b.addActionListener(new ActionListener(){
public void
actionPerformed(ActionEvent
ae) {
l1.add(tf.getText());
tf.setText("");
}
});

add(l1);
add(b1);
b1.addActionListener(new ActionListener(){
public void
actionPerformed(ActionEvent
Computer Department A. V. Parekh Technical Institute 14 | P a g e
Advance Java Programming(3360701) 186020307026

});

add(l2);
add(b2);
b2.addActionListener(new ActionListener(){
public void
actionPerformed(ActionEvent
ae) {
l1.add(l2.getSelectedItem());
l2.remove(l2.getSelectedItem());
}
});
}
}

//
//<APPLET CODE="p2_10.java" width="320"
height="200"></APPLET>
//

Computer Department A. V. Parekh Technical Institute 15 | P a g e


Advance Java Programming(3360701) 186020307026

11.Create a frame window of 300x200 with a label of “Hello Java from


Frame Window” and the frame window should close when the Close
button of the window is clicked.

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

public class p2_11 extends

Frame{ public p2_11() {

Label l = new Label("Hello Java from Frame


Window");
add(l);

addWindowListener(new WindowListener(){
public void windowClosing(WindowEvent
we){
System.exit(0);
}
public void windowDeactivated(WindowEvent
we){
System.out.println("DEACTIVATED!");
}
public void windowActivated(WindowEvent
we){
System.out.println("ACTIVATED!");
}
public void windowClosed(WindowEvent we){
System.out.println("Closed");
}
public void windowIconified(WindowEvent
we){
System.out.println("ICONIFIED");
}
public void windowOpened(WindowEvent we){
System.out.println("OPENED");
}

Computer Department A. V. Parekh Technical Institute 16 | P a g e


Advance Java Programming(3360701) 186020307026

public void windowDeiconified(WindowEvent


we){
System.out.println("DEICONIFIED!");
}
});

setSize(300,200);
setVisible(true);
}

public static void main(String[] args) {


p2_11 obj = new p2_11();
}
}

Computer Department A. V. Parekh Technical Institute 17 | P a g e


Advance Java Programming(3360701) 186020307026

12.Create a applet that contains "Generate" button upon clicking that it


should display number of circles entered in Textfield by user.

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

public class p2_12 extends


Applet{ TextField tf = new
TextField(2);

Label l = new Label("ENTER NO. OF

CIRCLES"); Button b = new

Button("GENERATE");

public void init() {


setLayout(new
FlowLayout()); add(l);
add(tf);
add(b);
b.addActionListener(new ActionListener() {
public void
actionPerformed(ActionEvent
ae) {
repaint();
}
});
}

public void paint(Graphics g){


System.out.println("ACTION HANDLED!");
int n;
if(tf.getText().isEmpty())
{ n = 0;
}else{
n = Integer.parseInt(tf.getText());

Computer Department A. V. Parekh Technical Institute 18 | P a g e


Advance Java Programming(3360701) 186020307026

for(int i = 0;i < n; i++) {


g.drawOval(x - (i*5), y - (i*5), h +
(i*10), h + (i*10));
}
}
}

//
//<APPLET CODE="p2_12.java" width="600"
height="600"></APPLET>
//

Computer Department A. V. Parekh Technical Institute 19 | P a g e


Advance Java Programming(3360701) 186020307026

13.Create a Frame using GridLayout that will generate a spiral matrix


of size entered by user.

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

public class p2_13 extends Frame

{ public p2_13(int n) {
Frame f = new Frame("SPIRAL MATRIX FRAME");
// f.setLayout(new FlowLayout());
// f.add(tf);

// f.add(b);
int a[][] = new int[n][n];
int c,r,count;

count =
1; r=n;
c=n;
int tn = n*n;
int cr = 0;
int cc = 0;

//count = val
//k = cr
//l = cc
//m = r
//n = c

f.setLayout(new GridLayout(n,n));
while (count<(n*n)) {
for (int i = cc; i < c; ++i) {
a[cr][i] = count++;
}
cr++;
for (int i = cr; i < r; ++i) {
a[i][c - 1] = count++;
}
Computer Department A. V. Parekh Technical Institute 20 | P a g e
Advance Java Programming(3360701) 186020307026

c--;
if (cr < r) {
for (int i = c - 1; i >= cc;
--i) {
a[r - 1][i] = count++;
}
r--;
}
if (cc < c) {
for (int i = r - 1; i >= cr;
--i) {
a[i][cc] = count++;
}
cc++;
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
f.add(new Label("LABEL "
+a[i][j]));
}
}

// b.addActionListener(new ActionListener() {
// public void
actionPerformed(ActionEvent ae)
{
// // int n =
Integer.parseInt(tf.getText());

// }
// });

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

public static void main(String[] args) {


int n = Integer.parseInt(args[0]);

Computer Department A. V. Parekh Technical Institute 21 | P a g e


Advance Java Programming(3360701) 186020307026

p2_13 obj = new p2_13(n);


}
}

Computer Department A. V. Parekh Technical Institute 22 | P a g e


Advance Java Programming(3360701) 186020307026

14.Create a frame of 300x200 having BorderLayout and each should


contain a button having the Label same as the name of that region.
(ex. NORTH, SOUTH, EAST, WEST, CENTER etc.)

let.*; import java.awt.*;


14 extends Applet

1 = new BorderLayout(); Button b1= new Button("North"); Button b2= new Button("South"); Button b3=
Button("West"); Button b5= new Button("Center");

1); add("North",b1);
);

;
5);

"p2_14.class" width = 300 height = 200>

Computer Department A. V. Parekh Technical Institute 23 | P a g e


Advance Java Programming(3360701) 186020307026

15.Create a frame and demonstrate CardLayout that displays list


of subjects in semesterwise Cards . ( Semester 1 - Computer
Programming,Fundamental of digital electronics) place a home
button to return to the main card.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class p2_15 extends

JFrame{ Label l1,l2,l3,l4;


Button nxt,prv,home;
CardLayout cl;

public p2_15(){
setLayout(new

BorderLayout()); cl = new

CardLayout();

nxt = new Button("NEXT");


prv = new Button("PREV");
home = new
Button("HOME");

add(nxt,BorderLayout.EAST);
add(prv,BorderLayout.WEST);
add(home,BorderLayout.SOUTH);

Panel sem1Panel = new Panel(cl);


Panel titlePanel = new Panel(new
FlowLayout());
Panel cpPanel = new Panel(new FlowLayout());
Panel fdePanel = new Panel(new
FlowLayout()); Panel fcaPanel = new
Panel(new FlowLayout());

Computer Department A. V. Parekh Technical Institute 24 | P a g e


Advance Java Programming(3360701) 186020307026

l3 = new Label("FUNDAMENTAL OF DIGITAL


ELECTRONICS (3310702)");
l4 = new Label("FUNDAMENTAL OF COMPUTER
APPLICATION (3310703)");

titlePanel.add(l1);
cpPanel.add(l2);
fdePanel.add(l3);
fcaPanel.add(l4);

sem1Panel.add(titlePanel,"TITLE");
sem1Panel.add(cpPanel,"CP");
sem1Panel.add(fdePanel,"FDE");
sem1Panel.add(fcaPanel,"FCA");

add(sem1Panel, BorderLayout.CENTER);

nxt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent
ae){
cl.next(sem1Panel);
}
});

prv.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent
ae){
cl.previous(sem1Panel);
}
});

home.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent
ae){
cl.first(sem1Panel);
}
});

setSize(300,300);

Computer Department A. V. Parekh Technical Institute 25 | P a g e


Advance Java Programming(3360701) 186020307026

setVisible(true);
}

public static void main(String[] args) {


p2_15 obj = new p2_15();
}
}

Computer Department A. V. Parekh Technical Institute 26 | P a g e


Advance Java Programming(3360701) 186020307026

16.Create a frame having button with label “Click”, and implement


MouseListener on that which should display appropriate event
message on console window.

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

public class p2_16 extends Frame implements


MouseListener{

Button b;

public p2_16()

{
setSize(300,300);
setLayout(new FlowLayout());

b = new Button("BUTTON");
add(b);
b.addMouseListener(this);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent
we){
dispose();
}
});

setVisible(true);
}

public void mouseClicked(MouseEvent me)


{ System.out.println("MOUSE
CLICKED");
}

public void mouseEntered(MouseEvent me)

Computer Department A. V. Parekh Technical Institute 27 | P a g e


Advance Java Programming(3360701) 186020307026

public void mouseExited(MouseEvent me) {


System.out.println("MOUSE EXITED FROM THE
REGION");
}

public void mousePressed(MouseEvent me) {


System.out.println("MOUSE CLICK
PRESSED");
}

public void mouseReleased(MouseEvent me) {


System.out.println("MOUSE CLICK
RELEASED");
}

public static void main(String[] args) {


p2_16 obj = new p2_16();
}

Computer Department A. V. Parekh Technical Institute 28 | P a g e


Advance Java Programming(3360701) 186020307026

17.Create an applet which displays cursor co-ordinates on Applet below


the mouse pointer.

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

public class p2_17 extends Applet{

int x = 0;
int y = 0;

public void init(){


setBackground(new Color(200,200,200));
addMouseMotionListener(new
MouseMotionListener(){
public void mouseMoved(MouseEvent me)
{ x = me.getX();
y = me.getY();
repaint();
}

public void mouseDragged(MouseEvent me) {


x = me.getX();
y = me.getY();
repaint();
}
});
}

public void paint(Graphics g) {

g.drawString("("+ x + "," + y + ")", x , y);


}
}

/*
<APPLET CODE = "p2_17.class" WIDTH=300
HEIGHT=300></APPLET> */

Computer Department A. V. Parekh Technical Institute 29 | P a g e


Advance Java Programming(3360701) 186020307026

Computer Department A. V. Parekh Technical Institute 30 | P a g e


Advance Java Programming(3360701) 186020307026

18.Create an applet window and implement WindowListener on that


which should display appropriate event message on console window
according to the event performed on the window.

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

public class p2_18 extends Frame implements


WindowListener {
public p2_18(){
Label l = new Label("WINDOW LISTENER
EXAMPLE");
add(l);
addWindowListener(this);
setVisible(true);
setSize(300,200);
}

public static void main(String[] args) {


p2_18 obj = new p2_18();
}
public void windowOpened(WindowEvent we)
{ System.out.println("WINDOW
OPENED!");
}
public void windowClosing(WindowEvent we)
{ System.out.println("WINDOW CLOSING
"); dispose();
}
public void windowClosed(WindowEvent we)
{ System.out.println("WINDOW CLOSED");
}
public void windowActivated(WindowEvent we)
{ System.out.println("WINDOW
ACTIVATED!");
}
public void windowDeactivated(WindowEvent we)
{ System.out.println("WINDOW DEACTIVATED");
}
Computer Department A. V. Parekh Technical Institute 31 | P a g e
Advance Java Programming(3360701) 186020307026

System.out.println("WINDOW ICONIFIED");
}
public void windowDeiconified(WindowEvent we)
{ System.out.println("WINDOW DEICONIFIED");
}
}
/*
<APPLET CODE = "p2_18.class" WIDTH=300 HEIGHT=300>
</APPLET>
*/

Computer Department A. V. Parekh Technical Institute 32 | P a g e


Advance Java Programming(3360701) 186020307026

19.Create a Jframe for user registration having details like Name,


Phone No, Gender, Birth Year (Using Dropdown list). Clicking on a
button Display will show all the data enterd in the form in a Dialog
Box.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class MyFrame extends JFrame implements


ActionListener {

private Container c;
private JLabel title , name , mno , gender , dob
, res;
private JTextField tname , tmno;
private JRadioButton male , female;
private ButtonGroup gengp;
private JComboBox date , month ,
year; private JTextArea tadd;
private JButton sub;
private JTextArea tout;

private String dates[] = { "1", "2", "3", "4",


"5","6", "7", "8", "9", "10","11", "12", "13", "14",
"15","16", "17", "18", "19", "20","21", "22", "23",
"24", "25","26", "27", "28", "29", "30","31" };
private String months[] = { "Jan", "feb", "Mar",
"Apr","May", "Jun", "July", "Aug","Sup", "Oct",
"Nov", "Dec" };
private String years[]= { "1995", "1996",
"1997", "1998","1999", "2000", "2001", "2002","2003",
"2004", "2005", "2006","2007", "2008",};

public MyFrame()
{
setTitle("Registration Form");
setBounds(300, 90, 900, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);

Computer Department A. V. Parekh Technical Institute 33 | P a g e


Advance Java Programming(3360701) 186020307026

setResizable(false);

c = getContentPane();
c.setLayout(null);

title = new JLabel("Registration Form");


title.setFont(new Font("Arial", Font.PLAIN,
30));
title.setSize(300, 30);
title.setLocation(300, 30);
c.add(title);

name = new JLabel("Name");


name.setFont(new Font("Arial", Font.PLAIN,
20));
name.setSize(100, 20);
name.setLocation(100, 100);
c.add(name);

tname = new JTextField();


tname.setFont(new Font("Arial", Font.PLAIN,
15));
tname.setSize(190, 20);
tname.setLocation(200, 100);
c.add(tname);

mno = new JLabel("Mobile");


mno.setFont(new Font("Arial", Font.PLAIN,
20));
mno.setSize(100, 20);
mno.setLocation(100, 150);
c.add(mno);

tmno = new JTextField();


tmno.setFont(new Font("Arial", Font.PLAIN,
15));
tmno.setSize(150, 20);
tmno.setLocation(200, 150);
c.add(tmno);

Computer Department A. V. Parekh Technical Institute 34 | P a g e


Advance Java Programming(3360701) 186020307026

gender = new JLabel("Gender");


gender.setFont(new Font("Arial", Font.PLAIN,
20));
gender.setSize(100, 20);
gender.setLocation(100, 200);
c.add(gender);

male = new JRadioButton("Male");


male.setFont(new Font("Arial", Font.PLAIN,
15));
male.setSelected(true);
male.setSize(75, 20);
male.setLocation(200, 200);
c.add(male);

female = new JRadioButton("Female");


female.setFont(new Font("Arial", Font.PLAIN,
15));
female.setSelected(false);
female.setSize(80, 20);
female.setLocation(275, 200);
c.add(female);

gengp = new ButtonGroup();


gengp.add(male);
gengp.add(female);

dob = new JLabel("DOB");


dob.setFont(new Font("Arial", Font.PLAIN,
20));
dob.setSize(100, 20);
dob.setLocation(100, 250);
c.add(dob);

date = new JComboBox(dates);


date.setFont(new Font("Arial", Font.PLAIN,
15));
date.setSize(50, 20);

Computer Department A. V. Parekh Technical Institute 35 | P a g e


Advance Java Programming(3360701) 186020307026

date.setLocation(200, 250);
c.add(date);

month = new JComboBox(months);


month.setFont(new Font("Arial", Font.PLAIN,
15));
month.setSize(60, 20);
month.setLocation(250, 250);
c.add(month);

year = new JComboBox(years);


year.setFont(new Font("Arial", Font.PLAIN,
15));
year.setSize(60, 20);
year.setLocation(320, 250);
c.add(year);

sub = new JButton("Submit");


sub.setFont(new Font("Arial", Font.PLAIN,
15));
sub.setSize(100, 20);
sub.setLocation(150, 350);
sub.addActionListener(this);
c.add(sub);

tout = new JTextArea();


tout.setFont(new Font("Arial", Font.PLAIN,
15));
tout.setSize(300, 400);
tout.setLocation(500, 100);
tout.setLineWrap(true);
tout.setEditable(false);
c.add(tout);

res = new JLabel("");


res.setFont(new Font("Arial", Font.PLAIN,
20));
res.setSize(500, 25);
res.setLocation(100, 500);

Computer Department A. V. Parekh Technical Institute 36 | P a g e


Advance Java Programming(3360701) 186020307026

c.add(res);

setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == sub)
{
String data1;
String data = "Name : "+
tname.getText() + "\n"+ "Mobile : "+ tmno.getText() +
"\n";
if (male.isSelected())
data1 = "Gender :
Male"
+ "\n";
else
data1 = "Gender : Female"
+ "\n";
String data2 = "DOB :
"+ (String)date.getSelectedItem()+ "/" +
(String)month.getSelectedItem() + "/" +
(String)year.getSelectedItem()+ "\n";
tout.setText(data + data1 + data2);
tout.setEditable(false);
res.setText("Registration
Successfully..");
}
}
}
class p2_19 {
public static void main(String[] args) throws
Exception
{
MyFrame f = new MyFrame();
}
}

Computer Department A. V. Parekh Technical Institute 37 | P a g e


Advance Java Programming(3360701) 186020307026

Computer Department A. V. Parekh Technical Institute 38 | P a g e


Advance Java Programming(3360701) 186020307026

Practical-3:JAVA DATABSE CONNECTIVITY


20.Develop a console application to connect with the database Store
made in Microsoft Access and display "Connection Successful"
message on console if the connection is OK using ODBC Driver.

import java.sql.*;

public class p3_20{


public static void main(String args[])
{ try{

Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/t
est","root","");
if(con != null)
System.out.println("Connection
Successfully...!!! ");
else
System.out.println("connection
error...!!!");
}catch(Exception e)
{ e.printStackTrace(
);
}
}

Computer Department A. V. Parekh Technical Institute 39 | P a g e


Advance Java Programming(3360701) 186020307026

21.Write a JDBC Console application create table “Product” with


columns ID(int PK, AUTO INCREMENT), Name(varchar(60)),
Price(double) and Quantity(int) stored in MySql Databse
“Product_Data” .

import java.sql.*;

public class p3_21

{
public static void main(String args[]){
try{

Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/t
est","root","");
Statement st = con.createStatement();
st.executeUpdate("CREATE TABLE Product(ID
int AUTO_INCREMENT PRIMARY KEY,Name
varchar(60),Price double, Quantity int);");
System.out.println("TABLE CREATED!");
con.close();
} catch(Exception e){
e.printStackTrace();
}
}
}

Computer Department A. V. Parekh Technical Institute 40 | P a g e


Advance Java Programming(3360701) 186020307026

22.Write a JDBC Console application to populate the data in


“Product” table as below, get those Data from user.
1-Watch-1200-10
2-Hat-75-50
3-Jeans-1600-23
4-Polo-900-52

import java.sql.*;
import java.util.Scanner;
// import java.util.Locale;

// class Product{
// int ID,quantity;
// String name;
// double price;
// }

public class p3_22 {


public static void main(String args[]){
try{
System.out.println("Enter 4 products
data as Name Price Quantity Format:");
// for(int i=0;i<4;i++) {
// p[i].name=sc.nextLine();
// p[i].price=sc.nextDouble();
// p[i].quantity=sc.nextInt();
// }

Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/t
est","root","");
Statement st = con.createStatement();
for(int i=0;i<4;i++){
String name;
int quantity;
double price;
Scanner sc =
new
Scanner(System.in);
Computer Department A. V. Parekh Technical Institute 41 | P a g e
Advance Java Programming(3360701) 186020307026

name=sc.nextLine();
price=sc.nextDouble();
quantity=sc.nextInt();
String sql = "INSERT INTO
Product VALUES(NULL,'" + name + "'," + price + "," +
quantity
+ ");";
st.executeUpdate(sql);
System.out.println("");
}
con.close();
System.out.println("DATA INSERTED!");
} catch(Exception e){
e.printStackTrace();
}
}

Computer Department A. V. Parekh Technical Institute 42 | P a g e


Advance Java Programming(3360701) 186020307026

23.Write a JDBC Console application to display all records of the table


“Product” having price greater than Rs. 1000.

import java.sql.*;

public class p3_23 {


public static void main(String args[]){
try{

Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/t
est","root","");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT
*
FROM Product");

System.out.println("ID\tName\tPrice\tQuantity");
while(rs.next()){
System.out.println(rs.getInt(1) +
"\t" + rs.getString(2) + "\t" + rs.getDouble(3) +
"\t" + rs.getInt(4));
}
con.close();
} catch(Exception e){
e.printStackTrace()
;
}
}

Computer Department A. V. Parekh Technical Institute 43 | P a g e


Advance Java Programming(3360701) 186020307026

24.Write a JDBC Console application to update value of Quantity of


all the products to 100 having price less than 1000.

import java.sql.*;

public class p3_24 {


public static void main(String args[]){
try{

Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/t
est","root","");
Statement st =
con.createStatement();
st.executeUpdate("UPDATE Product SET
Quantity=100 where Price<1000;");
System.out.println("CHECK DB For updated
values!");
con.close();
} catch(Exception e){
e.printStackTrace()
;
}
}

Computer Department A. V. Parekh Technical Institute 44 | P a g e


Advance Java Programming(3360701) 186020307026

25.Write a JDBC console Application to delete a row by asking ID of


the Product from user and then display count of number of rows in
the database.

import java.sql.*; import java.util.Scanner;

public class p3_25 {


public static void main(String args[]){ try{
Scanner sc = new Scanner(System.in);

Class.forName("com.mysql.cj.jdbc.Driver"); Connection con =


DriverManager.getConnection("jdbc:mysql://localhost/t est","root","");
Statement st = con.createStatement(); System.out.print("ENTER ID TO DELETE
PRODUCT : ");
int id = sc.nextInt(); st.executeUpdate("DELETE FROM PRODUCT
WHERE ID = " + id);
ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM Product;");
rs.next();
System.out.println(rs.getInt(1) + " rows
left");
con.close();
} catch(Exception e){ e.printStackTrace();
}
}
}

Computer Department A. V. Parekh Technical Institute 45 | P a g e


Advance Java Programming(3360701) 186020307026

Practical-4: JAVA SERVLETS


Web.xml
<web-app>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>first</servlet-class>
</servlet>

<servlet>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

<servlet-name>second</servlet-name>
<servlet-class>second</servlet-class>
</servlet>

<servlet>
<servlet-name>third</servlet-name>
<servlet-class>third</servlet-class>
</servlet>

<servlet>
<servlet-name>third_1</servlet-name>
<servlet-class>third_1</servlet-class>
</servlet>

Computer Department A. V. Parekh Technical Institute 46 | P a g e


Advance Java Programming(3360701) 186020307026

<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>third</servlet-name>
<url-pattern>/third</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>third_1</servlet-name>
<url-pattern>/third_1</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>second</servlet-name>
<url-pattern>/second</url-pattern>
</servlet-mapping>
</web-app>

Computer Department A. V. Parekh Technical Institute 47 | P a g e


Advance Java Programming(3360701) 186020307026

26.Write a Generic Servlet and servlet mapping code which displays


“Hello World” string in the browser window upon running.

Index.html
<html>
<head><title>P4_3</title></head>
<body>
<form action = "third" method = "post">

Username:<input type = "text" name = "username">


Password:<input type ="password" name = "pass">
<input type ="submit" name = "Login" value = "login">
</form>
</body>
</html>

first.java
import java.io.*;
import javax.servlet.*;

public class first extends GenericServlet{


public void service(ServletRequest
req,
ServletResponse res) throws
IOException,ServletException{
res.setContentType("text/html");

PrintWriter out =

res.getWriter();

out.println("<html><head><title>first</title></head><
body><h1>HELLOWORLD</h1></body></html>");

Computer Department A. V. Parekh Technical Institute 48 | P a g e


Advance Java Programming(3360701) 186020307026

27.Write a servlet and servlet mapping code for simple Servlet


which displays “Hello {User}” string in the browser window
where user value is passed through deployment descriptor file.

second.html
<html>
<head><title>P4_2</title></head>
<body>
<form action = "second" method = "post">

Username:<input type = "text" name = "username">


<input type ="submit" name = "Login" value = "login">
</form>
</body>
</html>

second.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class second extends HttpServlet {


public void doPost(HttpServletRequest req,
HttpServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String n=req.getParameter("username");
out.print("Welcome "+n);
out.close();
}
}

Computer Department A. V. Parekh Technical Institute 49 | P a g e


Advance Java Programming(3360701) 186020307026

Computer Department A. V. Parekh Technical Institute 50 | P a g e


Advance Java Programming(3360701) 186020307026

28.Write a servlet and servlet mapping code to for log in and welcome
page of the user containing Log Out button. Make use of Session to
load the home page. If the session is not created then the user should
automatically redirected to Log In page. Username should be passed
and a welcome message with the username should be displayed on
welcome page if the session is set. Username is to be passed through
cookie.

29.Write an application using servlet to perform CRUD operations


on MySQL database connected to the servlet with type-4 driver.
Also apply a basic formatting in the page.

web.xml
<web-app>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>first</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>save_customer</servlet-name>
<servlet-class>save_customer</servlet-class>
</servlet>

<servlet>
<servlet-name>update_customer</servlet-name>
<servlet-class>update_customer</servlet-class>
</servlet>

<servlet>
<servlet-name>delete_customer</servlet-name>
<servlet-class>delete_customer</servlet-class>
</servlet>

<servlet>

Computer Department A. V. Parekh Technical Institute 51 | P a g e


Advance Java Programming(3360701) 186020307026

<servlet-name>view_customer</servlet-name>
<servlet-class>view_customer</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>save_customer</servlet-name>
<url-pattern>/save_customer</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>update_customer</servlet-name>
<url-pattern>/update_customer</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>delete_customer</servlet-name>
<url-pattern>/delete_customer</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>view_customer</servlet-name>
<url-pattern>/view_customer</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

index.html
<html>
<head><title>p4_4</title></head>
<body>
<h1>Insert customer data</h1>
<form action = "save_customer" method = "post">
Name:<input type="text" name=
"name"/><br/><br/>
Address:<input type="text"
name="add"/><br/><br/>

Computer Department A. V. Parekh Technical Institute 52 | P a g e


Advance Java Programming(3360701) 186020307026

<input type ="submit" value ="insert"/>


</form>
</body>
</html>

customer.java
package entity;

public class
customer{ private
int id; private String
name;
private String address;

public String getAddress()


{ return address;
}

public void setAddress(String address)


{ this.address = address;
}

public int getId(){


return id;
}
public void setId(int id)
{ this.id = id;
}

public String getName(){


return name;
}
public void setName(String name)
{ this.name = name;
}

public String toString(){


return "customer{"+"id="+id+",name =
"+name+",address ="+address+"}";
}}
Computer Department A. V. Parekh Technical Institute 53 | P a g e
Advance Java Programming(3360701) 186020307026

CustomerDB.java
package db;
import entity.customer;
import java.sql.*;
import java.util.*;

public class CustomerDB{


public static Connection getConnection()
{ Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost/t
est","root","");
}catch(Exception e)
{ System.out.println(e
);
}
return con;
}
public static int save(customer c){
int status = 0;
try{
Connection con =
CustomerDB.getConnection();
PreparedStatement pst =
con.prepareStatement("insert into
customer(name,address) values(?,?)");

pst.setString(1,c.getName());
pst.setString(2,c.getAddress());
status = pst.executeUpdate();
con.close();
}catch(Exception e)
{ e.printStackTrace(
);

}
return status;
}
public static int update(customer c){
Computer Department A. V. Parekh Technical Institute 54 | P a g e
Advance Java Programming(3360701) 186020307026

int status = 0;
try{
Connection con =
CustomerDB.getConnection();
PreparedStatement pst =
con.prepareStatement("update customer set name=?,
address=? where id =?");

pst.setString(1,c.getName());
pst.setString(2,c.getAddress());
pst.setInt(3,c.getId());

status = pst.executeUpdate();

con.close();
}catch(Exception e){
e.printStackTrace();
}
return status;
}

public static customer getCustomerById(int id){


customer c = new customer();

try{
Connection con =
CustomerDB.getConnection();
PreparedStatement pst =
con.prepareStatement("Select * from customer where id
= ?");

pst.setInt(1,id);
ResultSet rs = pst.executeQuery();
if(rs.next()){
c.setId(rs.getInt(1));
c.setName(rs.getString(2));
c.setAddress(rs.getString(3));
}
con.close();

Computer Department A. V. Parekh Technical Institute 55 | P a g e


Advance Java Programming(3360701) 186020307026

}catch(Exception e)
{ e.printStackTrace(
);

}
return c;
}
public static int delete(int id)
{ int status = 0;
try{
Connection con =
CustomerDB.getConnection();
PreparedStatement pst =
con.prepareStatement("delete from customer where id =
?");
pst.setInt(1,id);
status = pst.executeUpdate();
con.close();
}catch(Exception e){
e.printStackTrace();
}
return status;
}
public static List<customer> getAllCustomer(){
List<customer> list=new
ArrayList<customer>();

try{
Connection
con=CustomerDB.getConnection();
PreparedStatement
ps=con.prepareStatement("select * from customer");
ResultSet rs=ps.executeQuery();
while(rs.next()){
customer c=new customer();
c.setId(rs.getInt(1));
c.setName(rs.getString(2));
c.setAddress(rs.getString(3));

Computer Department A. V. Parekh Technical Institute 56 | P a g e


Advance Java Programming(3360701) 186020307026

list.add(c);
}
con.close();
}catch(Exception e){e.printStackTrace();}

return list;
}
}

delete_customer.java

import entity.customer;
import db.CustomerDB;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class delete_customer extends


HttpServlet{ protected void
doPost(HttpServletRequest req,
HttpServletResponse res) throws
IOException,ServletException{
res.setContentType("text/html");

PrintWriter out = res.getWriter();


String id = req.getParameter("id");
CustomerDB.delete(Integer.parseInt(id));
out.println("Deleted successfully");
out.println("<a
href='view_customer'>View_customer</a>");
out.close();
}

protected void doGet(HttpServletRequest req,


HttpServletResponse res) throws
IOException,ServletException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String idpara = req.getParameter("id");

Computer Department A. V. Parekh Technical Institute 57 | P a g e


Advance Java Programming(3360701) 186020307026

customer cus =
CustomerDB.getCustomerById(Integer.parseInt(idpara));
out.println("<html><body><h1>Delete
customer</h1>");
out.println("<form
action='/CRUD/delete_customer' method='post'>");
out.println("<h4>please click Delete Button
for deleting Data</h4>");
out.println("<input type='hidden' value =
'"+cus.getId()+"'name = 'id'/>");
out.println("<input type='submit' value
='delete'/><br/>");
out.println("</form></body></html>");

out.close();
}
}

save_customer.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import entity.customer;
import db.CustomerDB;

public class save_customer extends HttpServlet


{
public void doPost(HttpServletRequest req,
HttpServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");

PrintWriter out = res.getWriter();


String name =req.getParameter("name");
String add =req.getParameter("add");

customer c= new customer();


c.setAddress(add);

Computer Department A. V. Parekh Technical Institute 58 | P a g e


Advance Java Programming(3360701) 186020307026

c.setName(name);

CustomerDB.save(c);

out.println("Data Inserted
successfull");

out.println("<a
href='view_customer'>View_customer</a>");

out.close();

}
}

update_customer.java

import db.CustomerDB;
import entity.customer;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class update_customer extends


HttpServlet{ protected void
doPost(HttpServletRequest req,
HttpServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");

PrintWriter out = res.getWriter();


String name = req.getParameter("name");
String address =
req.getParameter("address");
String id = req.getParameter("id");

customer c = new customer();

Computer Department A. V. Parekh Technical Institute 59 | P a g e


Advance Java Programming(3360701) 186020307026

c.s etName(name);
c.setAddress(address);
c.setId(Integer.parseInt(id));
CustomerDB.update(c);
out.println("updated Successfully" +
c.t oString());
out.println("<a
href='view_customer'>View_customer</a>");
out.close();
}
protected void doGet(HttpServletRequest req,
HttpServletResponse res) throws
IOException,ServletException{
res.setContentType("text/html");

PrintWriter out = res.getWriter();

String idpara = req.getParameter("id");

customer cus =
CustomerDB.getCustomerById(Integer.parseInt(idpara));

out.println("<html>");
out.println("<body>");
out.println("<h1>update Customer</h1>");
out.println("<form
action='/CRUD/update_customer' method='post'>");
out.println("Name <input type ='text' value
='"+cus.getName()+"'name= 'name'/><br/>");
out.println("Address <input type ='text'
value ='"+cus.getAddress()+"'name=
'address'/><br/>");
out.println("<input type ='hidden' value
='"+cus.getId()+"'name= 'id'/>");
out.println("<input type ='submit' value
='update'/><br/>");
out.println("</form");
out.println("</body>");

Computer Department A. V. Parekh Technical Institute 60 | P a g e


Advance Java Programming(3360701) 186020307026

out.println("</html>");

out.close();
}
}

view_cutomer.java
import entity.customer;
import db.CustomerDB;
import java.sql.*;
import java.io.*;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;

public class view_customer extends HttpServlet {


protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<a href='index.html'>Add New
Customer</a>");
out.println("<h1>Customer List</h1>");

List<customer> list=
CustomerDB.getAllCustomer();

out.print("<table border='1' width='100%'");

out.print("<tr><th>Id</th><th>Name</th><th>Address</t
h><th>Edit</th><th>Delete</th></tr>");
for(customer c:list){

out.print("<tr><td>"+c.getId()+"</td><td>"+c.getName(
)+"</td><td>"+c.getAddress()+"</td><td><a
href='update_customer?id="+c.getId()+"'>edit</a></td>
<td><a

Computer Department A. V. Parekh Technical Institute 61 | P a g e


Advance Java Programming(3360701) 186020307026

href='delete_customer?id="+c.getId()+"'>delete</a></t
d></tr>");
}
out.print("</table>");

out.close();
}
}

Computer Department A. V. Parekh Technical Institute 62 | P a g e


Advance Java Programming(3360701) 186020307026

Computer Department A. V. Parekh Technical Institute 63 | P a g e


Advance Java Programming(3360701) 186020307026

Practical-5: JAVA SERVER PAGES


30.Create an HTML page with a textbox to enter the name of user and a
button "Submit" which trasfers the control to another JSP page and
display a Hello Message with username passed from HTML page and
display the current Date and Time with it.

P5_1.html
<html>
<head><title>P5_1</title></head>

<body>
<form action ="P5_1.jsp" method ="POST">
Username:<input type='text' name = 'name'
><br/><br/>
<input type='submit' value = 'Submit'>
</form>
</body>
</html>

P5_1.jsp

<%
out.print("<h1>Hello"+"<b>"+request.getParameter(
"name")+"
<b></h1>");
out.print("<br><h1>Today's Date :-"+ new
java.util.Date());
%>

Computer Department A. V. Parekh Technical Institute 64 | P a g e


Advance Java Programming(3360701) 186020307026

31.Create a JSP page which displays a table of Square root of


numbers from 0 to 16.

<%
out.print("<table border =1>");
out.print("<h1>Square root</h1>");
out.print("<tr>");
out.print("<th>NO.</th>");
out.print("<th>Square root</th>");
out.print("</tr>");

for(int n=0;n<=16;n++)
{
out.print("<tr>");
out.print("<td>");
%>
<%= n %>
<%
out.print("</td>");
out.print("<td>");
%>
<%= Math.sqrt(n) %>
<%
out.print("</td>");
out.print("</tr>");
}
out.print("</table>");
%>

Computer Department A. V. Parekh Technical Institute 65 | P a g e


Advance Java Programming(3360701) 186020307026

Computer Department A. V. Parekh Technical Institute 66 | P a g e


Advance Java Programming(3360701) 186020307026

32.Design a JSP page and define 3 variables n1, n2 and n3 having


values 12, 13 and 15 respectively and then using Expression Tags
display the result of sum of those 3 variables.

<%
int n1= 12;
int n2= 13;
int n3= 15;
out.print("Sum of <br> n1="+n1+"<br>
n2="+n2+"<br> n3="+n3+"<br>ANS:=");
%>
<%= n1+n2+n3 %>

Computer Department A. V. Parekh Technical Institute 67 | P a g e


Advance Java Programming(3360701) 186020307026

33.Design a JSP page with a button "Click" on it and clicking on that


button will give the count of how many times that button is clicked.

<%! int click = 0; %>


<%
String Param = request.getParameter("integer");

try{
int i =Integer.parseInt(Param);

click++;
}catch(NumberFormatException e){

}
%>

<p>Number of clicks:<%= click %> </p>


<form action ="" >
<input type = "text" name="integer" value ="1">
<input type = "submit" value ="click">
</form>

Computer Department A. V. Parekh Technical Institute 68 | P a g e


Advance Java Programming(3360701) 186020307026

34.Develop a simple JSP program for user login form with database
connectivity.

Computer Department A. V. Parekh Technical Institute 69 | P a g e

You might also like