You are on page 1of 99

Java Technology M.

Sc IT Part II
___________________________________________________________________________

Practical 01
Problem Statement:

Design a program to implement concept of class, constructor and inheritance (extends).


Design a class to represent a Bank Account.
a. Account Name
b. Depositor’s Name
c. Type of Account
d. Balance amount in account
Methods:
a. to assign initial value
b. to deposit an amount
c. to withdraw an amount after checking balance
d. to display name and balance

Description:

JFrame

The size of the frame includes any area designated for the border. The dimensions of the
border area may be obtained using the getInsets method, however, since these dimensions
are platform-dependent, a valid insets value cannot be obtained until the frame is made
displayable by either calling pack or show. Since the border area is included in the overall size
of the frame, the border effectively obscures a portion of the frame, constraining the area
available for rendering and/or displaying subcomponents to the rectangle which has an upper-
left corner location of (insets.left, insets.top), and has a size of width - (insets.left +
insets.right) by height - (insets.top + insets.bottom).

The default layout for a frame is BorderLayout.

ActionListener:
The listener interface for receiving action events. The class that is interested in
processing an action event implements this interface, and the object created with that class is
registered with a component, using the component's addActionListener method. When the
action event occurs, that object's actionPerformed method is invoked.

_________________________________________________________________________
1
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Container;
class SavingAccount extends JFrame implements ActionListener
{
JButton jb,jb1,jb2;
JTextField t1,t11;
double amount;String accountName;
SavingAccount(double amt,String Aname)
{
super("BANK ACCOUNT INFORMATION");
amount=amt;
accountName=Aname;
}
public void init()
{
Container c = getContentPane();
JPanel panel = new JPanel();

jb=new JButton("DEPOSIT AMOUNT");


jb1=new JButton("WITHDRAW AMOUNT");
jb2=new JButton("SHOW BALANCE AND ACCOUNT HOLDER NAME");

jb.setActionCommand("AddAmount");
jb1.setActionCommand("CheckAmount");
jb2.setActionCommand("ShowBalanceAndName");

jb.addActionListener(this);
jb1.addActionListener(this);
jb2.addActionListener(this);

panel.setLayout(new GridLayout(3,3));
panel.add(new JLabel("ENTER THE AMOUNT"));

panel.add(t1 = new JTextField(20));

panel.add(jb);
panel.add(new JLabel("WITHDRAWING AMOUNT"));
panel.add(t11 = new JTextField(20));

panel.add(jb1);
panel.add(jb2);

c.add(panel);
setSize(1000,100);

_________________________________________________________________________
2
Java Technology M.Sc IT Part II
___________________________________________________________________________
setVisible(true);

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

}
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource() == jb)
{

String a=t1.getText();
double b=Double.parseDouble(a);
amount+=b;
JOptionPane.showMessageDialog(null, "THE AMOUNT
IS="+amount,"DISPLAYING AMOUNT",JOptionPane.INFORMATION_MESSAGE);
}
if(evt.getActionCommand() == "CheckAmount")
{
if(amount>=500)
{ t11.setEditable(true);
String s=t11.getText();
double b=Double.parseDouble(s);
amount=amount-b;
if(amount<500)
{
JOptionPane.showMessageDialog(null,"YOUR
MINIMUM BALANACE SHOULD NOT BE LESS THAN 500 \n","WARNING
MESSAGE",JOptionPane.INFORMATION_MESSAGE);
amount=amount+b;
}
else
{
JOptionPane.showMessageDialog(null,"YOUR TOTAL
AMOUNT IS="+amount,"DISPLAYING
AMOUNT",JOptionPane.INFORMATION_MESSAGE);
}
}
}
if(evt.getActionCommand() == "ShowBalanceAndName")
{

JOptionPane.showMessageDialog(null,"TOTAL BALANCE
IS="+amount+"\n ACCOUNT HOLDER NAME IS="+accountName, "DISPLAYING

_________________________________________________________________________
3
Java Technology M.Sc IT Part II
___________________________________________________________________________
BALANCE AND ACCOUNTHOLDER
NAME",JOptionPane.INFORMATION_MESSAGE);
}
}

}
class AccountDepositerName extends SavingAccount
{
String typeOfAccount;
String depositer;

AccountDepositerName(double amt,String Aname,String saving,String Dname)


{
super(amt,Aname);
typeOfAccount=saving;
depositer=Dname;
}

public void initialVal()


{
JOptionPane.showMessageDialog(null,"NAME OF ACCOUNT
HOLDER="+accountName+"\n NAME OF DEPOSITER="+depositer+"\n TOTAL
AMOUNT="+amount+"\n TYPE OF ACCCONUT NAME=" +typeOfAccount,"INITITAL
INFORMATION IS",JOptionPane.INFORMATION_MESSAGE);
}
}

public class BankAccount


{
public static void main(String args[])
{
AccountDepositerName save=new
AccountDepositerName(5000.00,"Sachin","saving","Rahul");
save.initialVal();
save.init();
}
}

_________________________________________________________________________
4
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
5
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 02-A
Write an Applet Application

Problem Statement:

A graphic program that displays your name four times in a large serif font in plain, bold italic
and bold italic. The name should be displayed on top of each other with equal distance between
them. Each of them should be centered horizontally.

Description:

java.applet package:
Provides the classes necessary to create an applet and the classes an applet uses to
communicate with its applet context. The applet framework involves two entities: the applet
and the applet context. An applet is an embeddable window (see the Panel class) with a few
extra methods that the applet context can use to initialize, start, and stop the applet.The applet
context is an application that is responsible for loading and running applets. For example, the
applet context could be a Web browser or an applet development environment.

Applet class:
An applet is a small program that is intended not to be run on its own, but rather to be
embedded inside another application. The Applet class must be the superclass of any applet
that is to be embedded in a Web page or viewed by the Java Applet Viewer. The Applet class
provides a standard interface between applets and their environment.

_________________________________________________________________________
6
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

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

/*
<applet code="font" width=400 height=200>
</applet>
*/

public class font extends Applet


{

String str,fontName;
Font font;

public void init()


{
str="Hemali";

}
public void start()
{
}
public void paint(Graphics g)
{
font=new Font("Serif",Font.BOLD,18);
g.setFont(font);
g.drawString(str, 150, 80);

font=new Font("Serif",Font.PLAIN,18);
g.setFont(font);
g.drawString(str, 150, 100);

font=new Font("Serif",Font.ITALIC,18);
g.setFont(font);
g.drawString(str, 150, 120);

font=new Font("Serif",Font.BOLD|Font.ITALIC,18);
g.setFont(font);
g.drawString(str, 150, 140);
}
}

_________________________________________________________________________
7
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
8
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 02-B
Problem Statement:

Write a graphics program to prompt user to enter radius. Draw a circle of that radius. Similarly
display different geometric shapes like line, square, rectangle, ellipse and polygon (with more
than four sides) as per the user co-ordinates.

Description:

javax.swing package:
Provides a set of "lightweight" (all-Java language) components that, to the maximum
degree possible, work the same on all platforms

ActionListener:
The listener interface for receiving action events. The class that is interested in
processing an action event implements this interface, and the object created with that class is
registered with a component, using the component's addActionListener method. When the
action event occurs, that object's actionPerformed method is invoked.

ItemListener:
The listener interface for receiving item events. The class that is interested in
processing an item event implements this interface. The object created with that class is then
registered with a component using the component's addItemListener method. When an item-
selection event occurs, the listener object's itemStateChanged method is invoked.

_________________________________________________________________________
9
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

/* <applet code = Applet2b


width = 600
height = 100>
<param name=text value = "Try Application">
</applet> */

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

public class Applet2b extends Applet implements ActionListener,ItemListener


{
String str;
Checkbox circle,rectangle,square,line,oval,polygon;
Panel p1,p2,p3,p4,p5,p6,p7;
CheckboxGroup cbg;
Label l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12,l13;
TextField t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14;
Button b1,b2,b3,b4,b5,b6;
CardLayout co;
int x,y,ch,stx,sty,edx,edy,no,flag=0;
int xpolygon5[];
int ypolygon5[];

public void init()


{
cbg=new CheckboxGroup();
circle=new Checkbox("Circle",cbg,true);
rectangle=new Checkbox("Rectangle",cbg,false);
square=new Checkbox("Square",cbg,false);
line=new Checkbox("Line",cbg,false);
oval=new Checkbox("Oval",cbg,false);
polygon=new Checkbox("Polygon",cbg,false);

xpolygon5=new int[5];
ypolygon5=new int[5];

l1=new Label("Enter radius of circle");


l2=new Label("Enter width of rectangle");
l3=new Label("Enter Heigth of rectangle");
l4=new Label("Enter widt and Height of Square");
l5=new Label("Enter starting X coordinate");
l6=new Label("Enter starting Y coordinate");
_________________________________________________________________________
10
Java Technology M.Sc IT Part II
___________________________________________________________________________

000l7=new Label("Enter ending X coordinate");


l8=new Label("Enter ending Y coordinate");
l9=new Label("Enter width of oval");
l10=new Label("Enter height of oval");
l11=new Label("Enter number of points for Polygon(>4 and <11)");
l12=new Label("Enter X coordinate");
l13=new Label("Enter Y coordinate");

b1=new Button("Display");
b2=new Button("Display");
b3=new Button("Display");
b4=new Button("Display");
b5=new Button("Display");
b6=new Button("Enter Coordinate");

t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
t4=new TextField(10);
t5=new TextField(10);
t6=new TextField(10);
t7=new TextField(10);
t8=new TextField(10);
t9=new TextField(10);
t10=new TextField(10);
t11=new TextField(10);
t12=new TextField(10);
t13=new TextField(10);
t14=new TextField(10);

co=new CardLayout();

p1=new Panel();
p1.setLayout(co);

p2=new Panel();
p2.setLayout(new FlowLayout());
p2.add(l1);
p2.add(t1);
p2.add(b1);

p3=new Panel();
p3.setLayout(new GridLayout(3,3));
p3.add(l2);
p3.add(t2);
p3.add(l3);
p3.add(t3);
p3.add(b2);
_________________________________________________________________________
11
Java Technology M.Sc IT Part II
___________________________________________________________________________

p4=new Panel();
p4.setLayout(new GridLayout(3,3));
p4.add(l4);
p4.add(t4);
p4.add(b3);

p5=new Panel();
p5.setLayout(new GridLayout(5,3));
p5.add(l5);
p5.add(t5);
p5.add(l6);
p5.add(t6);
p5.add(l7);
p5.add(t7);
p5.add(l8);
p5.add(t8);
p5.add(b4);

p6=new Panel();
p6.setLayout(new GridLayout(3,2));
p6.add(l9);
p6.add(t9);
p6.add(l10);
p6.add(t10);
p6.add(b5);

p7=new Panel();
p7.setLayout(new GridLayout(4,2));
p7.add(l11);
p7.add(t11);
p7.add(l12);
p7.add(t12);
p7.add(l13);
p7.add(t13);
p7.add(b6);

p1.add(p2,"Circle");
p1.add(p3,"Rectangle");
p1.add(p4,"Square");
p1.add(p5,"Line");
p1.add(p6,"Oval");
p1.add(p7,"Polygon");

add(line);
add(circle);
add(oval);
_________________________________________________________________________
12
Java Technology M.Sc IT Part II
___________________________________________________________________________

add(rectangle);
add(square);
add(polygon);
add(p1);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);

circle.addItemListener(this);
oval.addItemListener(this);
rectangle.addItemListener(this);
square.addItemListener(this);
line.addItemListener(this);
polygon.addItemListener(this);

public void start()


{

public void stop()


{

public void paint(Graphics g)


{
if(ch==1)
g.drawOval(200,175,2*x,2*x);
else if(ch==2)
g.drawRect(200,175,x,y);
else if(ch==3)
g.drawRect(200,175,x,x);
else if(ch==4)
g.drawLine(stx,sty,edx,edy);
else if(ch==5)
g.drawOval(200,175,x,y);
else if(ch==6)
g.drawPolygon(xpolygon5,ypolygon5,no);
}
_________________________________________________________________________
13
Java Technology M.Sc IT Part II
___________________________________________________________________________

public void actionPerformed(ActionEvent ae)


{
if(ae.getSource()==b1)
{
ch=1;
str=t1.getText();
x=Integer.parseInt(str);
repaint();
}
else if(ae.getSource()==b2)
{
ch=2;
str=t2.getText();
x=Integer.parseInt(str);
str=t3.getText();
y=Integer.parseInt(str);
repaint();
}
else if(ae.getSource()==b3)
{
ch=3;
str=t4.getText();
x=Integer.parseInt(str);
repaint();
}
else if(ae.getSource()==b4)
{
ch=4;
str=t5.getText();
stx=Integer.parseInt(str);
str=t6.getText();
edx=Integer.parseInt(str);
str=t7.getText();
sty=Integer.parseInt(str);
str=t8.getText();
edy=Integer.parseInt(str);
repaint();
}
else if(ae.getSource()==b5)
{
ch=5;
str=t9.getText();
x=Integer.parseInt(str);
str=t10.getText();
y=Integer.parseInt(str);
repaint();
}

_________________________________________________________________________
14
Java Technology M.Sc IT Part II
___________________________________________________________________________

else if(ae.getSource()==b6)
{
ch=6;

str=t11.getText();
no=Integer.parseInt(str);
while(flag<5)
{
str=t12.getText();
xpolygon5[flag]=Integer.parseInt(str);
str=t13.getText();
ypolygon5[flag]=Integer.parseInt(str);
t12.setText("");
t13.setText("");
flag++;
}

t11.setEnabled(false);
t12.setEnabled(false);
t13.setEnabled(false);
repaint();
}
}

public void itemStateChanged(ItemEvent ie)


{
if(cbg.getSelectedCheckbox().getLabel().equals("Circle"))
{
repaint();
co.show(p1,"Circle");
}
else if(cbg.getSelectedCheckbox().getLabel().equals("Rectangle"))
{
repaint();
co.show(p1,"Rectangle");
}
else if(cbg.getSelectedCheckbox().getLabel().equals("Square"))
{
repaint();
co.show(p1,"Square");
}
else if(cbg.getSelectedCheckbox().getLabel().equals("Line"))
{
repaint();
co.show(p1,"Line");
}

_________________________________________________________________________
15
Java Technology M.Sc IT Part II
___________________________________________________________________________
else if(cbg.getSelectedCheckbox().getLabel().equals("Oval"))
{
repaint();
co.show(p1,"Oval");
}

else if(cbg.getSelectedCheckbox().getLabel().equals("Polygon"))
{
repaint();
co.show(p1,"Polygon");
}
}
}

_________________________________________________________________________
16
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
17
Java Technology M.Sc IT Part II
___________________________________________________________________________

_________________________________________________________________________
18
Java Technology M.Sc IT Part II
___________________________________________________________________________

_________________________________________________________________________
19
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 03-A

Write a program for Multithreading (using frames).


Problem Statement:
Write a program for bouncing string. Multiple strings should be displayed in different colors.
The algorithm for bouncing each string must be assigned to different threads.

Description:

java.util package:
Contains the collections framework, legacy collection classes, event model, date and
time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a
random-number generator, and a bit array).

java.awt.event package:
Provides interfaces and classes for dealing with different types of events fired by AWT
components. Events are fired by event sources. An event listener registers with an event source
to receive notifications about the events of a particular type. This package defines events and
event listeners, as well as event listener adapters, which are convenience classes to make easier
the process of writing event listeners.

java.awt package:
Provides interfaces and classes for dealing with different types of events fired by AWT
components. Contains all of the classes for creating user interfaces and for painting graphics
and images.

_________________________________________________________________________
20
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.util.*;

class bouncestring extends JFrame implements ActionListener


{

JButton refstart,refstop,refexit;
JPanel refbuttonpanel,refcanvaspanel;
Container c;
drawcanvas refdc;

bouncestring()
{
c=getContentPane();
c.setLayout(new BorderLayout());

refdc=new drawcanvas();

refstart=new JButton("Start");
refstop=new JButton("Stop");
refexit=new JButton("Exit");

refbuttonpanel=new JPanel();
refcanvaspanel=new JPanel();

refbuttonpanel.add(refstart);
refbuttonpanel.add(refstop);
refbuttonpanel.add(refexit);

c.add(refbuttonpanel,BorderLayout.SOUTH);
c.add(refdc);

refstart.addActionListener(this);
refstop.addActionListener(this);
refexit.addActionListener(this);

setSize(200,300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

}
_________________________________________________________________________
21
Java Technology M.Sc IT Part II
___________________________________________________________________________

public void actionPerformed(ActionEvent ae)


{
if(ae.getSource()==refexit)
{
System.exit(0);
}
else if(ae.getSource()==refstart)
{

refdc.move();

}
else if(ae.getSource()==refstop)
{
refdc.halt();
}

public static void main(String args[])


{
bouncestring cd=new bouncestring();

}
}

class drawcanvas extends Canvas implements Runnable


{
int x,y,r,x1,y1,x2,y2,dx,dx1,dx2,dy,dy1,dy2;
Thread first;
Thread second;
Thread third;
Thread refcurthread;
boolean stop;
drawcanvas()
{
x = 10; y = 10; r = 10; //Position and radius of the first ball

x1 = 100; y1 = 100; // Position and radius of the second ball


x2 = 50; y2 = 50; // Position and radius of the third ball

dx = 11; dy = 7;
dx1 = 11; dy1 = 11;
dx2 = 17; dy2 = 10;

}
public void paint(Graphics g)
{
g.setColor(Color.red);
_________________________________________________________________________
22
Java Technology M.Sc IT Part II
___________________________________________________________________________
g.drawString("India", x-r, y-r);

g.setColor(Color.green);
g.drawString("Germany", x1-r, y1-r);

g.setColor(Color.blue);
g.drawString("France", x2-r, y2-r);

}
public void run()
{
while(!stop)
{
refcurthread=Thread.currentThread();

System.out.println(Thread.currentThread());

if(refcurthread.getName().equalsIgnoreCase("First"))
{
if ((x - r + dx < 0) || (x + r + dx > getWidth()))
dx = -dx;

if ((y - r + dy < 0) || (y + r + dy > getHeight()))


dy = -dy;

// Move the first ball.


x += dx; y += dy;
}
elseif(refcurthread.getName().equalsIgnoreCase("Second"))
{
if ((x1 - r + dx1 < 0) || (x1 + r + dx1 > getWidth()))
dx1 = -dx1;

if ((y1 - r + dy1 < 0) || (y1 + r + dy1 > getHeight()))


dy1 = -dy1;

// Move the second ball.


x1 += dx1; y1 += dy1;

}
else if(refcurthread.getName().equalsIgnoreCase("Third"))
{
if ((x2 - r + dx2 < 0) || (x2 + r + dx2 > getWidth()))
dx2 = -dx2;

if ((y2 - r + dy2 < 0) || (y2 + r + dy2 > getHeight()))


dy2 = -dy2;

// Move the third ball.


x2 += dx2; y2 += dy2;
_________________________________________________________________________
23
Java Technology M.Sc IT Part II
___________________________________________________________________________

}
repaint();
try
{
Thread.sleep(60);
}
catch(Exception e)
{
}
}
}
public void move()
{
first=new Thread(this,"First");
second=new Thread(this,"Second");
third=new Thread(this,"Third");

first.start();
second.start();
third.start();

stop=false;
}
public void halt()
{
stop=true;
}
}

_________________________________________________________________________
24
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
25
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 03-B

Problem Statement:
Write a program for bouncing ball. Each ball should be displayed with a different color.

Description:

JFrame:
An extended version of java.awt.Frame that adds support for the JFC/Swing
component architecture. The JFrame class is slightly incompatible with Frame. Like all other
JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content
pane provided by the root pane should, as a rule, contain all the non-menu components
displayed by the JFrame. This is different from the AWT Frame case. Unlike a Frame, a
JFrame has some notion of how to respond when the user attempts to close the window. The
default behavior is to simply hide the JFrame when the user closes the window.

Container:
A generic Abstract Window Toolkit(AWT) container object is a component that can
contain other AWT components.Components added to a container are tracked in a list. The
order of the list will define the components' front-to-back stacking order within the container.
If no index is specified when adding a component to a container, it will be added to the end of
the list .

_________________________________________________________________________
26
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

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

/**
* This JFrame subclass is a simple "paint" application.
**/
public class DrawingPane extends JFrame
{

// The scribble application relies on the ScribblePane component developed


// earlier. This field holds the ScribblePane instance it uses.
BouncingBallPane refBouncingBallPane;

/**
* This constructor creates the GUI for this application.
**/
public DrawingPane()
{
super("Multiple Bouncing Balls - Thread based"); // Call superclass
constructor and set window title

// All content of a JFrame (except for the menubar) goes in the


// Frame's internal "content pane", not in the frame itself.
// The same is true for JDialog and similar top-level containers.
Container contentPane = this.getContentPane();
// Specify a layout manager for the content pane
contentPane.setLayout(new BorderLayout());
// Create the main scribble pane component, give it a border, and
// a background color, and add it to the content pane
refBouncingBallPane = new BouncingBallPane();
refBouncingBallPane.setBorder(new BevelBorder
(BevelBorder.LOWERED));
refBouncingBallPane.setBackground(Color.yellow);
contentPane.add(refBouncingBallPane, BorderLayout.CENTER);
refBouncingBallPane.startApp();
}

public static void main(String[] args)


{
// Set the look-and-feel for the application.
// LookAndFeelPrefs is defined elsewhere in this package.

//LookAndFeelPrefs.setPreferredLookAndFeel(ScribbleApp.class);
_________________________________________________________________________
27
Java Technology M.Sc IT Part II
___________________________________________________________________________
DrawingPane refDrawingPane = new DrawingPane();

// Handle window close requests


refDrawingPane.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0); }
});
// Set the window size and make it visible.
refDrawingPane.setSize(500, 300);
refDrawingPane.setVisible(true);
}

}
class BouncingBallPane extends JComponent implements Runnable
{
int x, y, r; // Position and radius of the circle
int dx, dy; // Trajectory of circle
int x1, y1; // Position and radius of the circle
int dx1, dy1; // Trajectory of circle
int x2, y2; // Position and radius of the circle
int dx2, dy2; // Trajectory of circle

Thread animator1; // The threads that performs the animation


Thread animator2;
Thread animator3;

Thread refCurrentThread;

int ballNumber;
boolean pleaseStop; // A flag to ask the thread to stop

public BouncingBallPane()
{
setPreferredSize(new Dimension(450,200)); // We need a default size

x = 10; y = 10; r = 10; // Position and radius of the first ball


x1 = 100; y1 = 100; // Position and radius of the second ball
x2 = 50; y2 = 50; // Position and radius of the third ball
dx = 11; dy = 7;
dx1 = 11; dy1 = 11;
dx2 = 17; dy2 = 10;

ballNumber = 0;
}

public void paintComponent(Graphics g)


{
/** We override this method to draw ourselves. */

_________________________________________________________________________
28
Java Technology M.Sc IT Part II
___________________________________________________________________________
// Let the superclass do its painting first
super.paintComponent(g);
// Make a copy of the Graphics context so we can modify it
// We cast it at the same time so we can use Java2D graphics
Graphics2D g2 = (Graphics2D) (g.create());

// Our superclass doesn't paint the background, so do this ourselves.


g2.setColor(getBackground());
g2.fillRect(0, 0, getWidth(), getHeight());

g.setColor(Color.red);
g.fillOval(x-r, y-r, r*2, r*2);

g.setColor(Color.green);
g.fillOval(x1-r, y1-r, r*2, r*2);

g.setColor(Color.blue);
g.fillOval(x2-r, y2-r, r*2, r*2);

//g.drawString(refCurrentThread.getName(), getWidth()/2,
getHeight()/2);
}
/**
* This method moves (and bounces) the circle and then requests a redraw.
* The animator thread calls this method periodically.
**/
public void animate()
{
// Bounce if we've hit an edge.
switch(ballNumber)
{
case 1:
if ((x - r + dx < 0) || (x + r + dx > getWidth()))
dx = -dx;

if ((y - r + dy < 0) || (y + r + dy > getHeight()))


dy = -dy;

// Move the first ball.


x += dx; y += dy;
break;

case 2:
if ((x1 - r + dx1 < 0) || (x1 + r + dx1 > getWidth()))
dx1 = -dx1;

if ((y1 - r + dy1 < 0) || (y1 + r + dy1 > getHeight()))


dy1 = -dy1;

_________________________________________________________________________
29
Java Technology M.Sc IT Part II
___________________________________________________________________________
// Move the second ball.
x1 += dx1; y1 += dy1;
break;

case 3:
if ((x2 - r + dx2 < 0) || (x2 + r + dx2 > getWidth()))
dx2 = -dx2;

if ((y2 - r + dy2 < 0) || (y2 + r + dy2 > getHeight()))


dy2 = -dy2;

// Move the third ball.


x2 += dx2; y2 += dy2;
break;

}//end of switch

// Ask the browser to call our paint() method to draw the circle
// at its new position.
repaint();
}

/**
* This method is from the Runnable interface. It is the body of the
* thread that performs the animation. The thread itself is created
* and started in the start() method.
**/

public void run()


{
while(!pleaseStop)
{ // Loop until we're asked to stop
refCurrentThread = Thread.currentThread();
if( refCurrentThread.getName().equals("First Ball"))
ballNumber = 1;
else if(refCurrentThread.getName().equals("Second Ball"))
ballNumber = 2;
else if(refCurrentThread.getName().equals("Third Ball"))
ballNumber = 3;

animate();

try
{
Thread.sleep(30);
} // Wait 'n' milliseconds

catch(InterruptedException e) {} // Ignore interruptions


}
}
_________________________________________________________________________
30
Java Technology M.Sc IT Part II
___________________________________________________________________________

/** Start animating when the browser starts the applet */


public void startApp()
{
animator1 = new Thread(this, "First Ball"); // Create a thread
animator2 = new Thread(this, "Second Ball"); // Create a thread
animator3 = new Thread(this, "Third Ball"); // Create a thread
pleaseStop = false; // Don't ask it to stop now

animator1.start(); // Start the thread.


animator2.start();
animator3.start();

// The thread that called start now returns to its caller.


// Meanwhile, the new animator thread has called the run() method
}

/** Stop animating when the browser stops the applet */


public void stop()
{
// Set the flag that causes the run() method to end
pleaseStop = true;
}

_________________________________________________________________________
31
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
32
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 04

Write a program for Exception Handling.

Problem Statement:
Implement user-defined exception. Create throw and catch user-defined exception and handle
runtime exception.

Description:

InputStreamReader:
It extends from Reader class. An InputStreamReader is a bridge from byte streams to
character streams: It reads bytes and decodes them into characters using a specified charset.
Each invocation of one of an InputStreamReader's read() methods may cause one or more
bytes to be read from the underlying byte-input stream. For top efficiency, consider wrapping
an InputStreamReader within a BufferedReader. For example:
BufferedReader in= new BufferedReader(new InputStreamReader(System.in));

Dimension class:
The Dimension class encapsulates the width and height of a component (in integer
precision) in a single object. The class is associated with certain properties of components.
Several methods defined by the Component class and the LayoutManager interface return a
Dimension object.

_________________________________________________________________________
33
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.util.*;
class demo
{
private int x,y;
void div() throws ArithmeticException
{
if(y==0)
{
throw new ArithmeticException("Divide by zero");
}
int z=x/y;
System.out.println("The division is:"+z);
}
void call(int m,int n)
{
try
{
x=m;y=n;div();
}
catch(ArithmeticException e)
{
System.out.println("Error:"+e);
}
}
}
class excep
{
public static void main(String args[])
{
try
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
demo d=new demo();
d.call(a,b);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Error:Command Line arguments not found");
}
}
}
_________________________________________________________________________
34
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
35
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 05-A
Write a program for File Handling

Problem Statement:

Copy a file to another file.


For e.g. java copyFile from File.txt to File.txt

Description:

FileInputStream:
A FileInputStream obtains input bytes from a file in a file system. What files are
available depends on the host environment.FileInputStream is meant for reading streams of
raw bytes such as image data. For reading streams of characters, consider using FileReader.

FileOutputStream:
A file output stream is an output stream for writing data to a File or to a FileDescriptor.
Whether or not a file is available or may be created depends upon the underlying platform.
Some platforms, in particular, allow a file to be opened for writing by only one
FileOutputStream (or other file-writing object) at a time. In such situations the constructors in
this class will fail if the file involved is already open.
FileOutputStream is meant for writing streams of raw bytes such as image data. For writing
streams of characters, consider using FileWriter.

read():
Reads a byte of data from this input stream. This method blocks if no input is yet
available.

_________________________________________________________________________
36
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

import java.io.*;

class CopyFile5a
{
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
try
{
try{
fin=new FileInputStream(args[0]);
}
catch(FileNotFoundException e){
System.out.println("Input file not found");return;
}
try{
fout=new FileOutputStream(args[1]);
}
catch(FileNotFoundException e){
System.out.println("Output File file not found");return;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndex OutOf Bounds");return;
}
try
{
do
{
i=fin.read();
if(i!=-1)
{
fout.write((char)i);
}
}while(i!=-1);
}catch(IOException e){}
System.out.println("\nFile Copied!\nCopied File name is f2.txt");

fin.close();
fout.close();
}
}

_________________________________________________________________________
37
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

Input File:

So she went into the garden to cut a cabbage-leaf, to make an apple-pie; and at the same time a
great she-bear, coming up the street, pops its head into the
shop. 'What! no soap?' So he died, and she very imprudently married the barber; and there
were present the Picninnies, and the Joblillies, and the Garyalies, and the grand Panjandrum
himself, with the little round button at top, and they all fell to playing the game of catch as
catch can, till the gun powder ran out at the heels of their boots.

Samuel Foote 1720-1777

Output File:

So she went into the garden to cut a cabbage-leaf, to make an apple-pie; and at the same time a
great she-bear, coming up the street, pops its head into the
shop. 'What! no soap?' So he died, and she very imprudently married the barber; and there
were present the Picninnies, and the Joblillies, and the Garyalies, and the grand Panjandrum
himself, with the little round button at top, and they all fell to playing the game of catch as
catch can, till the gun powder ran out at the heels of their boots.

Samuel Foote 1720-1777

_________________________________________________________________________
38
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 05-B

Problem Statement:

Implement Caeser Cipher – Convert the text from an input file to cipher text. The cipher text
shifts all the alphabets by an amount. For e.g. if the amount is 5 then ‘a’ will be ‘f’, ‘b’ will
become ‘g’ and so on.

Description:

FileNotFoundException:
Signals that an attempt to open the file denoted by a specified pathname has failed.This
exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile
constructors when a file with the specified pathname does not exist. It will also be thrown by
these constructors if the file does exist but for some reason is inaccessible, for example when
an attempt is made to open a read-only file for writing.

IOException:
Signals that an I/O exception of some sort has occurred. This class is the general class
of exceptions produced by failed or interrupted I/O operations.

ArrayIndexOutOfBoundsException:
Thrown to indicate that an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.

_________________________________________________________________________
39
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

import java.io.*;
public class Copy
{
int c, count = 0;
public void copyFile(File inputFile, File outputFile);
{
try
{
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
while ((c = in.read()) != -1)
{
++count;
out.write(c);
}
in.close();
out.close();
}
catch(IOException e) {}
}
public void cipherFile(File inputFile)
{
try
{
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter("CaeserCipher.txt");
for(int i = 1; i <= count; i++)
{
c = in.read();
c = c + 5;
out.write(c);
}
in.close();
out.close();
}
catch(IOException e) {}
}
public void plainFile()
{
try
{
FileReader in = new FileReader("CaeserCipher.txt");
FileWriter out = new FileWriter("CaeserPlain.txt");
for(int i = 1; i <= count; i++)
{
_________________________________________________________________________
40
Java Technology M.Sc IT Part II
___________________________________________________________________________
c = in.read();
c = c - 5;
out.write(c);
}
in.close();
out.close();
System.out.println("File Converted to Cipher Text");
}
catch(IOException e) {}
}
public static void main(String[] args) throws IOException
{
Copy refCopy = new Copy();
File inputFile = new File(args[0]); //"farrago.txt");
File outputFile = new File(args[1]); //"outagain.txt");
refCopy.copyFile(inputFile, outputFile);
refCopy.cipherFile(inputFile);
refCopy.plainFile();
}
}

_________________________________________________________________________
41
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

Input File: Src.txt

So she went into the garden to cut a cabbage-leaf, to make an apple-pie; and at the same time a
great she-bear, coming up the street, pops its head into the
shop. 'What! no soap?' So he died, and she very imprudently married the barber; and there
were present the Picninnies, and the Joblillies, and the Garyalies, and the grand Panjandrum
himself, with the little round button at top, and they all fell to playing the game of catch as
catch can, till the gun powder ran out at the heels of their boots.

Samuel Foote 1720-1777

Ouput File:

Xt%xmj%|jsy%nsyt%ymj%lfwijs%yt%hzy%f%hfggflj2qjfk1%yt¤rfpj%fs%fuuqj2unj@%fsi
%fy%ymj%xfrj%ynrj%f%lwjfy¤xmj2gjfw1%htrnsl%zu%ymj%xywjjy1%utux%nyx%mjfi
%nsyt%ymj¤xmtu3%,\mfy&%st%xtfuD,%Xt%mj%inji1%fsi%xmj%{jw~¤nruwzijsyq~
%rfwwnji%ymj%gfwgjw@%fsi%ymjwj%|jwj¤uwjxjsy%ymj%Unhsnssnjx1%fsi%ymj
%Otgqnqqnjx1%fsi%ymj¤Lfw~fqnjx1%fsi%ymj%lwfsi%Ufsofsiwzr%mnrxjqk1%|nym
%ymj¤qnyyqj%wtzsi%gzyyts%fy%ytu1%fsi%ymj~%fqq%kjqq%yt%uqf~nsl¤ymj%lfrj%tk
%hfyhm%fx%hfyhm%hfs1%ynqq%ymj%lzs%ut|ijw%wfs¤tzy%fy%ymj%mjjqx%tk%ymjnw
%gttyx3¤¤Xfrzjq%Kttyj%6<7526<<<¤

_________________________________________________________________________
42
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 06
Problem Statement:

Create jar files using java package

Description:

java.lang package:
Provides classes that are fundamental to the design of the Java programming language.
The most important classes are Object, which is the root of the class hierarchy, and Class,
instances of which represent classes at run time.

Runtime:
Every Java application has a single instance of class Runtime that allows the
application to interface with the environment in which the application is running. The current
runtime can be obtained from the getRuntime method.An application cannot create its own
instance of this class.

JFileChooser:
JFileChooser provides a simple mechanism for the user to choose a file.

_________________________________________________________________________
43
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:
Code for login form

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

public class User_Login


{
static Color color1;
public static void main(String[] argv)
{
final JFrame f = new JFrame("Password");

color1 = new Color(39,58,126);

JLabel label = new JLabel("Enter the password: ");


label.setBounds(50,20,200,20);
label.setForeground(color1);
label.setFont(new Font("Monotype Corsiva", Font.BOLD, 20));

final JPasswordField passwordField = new JPasswordField(10);


passwordField.setBounds(250,20,100,20);
passwordField.setEchoChar('*');

passwordField.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JPasswordField input = (JPasswordField)e.getSource();
char[] password = input.getPassword();
if (isPasswordCorrect(password))
{
new ComboProgram();
f.setVisible(false);
}
else
{
JOptionPane.showMessageDialog(f,"Invalid password. Try
again.","ErrorMessage",JOptionPane.ERROR_MESSAGE);
passwordField.setText("");
}
}
});

f.getContentPane().add(label, BorderLayout.CENTER);
f.getContentPane().add(passwordField, BorderLayout.CENTER);

f.getContentPane().setLayout(null);

_________________________________________________________________________
44
Java Technology M.Sc IT Part II
___________________________________________________________________________
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.setVisible(true);
f.setSize(400,100);
f.setResizable(false);
f.setLocation(300,250);
f.validate();
f.repaint();
}

private static boolean isPasswordCorrect(char[] input)


{
char[] correctPassword = { '1', '2', '3'};
if (input.length != correctPassword.length)
{
return false;
}
for (int i = 0; i < input.length; i ++)
{
if (input[i] != correctPassword[i])
{
return false;
}
}
return true;
}
}

Code for executing the contents fater successful login

import java.awt.FlowLayout;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Color;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

import javax.swing.JLabel;
import javax.swing.JFrame;
_________________________________________________________________________
45
Java Technology M.Sc IT Part II
___________________________________________________________________________
import javax.swing.JComboBox;
import javax.swing.ImageIcon;

class ComboProgram extends JFrame implements ItemListener


{
JFrame frmShow;
JLabel jl;
ImageIcon france, germany, italy, japan;

ComboProgram()
{
frmShow = new JFrame("ComboBox Demo");
setVisible(true);
setLocation(300,250);

// Get content pane


Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());

// Create a combo box and add it to the panel


JComboBox jc = new JComboBox();
jc.addItem("Line");
jc.addItem("Rectangles");
jc.addItem("Circle");
jc.addItem("Ellipse");
jc.addItemListener(this);

addWindowListener (new WindowAdapter()


{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});

contentPane.add(jc);

// Create label
jl = new JLabel(new ImageIcon("france.gif"));
contentPane.add(jl);
setTitle("Draw Objects");
pack();
}

public void itemStateChanged(ItemEvent ie)


{
String s = (String)ie.getItem();
Graphics g = getGraphics();
Color c = new Color(255, 0, 0);
g.setColor(c);
_________________________________________________________________________
46
Java Technology M.Sc IT Part II
___________________________________________________________________________

if(s == "Line")
{
g.drawLine(150,150,400,400);
}
if(s == "Rectangles")
{
g.drawRect(100,100,400,400);
}
if(s == "Circle")
{
g.drawOval(150,150,400,400);
}
if(s == "Ellipse")
{
g.drawOval(150,150,500,400);
}
}

public static void main(String args[])


{
new ComboProgram();
}
}

_________________________________________________________________________
47
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
48
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 07-A
Swing Application

Problem Statement:

Write swings program for creating a single frame and display a text and change its font and
text color

Description:

JLabel:
A display area for a short text string or an image, or both. A label does not react to
input events. As a result, it cannot get the keyboard focus. A label can, however, display a
keyboard alternative as a convenience for a nearby component that has a keyboard alternative
but can't display it.A JLabel object can display either text, an image, or both. You can specify
where in the label's display area the label's contents are aligned by setting the vertical and
horizontal alignment. By default, labels are vertically centered in their display area. Text-only
labels are leading edge aligned, by default; image-only labels are horizontally centered, by
default.

JList:
A component that allows the user to select one or more objects from a list. A separate
model, ListModel, represents the contents of the list. It's easy to display an array or vector of
objects, using a JList constructor that builds a ListModel instance for you.

Font:
The Font class represents fonts, which are used to render text in a visible way. A font
provides the information needed to map sequences of characters to sequences of glyphs and to
render sequences of glyphs on Graphics and Component objects.

_________________________________________________________________________
49
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

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

public class FontSize_Color extends JFrame implements ActionListener


{
JLabel lblStr;
JPanel p1,p2,p3;
JList jlName,jlColor;
JButton Change,Exit;
public FontSize_Color()
{
setTitle("Select the Font Type anf Font COlor");
Container refCon=getContentPane();
refCon.setLayout(new FlowLayout();

lblStr=new JLabel("India is my Country");


String str1[] = {"Serif","SansSerif","Monospaced"};
jlName=new JList(str1);

String str2[] = {"Black","Blue","Cyan","Dark Gray","Green"};


jlColor=new JList(str2);

p1=new JPanel();
p1.setLayout(new FlowLayout());

p2=new JPanel();
p2.setLayout(new FlowLayout());

p3=new JPanel();
p3.setLayout(new FlowLayout());
p1.add(lblStr);
p2.add(jlName);
p2.add(jlColor);
//p2.setBorder(BorderFactory.createTitledBorder(BorderFactory.
createEtchedBorder(),"Select"));
Change=new JButton("Change");
p3.add(Change);
Change.addActionListener(this);

Exit=new JButton("Exit");
p3.add(Exit);
Exit.addActionListener(this);
refCon.add(p1);
refCon.add(p2);
_________________________________________________________________________
50
Java Technology M.Sc IT Part II
___________________________________________________________________________
refCon.add(p3);

setVisible(true);
pack();

public void actionPerformed(ActionEvent ae)


{
if(ae.getActionCommand()=="Change")
{
if(jlName.getSelectedIndex()==0 && jlColor.getSelectedIndex() ==0)
{
Font font=new Font("Serif",Font.BOLD|Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.black);
}

if(jlName.getSelectedIndex()==0 && jlColor.getSelectedIndex()==1)


{
Font font=new Font("Serif",Font.BOLD|Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.blue);
}

if(jlName.getSelectedIndex()==0 && jlColor.getSelectedIndex()==2)


{
Font font=new Font("Serif",Font.BOLD|Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.cyan);
}

if(jlName.getSelectedIndex()==0 && jlColor.getSelectedIndex()==3)


{
Font font=new Font("Serif",Font.BOLD|Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.darkGray);
}

if(jlName.getSelectedIndex()==0 && jlColor.getSelectedIndex()==4)


{
Font font=new Font("Serif",Font.BOLD|Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.green);
}

if(jlName.getSelectedIndex()==1 && jlColor.getSelectedIndex()==0)


{
_________________________________________________________________________
51
Java Technology M.Sc IT Part II
___________________________________________________________________________
Font font=new Font("SansSerif",Font.BOLD|Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.black);
}

if(jlName.getSelectedIndex()==1 && jlColor.getSelectedIndex()==1)


{
Font font=new Font("SansSerif",Font.BOLD|Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.blue);
}

if(jlName.getSelectedIndex()==1 && jlColor.getSelectedIndex()==2)


{
Font font=new Font("SansSerif",Font.BOLD|Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.cyan);
}

if(jlName.getSelectedIndex()==1 && jlColor.getSelectedIndex()==3)


{
Font font=new Font("SansSerif",Font.BOLD|Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.darkGray);
}

if(jlName.getSelectedIndex()==1 && jlColor.getSelectedIndex()==4)


{
Font font=new Font("SansSerif",Font.BOLD|Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.green);
}

if(jlName.getSelectedIndex()==2 && jlColor.getSelectedIndex()==0)


{
Font font=new Font("Monospaced",Font.BOLD|
Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.black);
}

if(jlName.getSelectedIndex()==2 && jlColor.getSelectedIndex()==1)


{
Font font=new Font("Monospaced",Font.BOLD|
Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.blue);
}

_________________________________________________________________________
52
Java Technology M.Sc IT Part II
___________________________________________________________________________
if(jlName.getSelectedIndex()==2 && jlColor.getSelectedIndex()==2)
{
Font font=new Font("Monospaced",Font.BOLD|Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.cyan);
}

if(jlName.getSelectedIndex()==2 && jlColor.getSelectedIndex()==3)


{
Font font=new Font("Monospaced",Font.BOLD|
Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.darkGray);
}

if(jlName.getSelectedIndex()==2 && jlColor.getSelectedIndex()==4)


{
Font font=new Font("Monospaced",Font.BOLD|
Font.ITALIC,15);
lblStr.setFont(font);
lblStr.setForeground(Color.green);
}
}
else if(ae.getActionCommand()=="Exit")
System.exit(0);
}
public static void main(String args[])
{
FontSize_Color refFont =new FontSize_Color();

}
}

_________________________________________________________________________
53
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
54
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 07-B

Problem Statement:

Write a swing program for displaying images on a frame

Description:

JButton:
An implementation of a "push" button.

JPanel:
JPanel is a generic lightweight container.

ImageIcon:
An implementation of the Icon interface that paints Icons from Images. Images that are
created from a URL, filename or byte array are preloaded using MediaTracker to monitor the
loaded state of the image.

getContentPane():
A Container that manages the contentPane and in some cases a menu bar. The
layeredPane can be used by descendants that want to add a child to the RootPaneContainer that
isn't layout managed. For example an internal dialog or a drag and drop effect component.

_________________________________________________________________________
55
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

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

public class ImageViewer extends JFrame implements ActionListener


{
ImageIcon ii1,ii2,ii3;
JList jl1;
Button show;
JLabel lblImage1,refLabel2;

ImageViewer()
{
String str[]={"Geen baby","White baby","Blue baby"};
jl1=new JList(str);
ii1=new ImageIcon("1.jpg");
ii2=new ImageIcon("2.jpg");
ii3=new ImageIcon("3.jpg");
lblImage1=new JLabel();
refLabel2 = new JLabel("Select to view Imagies of Babies", JLabel.LEFT);
show=new JButton("Show");

}
public void display()
{
setTitle("Image Viewer");
Container refCon=getContentPane();
refCon.setLayout(new FlowLayout());

refCon.add(refLabel2);
refCon.add(jl1);
refCon.add(show);

refCon.add(lblImage1);
show.addActionListener(this);
setVisible(true);
pack();

public void actionPerformed(ActionEvent ae)


{
if(ae.getActionCommand()=="Show")
_________________________________________________________________________
56
Java Technology M.Sc IT Part II
___________________________________________________________________________
{
if(jl1.getSelectedIndex()==0)
lblImage1.setIcon(ii1);
if(jl1.getSelectedIndex()==1)
lblImage1.setIcon(ii2);
if(jl1.getSelectedIndex()==2)
lblImage1.setIcon(ii3);
}
}
public static void main(String args[])
{
ImageViewer iv=new ImageViewer();
iv.display();
}
}

_________________________________________________________________________
57
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
58
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 07-C

Problem Statement:

Create a data entry form to store student information and display it on other frame

Description:

JTabbedPane:
A component that lets the user switch between a group of components by clicking
on a tab with a given title and/or icon. Tabs/components are added to a TabbedPane object by
using the addTab and insertTab methods. A tab is represented by an index corresponding to the
position it was added in, where the first tab has an index equal to 0 and the last tab has an index
equal to the tab count minus 1.

JTextField:
JTextField is a lightweight component that allows the editing of a single line of
text. TextField is intended to be source-compatible with java.awt.TextField where it is
reasonable to do so. This component has capabilities not found in the java.awt.TextField class.
The superclass should be consulted for additional capabilities.JTextField has a method to
establish the string used as the command string for the action event that gets fired. The
java.awt.TextField used the text of the field as the command string for the ActionEvent.
JTextField will use the command string set with the setActionCommand method if not null,
otherwise it will use the text of the field as a compatibility with java.awt.TextField.

JRadioButton:
An implementation of a radio button -- an item that can be selected or deselected,
and which displays its state to the user. Used with a ButtonGroup object to create a group of
buttons in which only one button at a time can be selected. (Create a ButtonGroup object and
use its add method to include the JRadioButton objects in the group.)

_________________________________________________________________________
59
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java .sql.*;
import java.util.Vector;

public class ViewRecords extends JFrame


{
JTable refTable;
JLabel lblTitle;
Vector refCol, refData, refRow;
public ViewRecords()
{

lblTitle=new JLabel("Student Records");

setTitle("Student Records");
Container refCon=getContentPane();
refCon.setLayout(new BorderLayout());

refCon.add(lblTitle,BorderLayout.NORTH);

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c= DriverManager.getConnection
("jdbc:odbc:StudInfo");
Statement s=c.createStatement();
String strQuery="select * from StudentInfo";
ResultSet rs=s.executeQuery(strQuery);

ResultSetMetaData rsmd=rs.getMetaData();
refCol = new Vector();
refData = new Vector();

for(int i=1 ; i<=rsmd.getColumnCount() ; i++)


{
refCol.add(rsmd.getColumnName(i));
}

_________________________________________________________________________
60
Java Technology M.Sc IT Part II
___________________________________________________________________________
while(rs.next())
{
refRow=new Vector();
for(int i=1 ; i<=rsmd.getColumnCount() ; i++)
{
refRow.add(rs.getString(i));
}

refData.add(refRow);

rs.close();
s.close();
c.close();
}
catch(Exception e)
{
System.out.println("Exception Occured .................." +e);
}

refTable=new JTable(refData,refCol);
System.out.println(refCol);
refCon.add(refTable,BorderLayout.CENTER);
setVisible(true);
pack();

public static void main(String args[])


{
ViewRecords refView=new ViewRecords();

}
}

_________________________________________________________________________
61
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
62
Java Technology M.Sc IT Part II
___________________________________________________________________________

_________________________________________________________________________
63
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 08

Problem Statement:

Design an editor containing following options:


a. file menu
b. file menu contains open, close and exit options
c. edit menu
d. edit menu contains bold, italic, underline and color options

Description:

GraphicsEnviroment:
The GraphicsEnvironment class describes the collection of GraphicsDevice
objects and Font objects available to a Java(tm) application on a particular platform. The
resources in this GraphicsEnvironment might be local or on a remote machine. GraphicsDevice
objects can be screens, printers or image buffers and are the destination of Graphics2D
drawing methods. Each GraphicsDevice has a number of GraphicsConfiguration objects
associated with it. These objects specify the different configurations in which the
GraphicsDevice can be used.

javax.swing.text.StyledEditorKit:
This is the set of things needed by a text component to be a reasonably
functioning editor for some type of text document. This implementation provides a default
implementation which treats text as styled text and provides a minimal set of actions for
editing styled text.

_________________________________________________________________________
64
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.KeyEvent;
import java.io.File.*;
import java.io.*;
import java.util.*;
import javax.swing.text.StyledEditorKit.*;
import javax.swing.event.*;
import javax.swing.undo.*;

public class Editor extends JFrame


{
JTextPane text=new JTextPane();
JScrollPane Scroller=new JScrollPane(text);
JToolBar toolbar=new JToolBar();
JToggleButton Toggle_Bold,Toggle_Italic,Toggle_Underline;
JButton Button_New,Button_Open,Button_Color;
JMenuBar menuBar=new JMenuBar();
JMenu File=new JMenu("File");
JMenu Edit=new JMenu("Edit");
//JMenu Format=new JMenu("Format");
JMenuItem File_Open,File_Close,File_Exit;
JMenuItem Format_FontColor;
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
JFileChooser fc;
String Title=" EDITOR ";
public boolean opened=false;
//FileInputStream fInput;
//Document doc1;
public Editor()
{
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(800,575);
setLocation((screensize.width / 2) - (getSize().width / 2),(screensize.height / 2) -
(getSize().height / 2));
this.setTitle(Title);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(Scroller, BorderLayout.CENTER);
this.getContentPane().add(toolbar, BorderLayout.NORTH);
Button_Open=new JButton("");
Button_Open.setOpaque(false);
toolbar.add(Button_Open);
_________________________________________________________________________
65
Java Technology M.Sc IT Part II
___________________________________________________________________________

toolbar.addSeparator();
Toggle_Bold=new JToggleButton(new StyledEditorKit.BoldAction());
Toggle_Bold.setText("Bold");
//Toggle_Bold.setIcon(new ImageIcon("icons/bold.gif"));
toolbar.add(Toggle_Bold);
Toggle_Italic=new JToggleButton(new StyledEditorKit.ItalicAction());
Toggle_Italic.setText("Italic");
//Toggle_Italic.setIcon(new ImageIcon("icons/italic.gif"));
toolbar.add(Toggle_Italic);

Toggle_Underline=new JToggleButton(new
StyledEditorKit.UnderlineAction());
Toggle_Underline.setText("Underline");
//Toggle_Underline.setIcon(new ImageIcon("icons/underline.gif"));
toolbar.add(Toggle_Underline);

toolbar.addSeparator();

Button_Color=new JButton("Font Color");


Button_Color.setBackground(Color.BLACK);
toolbar.add(Button_Color);
toolbar.addSeparator();
toolbar.setFloatable(false); // YOU CAN'T MOVE THIS TOOLBAR OVER
THE FRAME

File.setMnemonic('F');
Edit.setMnemonic(KeyEvent.VK_E);
menuBar.add(File);
menuBar.add(Edit);

File_Open=new JMenuItem("Open");
File_Open.setMnemonic(KeyEvent.VK_O);
File.add(File_Open);
File_Close=new JMenuItem("Close",new ImageIcon("icons/close.gif"));
File_Close.setMnemonic(KeyEvent.VK_C);
File.add(File_Close);
File.addSeparator();

File_Exit=new JMenuItem("Exit");
File_Exit.setMnemonic(KeyEvent.VK_X);
File.add(File_Exit);

Format_FontColor=new JMenuItem("Font color");


Format_FontColor.setMnemonic(KeyEvent.VK_C);
Edit.add(Format_FontColor);

this.setJMenuBar(menuBar); // SETTING UP THE MENU BAR


_________________________________________________________________________
66
Java Technology M.Sc IT Part II
___________________________________________________________________________
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

//OPEN FILE
File_Open.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Open();
}
});

//ACTION FOR CLOSING FILE


File_Close.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Close();
Editor.this.setTitle(Title);
opened=false;

}
});

// ACTION FOR CLOSING APPLICATION


File_Exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,ActionEvent.ALT_
MASK));
File_Exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Exit();
}
});

//FONT COLOR
Format_FontColor.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
FontColor();
}
});

// ACTION FOR OPEN FILES


Button_Open.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Open();
}
_________________________________________________________________________
67
Java Technology M.Sc IT Part II
___________________________________________________________________________
});

// ACTION FOR BOLD TEXT


Toggle_Bold.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
text.requestFocus();
}
});

// ACTION FOR ITALIC TEXT


Toggle_Italic.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
text.requestFocus();
}
});

// ACTION FOR UNDERLINE ACTION


Toggle_Underline.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
text.requestFocus();
}
});

// ACTION FOR SETTING TEXT COLOR


Button_Color.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
FontColor();
}
});

//ADD CARET LISTENER TO THE TEXTPANE


text.addCaretListener(new CaretListener()
{
public void caretUpdate(CaretEvent e)
{
StyledDocument doc=text.getStyledDocument();
AttributeSet a=doc.getCharacterElement(e.getDot()-
1).getAttributes();

boolean bold = StyleConstants.isBold(a);


if (bold != Toggle_Bold.isSelected())
Toggle_Bold.setSelected(bold);
_________________________________________________________________________
68
Java Technology M.Sc IT Part II
___________________________________________________________________________

boolean italic = StyleConstants.isItalic(a);


if (italic != Toggle_Italic.isSelected())
Toggle_Italic.setSelected(italic);

boolean underline = StyleConstants.isUnderline(a);


if (underline != Toggle_Underline.isSelected())
Toggle_Underline.setSelected(underline);

Color color=StyleConstants.getForeground(a);
if(color!=Button_Color.getBackground())
Button_Color.setBackground(color);

}
});

//ACTION FOR CLOSING APPLICATION


addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
Exit();
}
});

} ///// END OF: public Editor ///////

// FUNCTION FOR OPEN DOCUMENT ///////////////////////////


private void Open()
{

JFileChooser fd = new JFileChooser();


try{
fd.showOpenDialog(this);
BufferedReader br = new BufferedReader(new InputStreamReader(new
FileInputStream(fd.getSelectedFile())));
String str;

while((str=br.readLine())!=null)
text.getDocument().insertString(text.getCaretPosition(), str+"\n", null);

}catch(Exception ex)
{}
SetEnable_JTextPane();
}

////////////// FUNCTUIN FOR CLOSE WINDOW ////////////////////////////////


private void Exit()
_________________________________________________________________________
69
Java Technology M.Sc IT Part II
___________________________________________________________________________
{
if(opened)
{
int confirm = JOptionPane.showConfirmDialog(null,
"Would you like to save?",
"Exit Application",
JOptionPane.YES_NO_CANCEL_OPTION);

if( confirm == JOptionPane.YES_OPTION )


{
//Save();
dispose();
System.exit(0);
}
else if( confirm == JOptionPane.CANCEL_OPTION )
{
return;
}
else
{
dispose();
System.exit(0);
}
}
else
{
System.exit(0);
}
}

////////////////// FUNCTION FOR CLOSING //////////////////////


private void Close()
{

int confirm = JOptionPane.showConfirmDialog(null,


"Would you like to save?",
"Exit Application",
JOptionPane.YES_NO_CANCEL_OPTION);

if(confirm == JOptionPane.YES_OPTION)
{
//Save();
text.selectAll();
try
{

text.getDocument().remove(text.getSelectionStart(),text.getSelectionEnd());
}
catch(Exception ex)
{}
_________________________________________________________________________
70
Java Technology M.Sc IT Part II
___________________________________________________________________________
text.setBackground(Color.gray);
text.setEnabled(false);
}
else if(confirm == JOptionPane.CANCEL_OPTION)
{
return;
}
else
{
text.selectAll();
try
{

text.getDocument().remove(text.getSelectionStart(),text.getSelectionEnd());
}
catch(Exception ex)
{}
text.setBackground(Color.gray);
text.setEnabled(false);
}

//// FUNCTION FOR SETTING UP ENABLE JTextPane text ///////


private void SetEnable_JTextPane()
{
text.setBackground(Color.white);
text.setEditable(true);
text.requestFocus(true);
}

//////// FUNCTION FOR SETTING UP DISABLE JTextPane text ////////////


private void SetDisable_JTextPane()
{
text.setBackground(Color.gray);
text.setEditable(false);
}

///////// FUNCTION FOR ENABLING SOME TOOLBAR AND MENU


ITEMS //////////////
/* private void items_enable()
{
Toggle_Bold.setEnabled(true);
Toggle_Italic.setEnabled(true);
Toggle_Underline.setEnabled(true);
Button_Color.setEnabled(true);
Format_FontColor.setEnabled(true);
File_Close.setEnabled(true);

_________________________________________________________________________
71
Java Technology M.Sc IT Part II
___________________________________________________________________________
}*/

//////// FUNCTION FOR DISABLING SOME TOOLBAR AND MENU


ITEMS //////////////
/*private void items_disable()
{

Toggle_Bold.setEnabled(false);
Toggle_Italic.setEnabled(false);
Toggle_Underline.setEnabled(false);
Button_Color.setEnabled(false);
Format_FontColor.setEnabled(false);
File_Close.setEnabled(false);
}
*/
/////////// FUNCTION FOR FONT COLOR ///////////
private void FontColor()
{
Color color = JColorChooser.showDialog(
Editor.this,
"Choose Text Color",
Button_Color.getBackground());

if(color!=null)
{
Button_Color.setBackground(color);
Color fontColor=Button_Color.getBackground();
MutableAttributeSet attr=new SimpleAttributeSet();
StyleConstants.setForeground(attr,fontColor);
text.setCharacterAttributes(attr,false);
}
text.requestFocus();
}

public Document getDocument() { return text.getDocument(); }


public JTextPane getTextPane() {return text;}

//////////////// MAIN FUNCTION ///////////////////////


public static void main(String args[])
{

String look="com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
try
{
UIManager.setLookAndFeel(look);
}
catch (Exception exc)
{
System.err.println("Error loading L&F: " + exc);
_________________________________________________________________________
72
Java Technology M.Sc IT Part II
___________________________________________________________________________
}
Editor mainWindow = new Editor();
mainWindow.setVisible(true);
}
}

_________________________________________________________________________
73
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
74
Java Technology M.Sc IT Part II
___________________________________________________________________________

_________________________________________________________________________
75
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 09-A
Write a JDBC (Java Database Connectivity) application using frames

Problem Statement:

Design a form to retrieve account information from bank database

Description:

java.sql package:
Provides the API for accessing and processing data stored in a data source (usually a
relational database) using the JavaTM programming language.

JTable:
The JTable is used to display and edit regular two-dimensional tables of cells. The
JTable has many facilities that make it possible to customize its rendering and editing but
provides defaults for these features so that simple tables can be set up easily.

Connection:
A connection (session) with a specific database. SQL statements are executed and
results are returned within the context of a connection.A Connection object's database is able to
provide information describing its tables, its supported SQL grammar, its stored procedures,
the capabilities of this connection, and so on. This information is obtained with the
getMetaData method.

_________________________________________________________________________
76
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

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

class bank extends JFrame


{

JTable reftable;

String col[],rows[][];

int n;

void UI()
{

reftable=new JTable(rows,col);
Container c=getContentPane();
c.add(reftable);
setTitle("Bank Database");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}

void get_data()
{
try
{

n=0;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con=DriverManager.getConnection("jdbc:odbc:Bank");

Statement s= con.createStatement (ResultSet.TYPE_SCROLL _


INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

ResultSet rs=s.executeQuery("Select * from BankTable");

ResultSetMetaData rsmd =rs.getMetaData();

int columns=rsmd.getColumnCount();
col=new String[columns];

_________________________________________________________________________
77
Java Technology M.Sc IT Part II
___________________________________________________________________________

for(int i=1;i<=columns;i++)
{
col[i-1]=rsmd.getColumnName(i);
System.out.println(rsmd.getColumnName(i));
}

while(rs.next())
n++;

rs.beforeFirst();

rows=new String[n][5];

int x=0;
while(rs.next())
{
for(int i=1,y=0;i<=rsmd.getColumnCount();i++,y++)
{
rows[x][y]=rs.getString(i);
}
x++;
}

System.out.println(n);

System.out.println(rsmd.getColumnCount());
new bank();
}
catch(Exception e)
{
}
}

public static void main(String args[])


{
bank refbank=new bank();
refbank.get_data();
refbank.UI();
}
}

_________________________________________________________________________
78
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
79
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 09-B

Problem Statement:

Design a form to store student information along with image in a database

Description:

Integer.parseInt():
Parses the string argument as a signed decimal integer. The characters in the string
must all be decimal digits, except that the first character may be an ASCII minus sign '-'
('\u002D') to indicate a negative value. The resulting integer value is returned.

File:
An abstract representation of file and directory pathnames.User interfaces and
operating systems use system-dependent pathname strings to name files and directories. This
class presents an abstract, system-independent view of hierarchical pathnames.

PreparedStatement:
An object that represents a precompiled SQL statement.A SQL statement is
precompiled and stored in a PreparedStatement object. This object can then be used to
efficiently execute this statement multiple times.

_________________________________________________________________________
80
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

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

class getImg extends JFrame implements ActionListener


{
JLabel reflabelroll,reflabelname,reflabelcourse,reflabelpic,reflabelimage;
JTextField reftextroll,reftextname,reftextcourse;
JButton refok,refretrieve,refexit;
JPanel reftext,refbutton;
Connection con;

getImg()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:ImageDSN","scott","tiger");
}
catch(Exception e)
{
}
Container c=getContentPane();
c.setLayout(new BorderLayout());

reflabelroll=new JLabel("Roll No.");


reflabelname=new JLabel("Name");

reflabelcourse=new JLabel("Course");
reflabelpic=new JLabel("Image");
reflabelimage=new JLabel();

reftextroll=new JTextField();
reftextname=new JTextField();

reftextcourse=new JTextField();

refok=new JButton("OK");
refretrieve=new JButton("Retrieve");
refexit=new JButton("Exit");

reftext=new JPanel(new GridLayout(6,2));

_________________________________________________________________________
81
Java Technology M.Sc IT Part II
___________________________________________________________________________
refbutton=new JPanel();

reftext.add(reflabelroll);
reftext.add(reftextroll);

reftext.add(reflabelname);
reftext.add(reftextname);

reftext.add(reflabelcourse);
reftext.add(reftextcourse);

reftext.add(reflabelpic);

reftext.add(reflabelimage);

refbutton.add(refok);
refbutton.add(refretrieve);
refbutton.add(refexit);

c.add(reftext,BorderLayout.NORTH);
c.add(refbutton,BorderLayout.SOUTH);

refok.addActionListener(this);
refretrieve.addActionListener(this);
refexit.addActionListener(this);

setTitle("Student Application");
//setSize(300,200);
//setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}

public void actionPerformed(ActionEvent ae)


{
if(ae.getSource()==refexit)
{
System.exit(0);
}
else if(ae.getSource()==refok)
{
insertdata();
}
else if(ae.getSource()==refretrieve)
{
retrievedata();
_________________________________________________________________________
82
Java Technology M.Sc IT Part II
___________________________________________________________________________
}
}

void insertdata()
{
try
{
int roll=Integer.parseInt(reftextroll.getText());
String name=reftextname.getText();
String course=reftextcourse.getText();

File reffile=new File("D:\\Hemali\\Practical\\Java\\avtaar.jpg");


FileInputStream reffis=new FileInputStream(reffile);

PreparedStatement ps=con.prepareStatement("insert into imageTable


values(?,?,?,?)");

ps.setInt(1,roll);
ps.setString(2,name);

ps.setString(3,course);
ps.setBinaryStream(4,reffis,(int)reffile.length());

ps.executeUpdate();

JOptionPane.showMessageDialog(null,"Data
Inserted","Information",JOptionPane.INFORMATION_MESSAGE);

reftextroll.setText("");
reftextname.setText("");
reftextcourse.setText("");

}
catch(Exception e)
{
System.out.println(e);
}
}

void retrievedata()
{
try
{
byte imgByte[]=new byte[2048];

Statement s=con.createStatement();
String refQuery="select * from imageTable where RollNo=2";

_________________________________________________________________________
83
Java Technology M.Sc IT Part II
___________________________________________________________________________

ResultSet rs=s.executeQuery(refQuery);
System.out.println("conn made");

while(rs.next())
{

reftextroll.setText(rs.getString("rollno"));

reftextname.setText(rs.getString("Name"));
reftextcourse.setText(rs.getString("Course"));
imgByte=rs.getBytes("Image");
}
ImageIcon ai=new ImageIcon(imgByte);

reflabelimage.setIcon(ai);
}
catch(Exception e)
{
}

public static void main(String args[])


{
new getImg();
}
}

Output:
_________________________________________________________________________
84
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 10
_________________________________________________________________________
85
Java Technology M.Sc IT Part II
___________________________________________________________________________

Problem Statement:

Create a simple Java Server Page (JSP) for web application

Description:

DriverManager:
The basic service for managing a set of JDBC drivers. As part of its
initialization, the DriverManager class will attempt to load the driver classes referenced in the
"jdbc.drivers" system property. This allows a user to customize the JDBC Drivers used by their
applications.

Statement:
The object used for executing a static SQL statement and returning the results it
produces.By default, only one ResultSet object per Statement object can be open at the same
time. Therefore, if the reading of one ResultSet object is interleaved with the reading of
another, each must have been generated by different Statement objects. All execution methods
in the Statement interface implicitly close a statment's current ResultSet object if an open one
exists.

ResultSet:
A table of data representing a database result set, which is usually generated by
executing a statement that queries the database.A ResultSet object maintains a cursor pointing
to its current row of data. Initially the cursor is positioned before the first row. The next
method moves the cursor to the next row, and because it returns false when there are no more
rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

Source Code:

_________________________________________________________________________
86
Java Technology M.Sc IT Part II
___________________________________________________________________________
<!-- Create a simple java server page (JSP) for web application -->
<%@page import="java.sql.*"%>
<%!
String firstname_str, middlename_str, lastname_str, class_str, age_str, rollno_str;
Connection c;
Statement s;
ResultSet rs;
%>
<head>
<title>Database Connection</title>
</head>
<body>
<p align="center"><b><font size="5">Student Database</font></b></p>
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse"
bordercolor="#111111" width="100%" id="AutoNumber1">
<tr>
<td width="16%" align="center"><b>First Name</b></td>
<td width="16%" align="center"><b>Middle Name</b></td>
<td width="17%" align="center"><b>Last Name</b></td>
<td width="17%" align="center"><b>Class</b></td>
<td width="17%" align="center"><b>Age</b></td>
<td width="17%" align="center"><b>Roll No.</b></td>
</tr>
<%
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c = DriverManager.getConnection("jdbc:odbc:Students");
s = c.createStatement();
rs = s.executeQuery("Select * from StudentTable order by FirstName");
while(rs.next())
{
firstname_str = rs.getString(1);
middlename_str = rs.getString(2);
lastname_str = rs.getString(3);
class_str = rs.getString(4);
age_str = rs.getString(5);
rollno_str = rs.getString(6);
%>
<tr>
<td width="16%" align="center"><%=firstname_str%></td>
<td width="16%" align="center"><%=middlename_str%></td>
<td width="17%" align="center"><%=lastname_str%></td>
<td width="17%" align="center"><%=class_str%></td>
<td width="17%" align="center"><%=age_str%></td>
<td width="17%" align="center"><%=rollno_str%></td>
</tr>
<%
}

_________________________________________________________________________
87
Java Technology M.Sc IT Part II
___________________________________________________________________________
c.close();
}
catch(Exception e)
{}
%>
</table>
</body>

</html>

Output:
_________________________________________________________________________
88
Java Technology M.Sc IT Part II
___________________________________________________________________________

_________________________________________________________________________
89
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 11

Problem Statement:

Design a login form to implement servlets

Description:

javax.servlet package:
The javax.servlet package contains a number of classes and interfaces that describe and
define the contracts between a servlet class and the runtime environment provided for an
instance of such a class by a conforming servlet container.

javax.servlet.http package:
The javax.servlet.http package contains a number of classes and interfaces that describe
and define the contracts between a servlet class running under the HTTP protocol and the
runtime environment provided for an instance of such a class by a conforming servlet
container.

service(ServletRequest req,ServletResponse res):


Dispatches client requests to the protected service method. There's no need to override
this method.

_________________________________________________________________________
90
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

login.html

HTML code:

<html>

<form method="post" action="http://localhost:8888/servlet/LoginForm"/>


<br>
<center> UserID : <input type="text" name="Name" value="" /input>
<br><br>
Password : <input type="password" name="Password" value="" /input>
<br><br>&nbsp
<input type="Submit" name="Submit" value="Submit" /input> </center>
</form>

</html>
Java code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class LoginForm extends HttpServlet


{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
String a,b,c,d,e,f;
int i;
Connection con;
try
{
res.setContentType("text/html");

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:TwoServletsDeptDatabase");
// String Query="insert into login Values(?,?,?)";
Statement st=con.createStatement();
PreparedStatement ps;
PrintWriter out=res.getWriter();
// ps=con.prepareStatement(Query);
a=(String)req.getParameter("Name");
b=(String)req.getParameter("Password");

if (a.equals("admin") && b.equals("admin123"))


{
_________________________________________________________________________
91
Java Technology M.Sc IT Part II
___________________________________________________________________________
out.println("<b> <center>LOGIN SUCCESSFULL</center>
</b><br> <br>");
ResultSet rs=st.executeQuery("select * from Dept");
ResultSetMetaData md=rs.getMetaData();
int num=md.getColumnCount();
out.println("<html><body><table border=1 align=center><tr>");
for(i=1;i<=num;i++)
{
out.print("<th>"+md.getColumnName(i)+"</th>");
}
out.println("</tr>");
while(rs.next())
{
d=rs.getString(1);
e=rs.getString(2);
f=rs.getString(3);
out.println("<tr><td>");
out.println(d);
out.println("</td><td>");
out.println(e);
out.println("</td><td>");
out.println(f);
out.println("</td></tr>");

}
out.println("</table>");
con.commit();

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

else
{
out.println("<br> <br><b> <center>LOGIN
UNSUCCESSFULL</center> </b><br> <br>");
out.println("<center><a href =
http://localhost:8888/loginform.html> <b>Try Again</b> </a></center>");

}
con.close();
}
catch (Exception ae)
{
System.out.println(ae.getMessage());
}

}
}

_________________________________________________________________________
92
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
93
Java Technology M.Sc IT Part II
___________________________________________________________________________

_________________________________________________________________________
94
Java Technology M.Sc IT Part II
___________________________________________________________________________

Practical 12
Problem Statement:
Write a program to implement a Remote Procedure Call

Description:

java.rmi.Remote:
The Remote interface serves to identify interfaces whose methods may be invoked from
a non-local virtual machine. Any object that is a remote object must directly or indirectly
implement this interface. Only those methods specified in a "remote interface", an interface
that extends java.rmi.Remote are available remotely.

java.rmi package:
Provides the Remote Method Invocation package.

UnicastRemoteObject:
Used for exporting a remote object with JRMP and obtaining a stub that communicates
to the remote object.

Naming.rebind (String name,Remote obj):


Rebinds the specified name to a new remote object. Any existing binding for the name
is replaced.

_________________________________________________________________________
95
Java Technology M.Sc IT Part II
___________________________________________________________________________

Source Code:

processinterface.java

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface processinterface extends Remote


{
public int fact(int n) throws RemoteException;
public int rev(int n) throws RemoteException;
public int sum(int n) throws RemoteException;
}

processimplement.java

import java.rmi.*;
import java.rmi.server.*;

public class processimplement extends UnicastRemoteObject implements processinterface


{
processimplement() throws RemoteException{}
public int fact(int n) throws RemoteException
{
int fact=1;
for(;n>0;n--)
{
fact=fact*n;
}
return (fact);
}
public int rev(int n) throws RemoteException
{
int rev=0;
for(;n>0;)
{
rev=(rev*10)+(n%10);n=n/10;
}
return (rev);
}
public int sum(int n) throws RemoteException
{
int sum=0;
for(;n>0;)
{
sum=sum+(n%10);n=n/10;
}
return (sum);
}}
_________________________________________________________________________
96
Java Technology M.Sc IT Part II
___________________________________________________________________________
processserver.java

import java.rmi.*;
import java.rmi.server.*;

public class processserver


{

public static void main(String args[])


{
try
{
processimplement pim=new processimplement();
Naming.rebind("rmi://localhost:1099/process",pim);

System.out.println("Server Registered");
System.out.println("\nWaiting for Client........");
}
catch(Exception e)
{
}
}
}

processclient.java

import java.rmi.*;
import java.io.*;

public class processclient


{
public static void main(String args[])
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
processinterface
pi=(processinterface)Naming.lookup("rmi://localhost:1099/process");

System.out.println("\n**********************Welcome to World of
RMI*********************");
while(true)
{
System.out.println("\n\n1.Factorial\n2.Reverse\n3.Sum of
Digits");
System.out.print("\nPlease enter a option from the above
menu(Bye to exit):");
String choice=br.readLine();
if(choice.equalsIgnoreCase("bye"))
_________________________________________________________________________
97
Java Technology M.Sc IT Part II
___________________________________________________________________________
{
System.exit(0);
}
System.out.print("\nEnter a number:");
int num=Integer.parseInt(br.readLine());

if(choice.equals("1"))
System.out.println("\nThe Factorial of the number
is:"+pi.fact(num));
else if(choice.equals("2"))
System.out.println("\nThe Reverse of the number
is:"+pi.rev(num));
else if (choice.equals("3"))
System.out.println("\nThe Sum of digits of the number
is:"+pi.sum(num));
}

}
catch(Exception e)
{
}
}
}

_________________________________________________________________________
98
Java Technology M.Sc IT Part II
___________________________________________________________________________

Output:

_________________________________________________________________________
99

You might also like