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

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 upperleft corner location of (insets.left,, and has a size of width - (insets.left + insets.right) by height - ( + 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

INFORMATION_MESSAGE)."INITITAL INFORMATION IS". typeOfAccount=saving."Rahul"). } } _________________________________________________________________________ 4 .String saving.String Aname.Java Technology M. save."saving".JOptionPane. } } public class BankAccount { public static void main(String args[]) { AccountDepositerName save=new AccountDepositerName(5000.String Dname) { super(amt.JOptionPane.Sc IT Part II ___________________________________________________________________________ BALANCE AND ACCOUNTHOLDER NAME".initialVal(). } public void initialVal() { JOptionPane.00. depositer=Dname.showMessageDialog(null."Sachin".INFORMATION_MESSAGE). } } } class AccountDepositerName extends SavingAccount { String typeOfAccount.init(). String depositer."NAME OF ACCOUNT HOLDER="+accountName+"\n NAME OF DEPOSITER="+depositer+"\n TOTAL AMOUNT="+amount+"\n TYPE OF ACCCONUT NAME=" +typeOfAccount. save. AccountDepositerName(double amt.Aname).

Java Technology M.Sc IT Part II ___________________________________________________________________________


_________________________________________________________________________ 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.

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

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

_________________________________________________________________________ 9 . The class that is interested in processing an action event implements this interface.Java Technology M. Similarly display different geometric shapes like line. to the maximum degree possible.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. ellipse and polygon (with more than four sides) as per the user co-ordinates. that object's actionPerformed method is invoked. and the object created with that class is registered with a component. the listener object's itemStateChanged method is invoked.swing package: Provides a set of "lightweight" (all-Java language) components that. Description: javax. using the component's addActionListener method. square. The class that is interested in processing an item event implements this interface. When the action event occurs. ItemListener: The listener interface for receiving item events. work the same on all platforms ActionListener: The listener interface for receiving action events. The object created with that class is then registered with a component using the component's addItemListener method. rectangle. When an itemselection event occurs.

rectangle=new Checkbox("Rectangle" l6=new Label("Enter starting Y coordinate").cbg.l11.p5. _________________________________________________________________________ 10 .false).l12.b4.ItemListener { String str.*.p4. polygon=new Checkbox("Polygon".l7.l3.l9. TextField t1. import java. ypolygon5=new int[5].polygon.l4.cbg.b6.*. l4=new Label("Enter widt and Height of Square"). l2=new Label("Enter width of rectangle").false).ch. int x.square.p7.cbg.p3.oval.l2.edy. oval=new Checkbox("Oval".awt.b2. public void init() { cbg=new CheckboxGroup().p6.event.true). Checkbox circle.line.swing.l6.t8.t13. import java.b3.l10.t14.awt.stx.t2. int xpolygon5[]. xpolygon5=new int[5].false). circle=new Checkbox("Circle".t3.l13.p2.flag=0. int ypolygon5[].false).t4.l8.t5.applet.t6.t10.y.Java Technology M. square=new Checkbox("Square".edx.Sc IT Part II ___________________________________________________________________________ Source Code: /* <applet code = Applet2b width = 600 height = 100> <param name=text value = "Try Application"> </applet> */ import javax.t9.rectangle. CardLayout co.*. l1=new Label("Enter radius of circle").*. line=new Checkbox("Line". CheckboxGroup cbg.b5. public class Applet2b extends Applet implements ActionListener. import java. Label l1.t7.cbg.sty.false). l5=new Label("Enter starting X coordinate"). l3=new Label("Enter Heigth of rectangle"). Panel p1.cbg.l5. Button b1.

Sc IT Part II ___________________________________________________________________________ 000l7=new Label("Enter ending X coordinate"). t4=new TextField(10).add(b1).add(t3).add(t1). b5=new Button("Display"). co=new CardLayout(). b1=new Button("Display"). p2.add(l2). b6=new Button("Enter Coordinate"). p3. p3.setLayout(new GridLayout(3. p3. l13=new Label("Enter Y coordinate"). p3. p1=new Panel(). l9=new Label("Enter width of oval").Java Technology M. t6=new TextField(10). p3. l11=new Label("Enter number of points for Polygon(>4 and <11)"). t11=new TextField(10). t2=new TextField(10). p2. l8=new Label("Enter ending Y coordinate"). p2.add(l1). t1=new TextField(10). t12=new TextField(10). p3. t5=new TextField(10). t9=new TextField(10).add(b2). t3=new TextField(10). t7=new TextField(10).add(t2).setLayout(new FlowLayout()). t8=new TextField(10). b3=new Button("Display"). l10=new Label("Enter height of oval"). b4=new Button("Display").add(l3). p2=new Panel(). p2.setLayout(co). l12=new Label("Enter X coordinate"). t10=new TextField(10).3)). t13=new TextField(10). p3=new Panel(). p1. b2=new Button("Display"). _________________________________________________________________________ 11 . t14=new TextField(10).

add(l12)."Rectangle").setLayout(new GridLayout(3. p5. add(circle). p6.add(l7). p1. p6.2)). p5=new Panel().add(l13).add(p5.add(b5).setLayout(new GridLayout(3."Square").add(t12).add(t7). p6=new Panel(). p1. p4.add(t9)."Circle").add(p4. p4. add(oval).add(l10).add(l9). p5. p1.add(l4). _________________________________________________________________________ 12 . p5.add(b4). p6.2)). p7."Polygon").add(p7.add(l8).setLayout(new GridLayout(4."Line").add(p6. p5. p7. p5. p1.3)).add(b3).add(t8). p6.add(p2."Oval"). p6. p7.add(t5). p5. p4. add(line). p7.Java Technology M. p6.3)).add(l11).add(p3. p5.setLayout(new GridLayout(5. p7. p1. p7.add(l5). p7.add(l6).add(t13). p5. p1. p4. p5. p7=new Panel().add(b6).Sc IT Part II ___________________________________________________________________________ p4=new Panel(). p5.add(t10).add(t11).add(t6). p7.add(t4).

addActionListener(this).y).addItemListener(this). add(square).drawOval(200.drawPolygon(xpolygon5.2*x). polygon.edy).x.addActionListener(this). line. else if(ch==2) g. circle. b4. b1.drawRect(200.addItemListener(this).addActionListener(this).ypolygon5.175.Java Technology M.edx.2*x. square.addItemListener(this).addItemListener(this).drawOval(200. add(polygon).175. b3.addItemListener(this). else if(ch==4) g. b5. add(p1).sty.addActionListener(this).drawLine(stx. } _________________________________________________________________________ 13 . else if(ch==5) g. oval.x.drawRect(200.x. else if(ch==3) g.addActionListener(this). rectangle. } public void start() { } public void stop() { } public void paint(Graphics g) { if(ch==1) g. else if(ch==6) g.175.addItemListener(this).x).Sc IT Part II ___________________________________________________________________________ add(rectangle). b6.175.y).

edy=Integer.getSource()==b5) { ch=5.getText(). } else if(ae. str=t4.parseInt(str).getText(). repaint(). y=Integer.parseInt(str).getSource()==b2) { ch=2.getText().parseInt(str).parseInt(str). str=t6. x=Integer.parseInt(str).Java Technology M.Sc IT Part II ___________________________________________________________________________ public void actionPerformed(ActionEvent ae) { if(ae. edx=Integer. x=Integer. x=Integer.getText(). } else if(ae.getText().getText().parseInt(str).getText(). str=t3.getSource()==b1) { ch=1. repaint(). repaint(). x=Integer. } else if(ae.getText().parseInt(str). str=t7.getSource()==b3) { ch=3. str=t10. str=t5. str=t8. stx=Integer. y=Integer.parseInt(str).parseInt(str).parseInt(str). repaint(). } else if(ae. str=t1. repaint(). str=t2. str=t9.getSource()==b4) { ch=4.getText(). sty=Integer.getText(). } _________________________________________________________________________ 14 .

no=Integer. } } public void itemStateChanged(ItemEvent ie) { if(cbg. co. t13. t12.getText(). } else if(cbg. } else if(cbg.getLabel().getSelectedCheckbox().setText("").setEnabled(false). } _________________________________________________________________________ 15 .getSource()==b6) { ch=6.parseInt(str).getSelectedCheckbox().getLabel(). while(flag<5) { str=t12. str=t13.equals("Rectangle")) { repaint(). co. co. repaint().setEnabled(false).getText(). co.Java Technology M."Circle").setText("")."Line").parseInt(str).getLabel().getSelectedCheckbox().Sc IT Part II ___________________________________________________________________________ else if(ae.getSelectedCheckbox().show(p1."Rectangle").show(p1. str=t11. } t11.parseInt(str). t13.getLabel(). t12.equals("Line")) { repaint(). } else if(cbg.getText().equals("Square")) { repaint().show(p1.equals("Circle")) { repaint()."Square"). flag++.setEnabled(false). xpolygon5[flag]=Integer. ypolygon5[flag]

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

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

Java Technology M.Sc IT Part II ___________________________________________________________________________ _________________________________________________________________________ 18 .

Sc IT Part II ___________________________________________________________________________ _________________________________________________________________________ 19 .Java Technology M.

legacy collection classes. _________________________________________________________________________ 20 . Multiple strings should be displayed in different colors. internationalization.awt package: Provides interfaces and classes for dealing with different types of events fired by AWT components. Description: java. Events are fired by event sources. An event listener registers with an event source to receive notifications about the events of a particular type.awt. as well as event listener adapters. which are convenience classes to make easier the process of writing event listeners. Problem Statement: Write a program for bouncing string. date and time facilities. event model. java.event package: Provides interfaces and classes for dealing with different types of events fired by AWT components. This package defines events and event listeners. a random-number generator. java.util package: Contains the collections framework.Sc IT Part II ___________________________________________________________________________ Practical 03-A Write a program for Multithreading (using frames). The algorithm for bouncing each string must be assigned to different threads. and miscellaneous utility classes (a string tokenizer.Java Technology M. Contains all of the classes for creating user interfaces and for painting graphics and images. and a bit array).

refbuttonpanel.swing.swing. setSize(200. import java. import javax.swing. refbuttonpanel. c. import javax.refstop.*. refdc=new drawcanvas().JButton. c.add(refstart).awt. refcanvaspanel=new JPanel(). refbuttonpanel.util.BorderLayout.SOUTH).setLayout(new BorderLayout()). class bouncestring extends JFrame implements ActionListener { JButton refstart.JPanel. refexit.300).addActionListener(this). c. refexit=new JButton("Exit"). refbuttonpanel=new JPanel(). } _________________________________________________________________________ 21 .refcanvaspanel.awt.JFrame. refstop. bouncestring() { c=getContentPane().add(refdc). import javax.addActionListener(this). setVisible(true). refstart=new JButton("Start"). refstart.add(refstop).add(refexit).Sc IT Part II ___________________________________________________________________________ Source Code: import java. import java. refstop=new JButton("Stop").*.addActionListener(this). Container c.add(refbuttonpanel. drawcanvas refdc.event.*. setDefaultCloseOperation(EXIT_ON_CLOSE). JPanel refbuttonpanel.refexit.Java Technology M.

//Position and radius of the first ball x1 = 100. dy = 7. drawcanvas() { x = 10. y = 10. Thread third.exit(0).dy1.dx1. // Position and radius of the third ball dx = 11. } } public static void main(String args[]) { bouncestring cd=new bouncestring(). Thread refcurthread. boolean stop.dx2. dx1 = 11.dy2. } public void paint(Graphics g) { } else if(ae. r = 10. } } class drawcanvas extends Canvas implements Runnable { int x.move(). _________________________________________________________________________ 22 . y2 = 50.x1.getSource()==refstart) { refdc. Thread first.getSource()==refstop) { refdc.getSource()==refexit) { System.Java Technology M. } else if(ae.y1. // Position and radius of the second ball x2 = 50. dy1 = 11.setColor(Color.dx. dx2 = 17.halt().Sc IT Part II ___________________________________________________________________________ public void actionPerformed(ActionEvent ae) { if(ae. y1 = 100.y. Thread second.r.dy. dy2 = 10.

g. x += dx.r + dx < 0) || (x + r + dx > getWidth())) dx = -dx. if ((y .drawString("Germany". g.drawString("France"."First")) { if ((x . y += dy. } else if(refcurthread. y2-r).getName(). y-r). // Move the third ball. g.r + dy2 < 0) || (y2 + r + dy2 > getHeight())) dy2 = -dy2. g.r + dx2 < 0) || (x2 + r + dx2 > getWidth())) dx2 = -dx2.Sc IT Part II ___________________________________________________________________________ g.setColor(Color.currentThread(). _________________________________________________________________________ 23 . y2 += dy2. y1-r).currentThread()). x1-r.drawString("India".equalsIgnoreCase("Third")) { if ((x2 .blue). x2-r. // Move the first ball. // Move the second ball.equalsIgnoreCase("Second")) { if ((x1 . x2 += dx2.println(Thread. } elseif(refcurthread.setColor(Color.out. if ((y2 . } public void run() { while(!stop) { refcurthread=Thread.r + dy1 < 0) || (y1 + r + dy1 > getHeight())) dy1 = -dy1. System.Java Technology M. if(refcurthread.r + dx1 < 0) || (x1 + r + dx1 > getWidth())) dx1 = -dx1. y1 += dy1.getName(). x1 += dx1.r + dy < 0) || (y + r + dy > getHeight())) dy = -dy.getName(). if ((y1 .

start()."Second")."First"). stop=false.start(). } } _________________________________________________________________________ 24 . first. try { Thread.sleep(60). } catch(Exception e) { } } } public void move() { first=new Thread(this. second=new Thread(this. third=new Thread(this. third."Third").Java Technology M.start(). } public void halt() { stop=true. second.Sc IT Part II ___________________________________________________________________________ } repaint().

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

Frame that adds support for the JFC/Swing component architecture. If no index is specified when adding a component to a container. The order of the list will define the components' front-to-back stacking order within the container. as a rule. Container: A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components. a JFrame contains a JRootPane as its only child.Components added to a container are tracked in a list. The JFrame class is slightly incompatible with Frame. Each ball should be displayed with a different color. it will be added to the end of the list .Sc IT Part II ___________________________________________________________________________ Practical 03-B Problem Statement: Write a program for bouncing ball. contain all the non-menu components displayed by the JFrame.Java Technology M. The default behavior is to simply hide the JFrame when the user closes the window. This is different from the AWT Frame case. _________________________________________________________________________ 26 .awt. The content pane provided by the root pane should. Description: JFrame: An extended version of java. Unlike a Frame. a JFrame has some notion of how to respond when the user attempts to close the window. Like all other JFC/Swing top-level containers.

not in the frame itself. **/ public class DrawingPane extends JFrame { // The scribble application relies on the ScribblePane component developed // earlier.Sc IT Part II ___________________________________________________________________________ Source Code: import java. // Call superclass constructor and set window title // All content of a JFrame (except for the menubar) goes in the // Frame's internal "content pane". import javax.setLayout(new BorderLayout()).setBorder(new BevelBorder (BevelBorder. refBouncingBallPane.Java Technology M.swing.awt.yellow).awt. BorderLayout. // LookAndFeelPrefs is defined elsewhere in this package. **/ public DrawingPane() { super("Multiple Bouncing Balls .*. _________________________________________________________________________ 27 .event.swing.*.border.Thread based"). //LookAndFeelPrefs. // Create the main scribble pane component. /** * This constructor creates the GUI for this application. Container contentPane = this. // Specify a layout manager for the content pane contentPane. BouncingBallPane refBouncingBallPane.*. } public static void main(String[] args) { // Set the look-and-feel for the application. This field holds the ScribblePane instance it uses.setBackground(Color. import java. and add it to the content pane refBouncingBallPane = new BouncingBallPane(). contentPane.getContentPane(). refBouncingBallPane. refBouncingBallPane.class).CENTER).setPreferredLookAndFeel(ScribbleApp.LOWERED)). import javax. and // a background color.startApp().*.add(refBouncingBallPane. give it a border. // The same is true for JDialog and similar top-level containers. /** * This JFrame subclass is a simple "paint" application.

y2. boolean pleaseStop. refDrawingPane.setSize(500. Thread animator2. // Position and radius of the circle int dx1.exit(0). // Position and radius of the first ball x1 = 100. r = 10. dy1 = 11. } public void paintComponent(Graphics g) { /** We override this method to draw ourselves. Thread refCurrentThread. refDrawingPane. y = 10.200)). int ballNumber.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System. 300). // Trajectory of circle int x1. y2 = 50. } } class BouncingBallPane extends JComponent implements Runnable { int x. y. // Position and radius of the circle int dx.Sc IT Part II ___________________________________________________________________________ DrawingPane refDrawingPane = new DrawingPane(). dy2 = 10. dy = 7. Thread animator3. dy. dy2. // A flag to ask the thread to stop public BouncingBallPane() { setPreferredSize(new Dimension(450. ballNumber = 0.Java Technology M. // Handle window close requests refDrawingPane. dx2 = 17. // We need a default size x = 10. */ _________________________________________________________________________ 28 // The threads that performs the animation . dx1 = 11. // Trajectory of circle Thread animator1. // Position and radius of the third ball dx = 11. y1. // Position and radius of the circle int dx2. } }). y1 = 100.setVisible(true). r. // Set the window size and make it visible. dy1. // Position and radius of the second ball x2 = 50. // Trajectory of circle int x2.

paintComponent(g). g.fillRect(0. x += dx.getName(). 0. g. y-r. } /** * This method moves (and bounces) the circle and then requests a redraw. y += dy.setColor(Color.drawString(refCurrentThread. r*2).setColor(Color.r + dy < 0) || (y + r + dy > getHeight())) dy = -dy. getWidth().r + dx < 0) || (x + r + dx > getWidth())) dx = -dx. * The animator thread calls this method periodically.create()). g. y2-r. r*2).Sc IT Part II ___________________________________________________________________________ // Let the superclass do its painting first super.fillOval(x-r. if ((y . g2. r*2).r + dy1 < 0) || (y1 + r + dy1 > getHeight())) dy1 = r*2. Technology M. getWidth()/2. g. switch(ballNumber) { case 1: if ((x . r*2. getHeight()). g2. g. so do this ourselves. // Move the first ball. _________________________________________________________________________ 29 . if ((y1 .setColor(getBackground()). // 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. case 2: if ((x1 . getHeight()/2). **/ public void animate() { // Bounce if we've hit an edge. break. // Our superclass doesn't paint the background. r*2. //g.fillOval(x1-r.r + dx1 < 0) || (x1 + r + dx1 > getWidth())) dx1 = -dx1.

equals("Third Ball")) ballNumber = 3.Sc IT Part II ___________________________________________________________________________ // Move the second ball.currentThread(). // Wait 'n' milliseconds catch(InterruptedException e) {} // Ignore interruptions } } _________________________________________________________________________ 30 . } /** * This method is from the Runnable interface. case 3: if ((x2 . x1 += dx1. y2 += dy2. if( refCurrentThread.r + dx2 < 0) || (x2 + r + dx2 > getWidth())) dx2 = -dx2.getName(). else if(refCurrentThread.r + dy2 < 0) || (y2 + r + dy2 > getHeight())) dy2 = -dy2. break.getName().sleep(30). // Move the third ball. try { } Thread. It is the body of the * thread that performs the animation.equals("First Ball")) ballNumber = 1. break. repaint(). x2 += dx2.Java Technology M. y1 += dy1. The thread itself is created * and started in the start() method. }//end of switch // Ask the browser to call our paint() method to draw the circle // at its new position. **/ public void run() { while(!pleaseStop) { // Loop until we're asked to stop refCurrentThread = Thread. else if(refCurrentThread.getName(). if ((y2 . animate().equals("Second Ball")) ballNumber = 2.

// Start the thread. // Create a thread pleaseStop = false. // Create a thread animator3 = new Thread(this. animator3.start(). "First Ball"). "Second Ball"). // Don't ask it to stop now animator1. "Third Ball").start().Java Technology M.Sc IT Part II ___________________________________________________________________________ /** Start animating when the browser starts the applet */ public void startApp() { animator1 = new Thread(this. } } _________________________________________________________________________ 31 . // Create a thread animator2 = new Thread(this. animator2. // Meanwhile. // The thread that called start now returns to its caller.start(). 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.

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

For top efficiency. For example: BufferedReader in= new BufferedReader(new InputStreamReader(System. Description: InputStreamReader: It extends from Reader class.Java Technology M. Dimension class: The Dimension class encapsulates the width and height of a component (in integer precision) in a single object. consider wrapping an InputStreamReader within a BufferedReader. Several methods defined by the Component class and the LayoutManager interface return a Dimension object. Problem Statement: Implement user-defined exception.Sc IT Part II ___________________________________________________________________________ Practical 04 Write a program for Exception Handling. Create throw and catch user-defined exception and handle runtime exception. 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. The class is associated with certain properties of components. _________________________________________________________________________ 33 . An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified

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

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

Whether or not a file is available or may be created depends upon the underlying platform. allow a file to be opened for writing by only one FileOutputStream (or other file-writing object) at a time. FileOutputStream: A file output stream is an output stream for writing data to a File or to a FileDescriptor. _________________________________________________________________________ 36 . For writing streams of characters. For e.txt to File. In such situations the constructors in this class will fail if the file involved is already open. What files are available depends on the host environment. in particular. This method blocks if no input is yet available.Java Technology M.FileInputStream is meant for reading streams of raw bytes such as image data.g. consider using FileReader. java copyFile from File.txt Description: FileInputStream: A FileInputStream obtains input bytes from a file in a file system. For reading streams of characters.Sc IT Part II ___________________________________________________________________________ Practical 05-A Write a program for File Handling Problem Statement: Copy a file to another file. FileOutputStream is meant for writing streams of raw bytes such as image data. consider using FileWriter. read(): Reads a byte of data from this input stream. Some platforms.

fin.close().Java Technology M.out. } }while(i!=-1). }catch(IOException e){} System.println("ArrayIndex OutOf Bounds").close().out.out.return. } try { do { i=fin.Sc IT Part II ___________________________________________________________________________ Source Code: import java.println("\nFile Copied!\nCopied File name is f2. try { try{ fin=new FileInputStream(args[0]).*.txt").return. } } _________________________________________________________________________ 37 . fout.out. } catch(FileNotFoundException e){ System.return. if(i!=-1) { fout. FileInputStream fin.println("Input file not found"). } catch(FileNotFoundException e){ System. FileOutputStream fout. class CopyFile5a { public static void main(String args[]) throws IOException { int i.write((char)i). } } catch(ArrayIndexOutOfBoundsException e) {"Output File file not found"). } try{ fout=new FileOutputStream(args[1]).

and the Garyalies. pops its head into the shop. Samuel Foote 1720-1777 _________________________________________________________________________ 38 . with the little round button at top. and there were present the Picninnies. and the grand Panjandrum himself.Java Technology M. coming up the street. and at the same time a great she-bear. and there were present the Picninnies. and they all fell to playing the game of catch as catch can.Sc IT Part II ___________________________________________________________________________ Output: Input File: So she went into the garden to cut a cabbage-leaf. till the gun powder ran out at the heels of their boots. and she very imprudently married the barber. and the Garyalies. and at the same time a great she-bear. to make an apple-pie. to make an apple-pie. and the grand Panjandrum himself. and the Joblillies. coming up the street. and the Joblillies. 'What! no soap?' So he died. with the little round button at top. and they all fell to playing the game of catch as catch can. 'What! no soap?' So he died. 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. and she very imprudently married the barber. pops its head into the shop.

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.


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*; 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 = != -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 =; 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 =; 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

and the Joblillies. pops its head into the shop. and the grand Panjandrum himself. coming up the street. 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%.%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 . and at the same time a great she-bear.txt So she went into the garden to cut a cabbage-leaf. and the Garyalies.Java Technology M. 'What! no soap?' So he died.\mfy&%st%xtfuD.Sc IT Part II ___________________________________________________________________________ Output: Input File: Src. and she very imprudently married the barber. to make an apple-pie. with the little round button at top. and there were present the Picninnies. till the gun powder ran out at the heels of their boots. and they all fell to playing the game of catch as catch can.

_________________________________________________________________________ 43 . JFileChooser: JFileChooser provides a simple mechanism for the user to choose a file. The most important classes are Object. instances of which represent classes at run time.Sc IT Part II ___________________________________________________________________________ Practical 06 Problem Statement: Create jar files using java package Description: java.An application cannot create its own instance of this class. which is the root of the class hierarchy. 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. and Class.Java Technology M.lang package: Provides classes that are fundamental to the design of the Java programming language. The current runtime can be obtained from the getRuntime method.

getSource(). color1 = new Color(39.20).100. char[] password = input.200.*. label."Invalid password. public static void main(String[] argv) { final JFrame f = new JFrame("Password"). BorderLayout.setBounds(50.add(label.Java Technology M.awt.add(passwordField.126).setFont(new Font("Monotype Corsiva". f. passwordField. Try again.getContentPane().setEchoChar('*'). f.*. import java.swing. passwordField. import java. f. BorderLayout.20.JOptionPane.getPassword().setBounds(250. } } }). label. 20)). label. _________________________________________________________________________ 44 .20).CENTER). passwordField. passwordField. f.setVisible(false).setForeground(color1).showMessageDialog(f. final JPasswordField passwordField = new JPasswordField(10).ERROR_MESSAGE). if (isPasswordCorrect(password)) { new ComboProgram().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JPasswordField input = (JPasswordField)e. JLabel label = new JLabel("Enter the password: ").setText(""). public class User_Login { static Color color1.getContentPane().event. Font.Sc IT Part II ___________________________________________________________________________ Source Code: Code for login form import javax."ErrorMessage".".*.CENTER).20. } else { JOptionPane.getContentPane().BOLD.58.awt.setLayout(null).

Sc IT Part II ___________________________________________________________________________ f.length != correctPassword. _________________________________________________________________________ 45 . import java.awt.100).Graphics. i < input.awt.awt. import javax.event. f.JLabel. f.awt. i ++) { if (input[i] != correctPassword[i]) { return false. } } Code for executing the contents fater successful login import java.setVisible(true).setLocation(300.setResizable(false).ItemListener.250).ItemEvent.awt. } } return true.Color. import java. import java.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.setSize(400.awt. f.JFrame.repaint().awt.WindowAdapter. import javax. } }).event. f. import java. f.length) { return false. import java. f.validate().Java Technology M.exit(0).event.swing.awt. if (input. } private static boolean isPasswordCorrect(char[] input) { char[] correctPassword = { '1'.event. '3'}. import java.WindowEvent.FlowLayout. '2'.Container.length. } for (int i = 0.swing. import java.

jc. jc. // Create label jl = new JLabel(new ImageIcon("france. // Get content pane Container contentPane = getContentPane().Java Technology M. jc.Sc IT Part II ___________________________________________________________________________ import javax. japan. _________________________________________________________________________ 46 .JComboBox.addItem("Line").add(jl).setColor(c).setLayout(new FlowLayout()). jc.addItemListener(this). // Create a combo box and add it to the panel JComboBox jc = new JComboBox(). pack().addItem("Circle").exit(0).ImageIcon.addItem("Ellipse"). jc.250). g. contentPane.add(jc). italy. ImageIcon france. JLabel jl.gif")). Graphics g = getGraphics().getItem(). setVisible(true). 0). ComboProgram() { frmShow = new JFrame("ComboBox Demo").swing. contentPane.swing. setLocation(300. import javax.addItem("Rectangles"). contentPane. setTitle("Draw Objects"). addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent we) { System. } public void itemStateChanged(ItemEvent ie) { String s = (String)ie. 0. germany. class ComboProgram extends JFrame implements ItemListener { JFrame frmShow. } }). Color c = new Color(255.

} if(s == "Circle") { g. } if(s == "Rectangles") { g.150.Sc IT Part II ___________________________________________________________________________ if(s == "Line") { g.400. } } _________________________________________________________________________ 47 . } } public static void main(String args[]) { new ComboProgram().Java Technology M.400.400. } if(s == "Ellipse") { g.drawLine(150.drawOval(

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

however. image-only labels are horizontally centered. JList: A component that allows the user to select one or more objects from a list. by default. labels are vertically centered in their display area.Java Technology M. It's easy to display an array or vector of objects. 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.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. display a keyboard alternative as a convenience for a nearby component that has a keyboard alternative but can't display it. By default. Text-only labels are leading edge aligned. represents the contents of the list. using a JList constructor that builds a ListModel instance for you. A label does not react to input events. it cannot get the keyboard focus. A label can. by default.A JLabel object can display either text. Font: The Font class represents fonts. You can specify where in the label's display area the label's contents are aligned by setting the vertical and horizontal alignment. an image. ListModel. or both. _________________________________________________________________________ 49 . As a result. A separate model. or both.

jlName=new JList(str1)."Dark Gray". p3."Monospaced"}.Exit. import javax."Blue". _________________________________________________________________________ 50 .*.add(p2).*. p2.add(p1). import java. lblStr=new JLabel("India is my Country"). p2=new JPanel(). p1. String str2[] = {"Black". Exit=new JButton("Exit").add(Change).p2.event.add(jlName).swing. createEtchedBorder().awt. p3."Cyan".Java Technology M. Container refCon=getContentPane().jlColor. String str1[] = {"Serif".Sc IT Part II ___________________________________________________________________________ Source Code: import java. public class FontSize_Color extends JFrame implements ActionListener { JLabel lblStr.setLayout(new FlowLayout())."Green"}.setBorder(BorderFactory. refCon."Select")).awt. p1.*. refCon. p3.setLayout(new FlowLayout().setLayout(new FlowLayout()). p2. jlColor=new JList(str2). Exit. p1=new JPanel()."SansSerif".p3. Change=new JButton("Change"). JButton Change.add(lblStr).setLayout(new FlowLayout()). JList jlName.createTitledBorder(BorderFactory. JPanel p1. Change.add(jlColor).addActionListener(this). refCon.add(Exit). p3=new JPanel(). p2. public FontSize_Color() { setTitle("Select the Font Type anf Font COlor"). //p2.addActionListener(this).

BOLD|Font.getSelectedIndex()==4) { Font font=new Font("Serif".green).15).ITALIC.setFont(font).BOLD|Font.Font.getSelectedIndex()==2) { Font font=new Font("Serif". lblStr.setFont(font).Font.getSelectedIndex()==0 && jlColor.Font. } if(jlName.ITALIC.BOLD|Font.setForeground(Color.Font. lblStr.setForeground(Color. } if( IT Part II ___________________________________________________________________________ refCon.15). lblStr.getSelectedIndex()==1) { Font font=new Font("Serif".setForeground(Color.getActionCommand()=="Change") { if(jlName. lblStr. lblStr.cyan). lblStr.getSelectedIndex()==0 && jlColor.getSelectedIndex()==0) { _________________________________________________________________________ 51 .black). } if(jlName.setFont(font).setFont(font).getSelectedIndex()==0 && jlColor.add(p3). lblStr. } public void actionPerformed(ActionEvent ae) { if(ae.getSelectedIndex()==0 && jlColor. lblStr. } if(jlName.getSelectedIndex() ==0) { Font font=new Font("Serif".15). } if(jlName.getSelectedIndex()==1 && jlColor.setFont(font).15).BOLD|Font.getSelectedIndex()==0 && jlColor.ITALIC.BOLD|Font. lblStr. pack().15).setForeground(Color.Java Technology M.ITALIC.Font.ITALIC.getSelectedIndex()==3) { Font font=new Font("Serif".darkGray). lblStr. setVisible(true).

setFont(font). lblStr.darkGray).getSelectedIndex()==2 && jlColor.ITALIC.BOLD| lblStr.Font.getSelectedIndex()==1 && jlColor.setForeground(Color.15). } if(jlName.getSelectedIndex()==1 && jlColor.setForeground(Color. lblStr.getSelectedIndex()==1 && jlColor. lblStr.Font.getSelectedIndex()==2) { Font font=new Font("SansSerif". lblStr. lblStr.BOLD|Font.getSelectedIndex()==2 && jlColor.Sc IT Part II ___________________________________________________________________________ Font font=new Font("SansSerif". } _________________________________________________________________________ 52 .setFont(font). lblStr.getSelectedIndex()==3) { Font font=new Font("SansSerif".BOLD| Font.setForeground(Color.getSelectedIndex()==4) { Font font=new Font("SansSerif".setForeground(Color. } if( lblStr. lblStr. } if(jlName. lblStr.getSelectedIndex()==0) { Font font=new Font("Monospaced".getSelectedIndex()==1 && jlColor.15). } if(jlName.setForeground(Color.setFont(font).setFont(font) Technology M.15).getSelectedIndex()==1) { Font font=new Font("SansSerif". lblStr. lblStr.BOLD| Font.setForeground(Color.BOLD|Font.setFont(font).15).15).ITALIC.ITALIC.setForeground(Color.getSelectedIndex()==1) { Font font=new Font("Monospaced". } if(jlName. } if(jlName. lblStr.15).blue).BOLD|Font.BOLD|Font.setFont(font).Font.ITALIC.Font.ITALIC.

ITALIC.setForeground(Color.BOLD| Font.getSelectedIndex()==2 && } public static void main(String args[]) { FontSize_Color refFont =new FontSize_Color().getSelectedIndex()==2 && jlColor.cyan).getSelectedIndex()==2) { Font font=new Font("Monospaced".Font.BOLD|Font. lblStr.getSelectedIndex()==4) { Font font=new Font("Monospaced".setFont(font).exit(0).setFont(font).Font. } if(jlName. } if(jlName.getActionCommand()=="Exit") System.darkGray).15). lblStr.Java Technology M. lblStr.getSelectedIndex()==2 && jlColor. lblStr.ITALIC.getSelectedIndex()==3) { Font font=new Font("Monospaced".setForeground(Color. lblStr. lblStr.setForeground(Color.BOLD| Font.15).Sc IT Part II ___________________________________________________________________________ if(jlName. } } _________________________________________________________________________ 53 . } } else if(ae.Font.15).

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

For example an internal dialog or a drag and drop effect component. JPanel: JPanel is a generic lightweight container. The layeredPane can be used by descendants that want to add a child to the RootPaneContainer that isn't layout managed.Java Technology M. Images that are created from a URL. filename or byte array are preloaded using MediaTracker to monitor the loaded state of the image. _________________________________________________________________________ 55 . getContentPane(): A Container that manages the contentPane and in some cases a menu bar.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. ImageIcon: An implementation of the Icon interface that paints Icons from Images.

getActionCommand()=="Show") _________________________________________________________________________ 56 .refLabel2. refLabel2 = new JLabel("Select to view Imagies of Babies"."White baby". ImageViewer() { String str[]={"Geen baby".swing.*. refCon.add(show). ii1=new ImageIcon("1. refCon.add(lblImage1). JList jl1.setLayout(new FlowLayout()). show=new JButton("Show"). pack()."Blue baby"}. import javax. Container refCon=getContentPane(). } public void actionPerformed(ActionEvent ae) { if(ae.add(jl1).add(refLabel2).*.LEFT).ii3. refCon.ii2. Button show. setVisible(true). lblImage1=new JLabel(). JLabel. ii2=new ImageIcon("2. import java.awt. ii3=new ImageIcon("3. JLabel lblImage1.event. jl1=new JList(str).Java Technology M.jpg").jpg").awt. } public void display() { setTitle("Image Viewer").Sc IT Part II ___________________________________________________________________________ Source Code: import java.addActionListener(this). show. refCon. public class ImageViewer extends JFrame implements ActionListener { ImageIcon ii1.*.jpg"). refCon.

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

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

an item that can be selected or deselected. Used with a ButtonGroup object to create a group of buttons in which only one button at a time can be selected.awt. The java.awt.awt.TextField.Java Technology M.JTextField has a method to establish the string used as the command string for the action event that gets fired. JRadioButton: An implementation of a radio button -. This component has capabilities not found in the java.TextField where it is reasonable to do so. A tab is represented by an index corresponding to the position it was added in.) _________________________________________________________________________ 59 .awt. TextField is intended to be source-compatible with java. JTextField: JTextField is a lightweight component that allows the editing of a single line of text.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. where the first tab has an index equal to 0 and the last tab has an index equal to the tab count minus 1. and which displays its state to the user. The superclass should be consulted for additional capabilities. (Create a ButtonGroup object and use its add method to include the JRadioButton objects in the group.TextField class. otherwise it will use the text of the field as a compatibility with java. JTextField will use the command string set with the setActionCommand method if not null.TextField used the text of the field as the command string for the ActionEvent.

add(rsmd.getColumnName(i)). import java. Container refCon=getContentPane(). Statement s=c.awt. for(int i=1 .awt. public ViewRecords() { lblTitle=new JLabel("Student Records"). ResultSetMetaData rsmd=rs.getConnection ("jdbc:odbc:StudInfo").odbc. refCon.*. setTitle("Student Records").executeQuery(strQuery). refRow.setLayout(new BorderLayout()).add(lblTitle.*. import java.getColumnCount() .event. Vector refCol.BorderLayout. i++) { refCol.forName("sun.Sc IT Part II ___________________________________________________________________________ Source Code: import java.*.NORTH). ResultSet rs=s. refCol = new Vector(). public class ViewRecords extends JFrame { JTable refTable.util.getMetaData().JdbcOdbcDriver").jdbc. refCon. } _________________________________________________________________________ 60 .swing. refData = new Vector(). try { Class. i<=rsmd. refData. String strQuery="select * from StudentInfo".*. JLabel lblTitle. Connection c= DriverManager.Vector.createStatement().Java Technology M. import java .sql. import javax.

..Sc IT Part II ___________________________________________________________________________ while(rs. } rs.. refCon.out..CENTER).getString(i))..add(rs. i<=rsmd. for(int i=1 .getColumnCount() . } refTable=new JTable(refData...add(refTable.add(refRow).out. } refData..println("Exception Occured ... } public static void main(String args[]) { ViewRecords refView=new ViewRecords().... } catch(Exception e) { { refRow=new Vector().close(). pack()." +e).BorderLayout.close().Java Technology M. setVisible(true).println(refCol).. System. i++) { refRow.. } } _________________________________________________________________________ 61 . s.close().refCol). c..

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

Java Technology M.Sc IT Part II ___________________________________________________________________________ _________________________________________________________________________ 63 .

These objects specify the different configurations in which the GraphicsDevice can be used. file menu contains open. The resources in this GraphicsEnvironment might be local or on a remote machine.StyledEditorKit: This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document. close and exit options c.Java Technology M.swing. Each GraphicsDevice has a number of GraphicsConfiguration objects associated with it. edit menu contains bold.text. _________________________________________________________________________ 64 . This implementation provides a default implementation which treats text as styled text and provides a minimal set of actions for editing styled text. file menu b. edit menu d. printers or image buffers and are the destination of Graphics2D drawing methods. GraphicsDevice objects can be screens. italic.Sc IT Part II ___________________________________________________________________________ Practical 08 Problem Statement: Design an editor containing following options: a. javax. 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.

toolbar. this. JMenuBar menuBar=new JMenuBar().*.event. JMenu File=new JMenu("File").Java Technology M.event.File_Close.add(Scroller. String Title=" EDITOR ".add(Button_Open).*.(screensize.*. JFileChooser fc.width / 2).NORTH).add(toolbar.File.awt. JScrollPane Scroller=new JScrollPane(text). import java.Toggle_Underline.util. //JMenu Format=new JMenu("Format").text. JMenuItem File_Open.*.Button_Color.setSize(800. import javax. import java.(getSize(). //FileInputStream fInput.getContentPane(). JMenuItem Format_FontColor. public class Editor extends JFrame { JTextPane text=new JTextPane(). this.awt. _________________________________________________________________________ 65 . import javax.setOpaque(false).event.getDefaultToolkit(). BorderLayout. import java.*.swing. import javax.undo. Button_Open=new JButton(""). import java.*. BorderLayout.awt.*.KeyEvent.event. import java. this. this.CENTER). JToolBar toolbar=new JToolBar(). import javax. public Editor() { Dimension screensize = Toolkit.Toggle_Italic.width / 2) .getContentPane(). import javax. JButton*. JToggleButton Toggle_Bold. this.*.getLocalGraphicsEnvironment(). setLocation((screensize.getScreenSize().swing. import java.*.Button_Open. GraphicsEnvironment ge=GraphicsEnvironment.swing.*.text. public boolean opened=false.height / 2) (getSize(). JMenu Edit=new JMenu("Edit").Sc IT Part II ___________________________________________________________________________ Source Code: import javax.swing.File_Exit.setLayout(new BorderLayout()).getContentPane().height / 2)). //Document doc1.575).swing.swing.

setMnemonic(KeyEvent.setMnemonic('F').setIcon(new ImageIcon("icons/underline.addSeparator(). File.setFloatable(false). File_Close.add(File_Close). Toggle_Bold. toolbar.VK_E). File_Open=new JMenuItem("Open"). //Toggle_Bold.gif")). Toggle_Italic=new JToggleButton(new StyledEditorKit.addSeparator(). toolbar. Toggle_Bold=new JToggleButton(new StyledEditorKit.VK_C).add(File).Java Technology M.setIcon(new ImageIcon("icons/bold.add(File_Exit). File_Close=new JMenuItem("Close". File_Exit=new JMenuItem("Exit").setIcon(new ImageIcon("icons/italic.add(File_Open).ItalicAction()).Sc IT Part II ___________________________________________________________________________ toolbar. toolbar.BLACK). // SETTING UP THE MENU BAR _________________________________________________________________________ 66 .setMnemonic(KeyEvent. this.addSeparator(). menuBar. Toggle_Italic.VK_O).UnderlineAction()).setMnemonic(KeyEvent.VK_C). Toggle_Underline=new JToggleButton(new StyledEditorKit.add(Edit).add(Toggle_Italic).BoldAction()). File. File_Exit.setMnemonic(KeyEvent.setText("Underline").add(Button_Color).setBackground(Color.add(Toggle_Underline).addSeparator(). Toggle_Underline.gif")).add(Format_FontColor). Button_Color=new JButton("Font Color").gif")). Button_Color. menuBar. Edit. toolbar. toolbar. // YOU CAN'T MOVE THIS TOOLBAR OVER THE FRAME File.setMnemonic(KeyEvent. toolbar. //Toggle_Italic. Edit.VK_X). File. File_Open.setText("Italic").new ImageIcon("icons/close.setJMenuBar(menuBar).gif")). File.add(Toggle_Bold). Format_FontColor. toolbar.setText("Bold"). //Toggle_Underline. Format_FontColor=new JMenuItem("Font color").

//FONT COLOR Format_FontColor.Java Technology M.setAccelerator(KeyStroke.ALT_ MASK)). // ACTION FOR OPEN FILES Button_Open.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { FontColor().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Exit().setTitle(Title). File_Exit.VK_F4.ActionEvent.getKeyStroke(KeyEvent. // ACTION FOR CLOSING APPLICATION File_Exit. } _________________________________________________________________________ 67 . } }). Editor. } }). opened=false. //ACTION FOR CLOSING FILE File_Close.this.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Open().EXIT_ON_CLOSE).Sc IT Part II ___________________________________________________________________________ this. } }).setDefaultCloseOperation(WindowConstants.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Close().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Open(). //OPEN FILE File_Open. } }).

getStyledDocument(). } }).Sc IT Part II ___________________________________________________________________________ }). } }).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { text.isBold(a). _________________________________________________________________________ 68 . // ACTION FOR UNDERLINE ACTION Toggle_Underline. AttributeSet a=doc.Java Technology M. } }).requestFocus().setSelected(bold). } }).requestFocus().getAttributes().addCaretListener(new CaretListener() { public void caretUpdate(CaretEvent e) { StyledDocument doc=text.isSelected()) Toggle_Bold.getCharacterElement(e. boolean bold = StyleConstants.getDot()1). //ADD CARET LISTENER TO THE TEXTPANE text.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { text.requestFocus(). // ACTION FOR ITALIC TEXT Toggle_Italic.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { FontColor().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { text. if (bold != Toggle_Bold. // ACTION FOR SETTING TEXT COLOR Button_Color. // ACTION FOR BOLD TEXT Toggle_Bold.

getCaretPosition().setSelected(italic). if(color!=Button_Color.isUnderline(a).setSelected(underline).getDocument(). } }). } ///// END OF: public Editor /////// // FUNCTION FOR OPEN DOCUMENT /////////////////////////// private void Open() { JFileChooser fd = new JFileChooser().Sc IT Part II ___________________________________________________________________________ boolean italic = StyleConstants.isSelected()) Toggle_Italic. }catch(Exception ex) {} SetEnable_JTextPane(). boolean underline = StyleConstants. null). if (underline != Toggle_Underline.Java Technology M. //ACTION FOR CLOSING APPLICATION addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Exit().isItalic(a). Color color=StyleConstants. str+"\n". if (italic != Toggle_Italic.getForeground(a).isSelected()) Toggle_Underline.readLine())!=null) text.setBackground(color).showOpenDialog(this). BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fd. } ////////////// FUNCTUIN FOR CLOSE WINDOW //////////////////////////////// private void Exit() _________________________________________________________________________ 69 . String str. } }).getSelectedFile()))).insertString(text. while((str=br. try{ fd.getBackground()) Button_Color.

exit(0). JOptionPane. } } else { System. } else if( confirm == JOptionPane. } } ////////////////// FUNCTION FOR CLOSING ////////////////////// private void Close() { int confirm = JOptionPane.YES_OPTION ) { //Save(). System. text.showConfirmDialog(null. "Exit Application".YES_NO_CANCEL_OPTION). "Exit Application". dispose(). } else { dispose().showConfirmDialog(null.getSelectionEnd()).selectAll(). try { text. "Would you like to save?". JOptionPane. if(confirm == JOptionPane.getSelectionStart().getDocument().YES_NO_CANCEL_OPTION).CANCEL_OPTION ) { return. "Would you like to save?".Sc IT Part II ___________________________________________________________________________ { if(opened) { int confirm = JOptionPane. if( confirm == JOptionPane.remove(text. System.Java Technology M. } catch(Exception ex) {} _________________________________________________________________________ 70 .YES_OPTION) { //Save().exit(0).text.exit(0).

white). } ///////// FUNCTION FOR ENABLING SOME TOOLBAR AND MENU ITEMS ////////////// /* private void items_enable() { Toggle_Bold. text.Sc IT Part II ___________________________________________________________________________ text. Format_FontColor. } else { text. text.setBackground(Color. } //////// FUNCTION FOR SETTING UP DISABLE JTextPane text //////////// private void SetDisable_JTextPane() { text.gray). _________________________________________________________________________ 71 . } else if(confirm == JOptionPane. } } //// FUNCTION FOR SETTING UP ENABLE JTextPane text /////// private void SetEnable_JTextPane() { text.remove(text.requestFocus(true).setBackground(Color.setEnabled(true). text.text.CANCEL_OPTION) { return.setEnabled(true).selectAll(). Toggle_Underline.setEnabled(false). text. } catch(Exception ex) {} text.gray).gray).setEnabled(true).getDocument(). Toggle_Italic.getSelectionEnd()).setEditable(false).Java Technology M.setEnabled(false).setEditable(true).setEnabled(true).setBackground(Color.setEnabled(true).setBackground(Color.setEnabled(true). File_Close. Button_Color. text. try { text.getSelectionStart().

setEnabled(false).setEnabled(false).getDocument().showDialog("Error loading L&F: " + exc).Sc IT Part II ___________________________________________________________________________ }*/ //////// FUNCTION FOR DISABLING SOME TOOLBAR AND MENU ITEMS ////////////// /*private void items_disable() { Toggle_Bold. if(color!=null) { Button_Color.setEnabled(false). "Choose Text Color".false). text.setCharacterAttributes( Button_Color.WindowsLookAndFeel". StyleConstants.} //////////////// MAIN FUNCTION /////////////////////// public static void main(String args[]) { String look="com.setBackground(color).setForeground(attr.fontColor).setLookAndFeel(look). } catch (Exception exc) { System.err. Button_Color.setEnabled(false). } text. Color fontColor=Button_Color. } public JTextPane getTextPane() {return text.setEnabled(false). _________________________________________________________________________ 72 . MutableAttributeSet attr=new SimpleAttributeSet(). } public Document getDocument() { return text.setEnabled(false).requestFocus(). Format_FontColor.this.getBackground(). Toggle_Italic. try { UIManager.Java Technology M.getBackground()).sun. Toggle_Underline. } */ /////////// FUNCTION FOR FONT COLOR /////////// private void FontColor() { Color color = JColorChooser. File_Close.

Java Technology M.Sc IT Part II ___________________________________________________________________________ } Editor mainWindow = new Editor(). } } _________________________________________________________________________ 73 . mainWindow.setVisible(true).

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

Java Technology M.Sc IT Part II ___________________________________________________________________________ _________________________________________________________________________ 75 .

sql package: Provides the API for accessing and processing data stored in a data source (usually a relational database) using the JavaTM programming language. Connection: A connection (session) with a specific database.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. JTable: The JTable is used to display and edit regular two-dimensional tables of cells. and so on.A Connection object's database is able to provide information describing its tables.Java Technology M. its stored procedures. 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. the capabilities of this connection. SQL statements are executed and results are returned within the context of a connection. its supported SQL grammar. This information is obtained with the getMetaData method. _________________________________________________________________________ 76 .

CONCUR_READ_ONLY). setVisible(true).*.sql. ResultSet rs=s. Class.getColumnCount().forName("sun. ResultSetMetaData rsmd =rs.awt.rows[][]. pack().swing. Container c=getContentPane().JdbcOdbcDriver"). col=new String[columns].Java Technology M. _________________________________________________________________________ 77 .Sc IT Part II ___________________________________________________________________________ Source Code: import java.*.*. ResultSet. import java. int n.add(reftable). } void get_data() { try { n=0.getMetaData().executeQuery("Select * from BankTable"). setTitle("Bank Database"). import javax. Statement s= con. import java. int columns=rsmd. Connection con=DriverManager.jdbc. setDefaultCloseOperation(EXIT_ON_CLOSE).event. class bank extends JFrame { JTable reftable. void UI() { reftable=new JTable(rows.col). c.createStatement (ResultSet.awt.odbc.TYPE_SCROLL _ INSENSITIVE. String col[].*.getConnection("jdbc:odbc:Bank").

next()) n++. while(rs.getColumnName(i)). int x=0. } catch(Exception e) { } } public static void main(String args[]) { bank refbank=new bank(). System.getColumnCount(). } } _________________________________________________________________________ 78 . new bank().y++) { rows[x][y]=rs. rows=new String[n][5].UI().println(n).y=0. System.out. refbank.getColumnCount()).i++) { col[i-1]=rsmd.i++.out.println(rsmd. rs.Java Technology M.println(rsmd.i<=rsmd.Sc IT Part II ___________________________________________________________________________ for(int i=1.out.beforeFirst().getString(i). refbank.i< { for(int i=1.getColumnName(i). } System. } x++.get_data(). } while(rs.

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

File: An abstract representation of file and directory pathnames. _________________________________________________________________________ 80 . The characters in the string must all be decimal digits. PreparedStatement: An object that represents a precompiled SQL statement. The resulting integer value is returned.parseInt(): Parses the string argument as a signed decimal integer.A SQL statement is precompiled and stored in a PreparedStatement object.Java Technology M. system-independent view of hierarchical pathnames. This object can then be used to efficiently execute this statement multiple times.Sc IT Part II ___________________________________________________________________________ Practical 09-B Problem Statement: Design a form to store student information along with image in a database Description: Integer.User interfaces and operating systems use system-dependent pathname strings to name files and directories. except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. This class presents an abstract.

reflabelimage.refexit.JdbcOdbcDriver"). getImg() { try { Class.reflabelcourse. reftextcourse=new JTextField().reflabelpic.reflabelname.getConnection("jdbc:odbc:ImageDSN". import java.*.Sc IT Part II ___________________________________________________________________________ Source Code: import java. reftextname=new JTextField().2)). reflabelpic=new JLabel("Image").refbutton.sql. JTextField reftextroll.*.Java Technology M.*. reflabelcourse=new JLabel("Course").refretrieve. reflabelroll=new JLabel("Roll No.event.*. c. reftext=new JPanel(new GridLayout(6.reftextname. } catch(Exception e) { } Container c=getContentPane().jdbc. class getImg extends JFrame implements ActionListener { JLabel reflabelroll. JButton refok. import java.odbc.awt."tiger"). JPanel reftext.reftextcourse. reflabelimage=new JLabel(). reftextroll=new JTextField(). _________________________________________________________________________ 81 . refok=new JButton("OK"). reflabelname=new JLabel("Name").*.swing.awt. refretrieve=new JButton("Retrieve").forName("sun.setLayout(new BorderLayout())."). import java."scott". Connection con. import javax. refexit=new JButton("Exit").

refexit.getSource()==refok) { insertdata().addActionListener(this). setVisible(true).add(reftextroll). refbutton. } public void actionPerformed(ActionEvent ae) { if(ae. c.SOUTH).add(refok).NORTH). reftext. reftext. _________________________________________________________________________ 82 . refbutton.add(reflabelname).getSource()==refexit) { System.BorderLayout.add(refretrieve). reftext.addActionListener(this). reftext. refbutton. //setResizable(false).add(refbutton.getSource()==refretrieve) { retrievedata(). reftext.add(refexit).add(reflabelcourse). pack().add(reflabelimage). } else if(ae.add(reftextcourse).add(reflabelroll). } else if(ae.add(reftextname).add(reflabelpic).addActionListener(this). reftext.Java Technology M. refretrieve. c. //setSize(300.exit(0). refok.Sc IT Part II ___________________________________________________________________________ refbutton=new JPanel(). setTitle("Student Application").200). setDefaultCloseOperation(EXIT_ON_CLOSE). reftext.add(reftext. reftext.BorderLayout.

roll).Sc IT Part II ___________________________________________________________________________ } } void insertdata() { try { int roll=Integer. String refQuery="select * from imageTable where RollNo=2". String name=reftextname.jpg"). reftextroll.Java Technology M.?.JOptionPane. ps. PreparedStatement ps=con.getText().setBinaryStream(4.createStatement().course). Statement s=con. reftextname. _________________________________________________________________________ 83 .getText()).executeUpdate().setInt( FileInputStream reffis=new FileInputStream(reffile). reftextcourse. ps. } catch(Exception e) { System."Information".?)").(int)reffile.setText(""). JOptionPane.setString(3.prepareStatement("insert into imageTable values(?.INFORMATION_MESSAGE).showMessageDialog(null.getText().?. String course=reftextcourse.setText("").length()). ps.setText(""). ps. } } void retrievedata() { try { byte imgByte[]=new byte[2048]. ps."Data Inserted".reffis.out. File reffile=new File("D:\\Hemali\\Practical\\Java\\avtaar.println(e).setString(2.

imgByte=rs.out.setText(rs. } ImageIcon ai=new ImageIcon(imgByte).Sc IT Part II ___________________________________________________________________________ ResultSet rs=s. while(rs.setText(rs. } } Output: _________________________________________________________________________ 84 .setIcon(ai). reflabelimage. { reftextroll.getBytes("Image").getString("rollno")).Java Technology M.getString("Name")).println("conn made"). System. } catch(Exception e) { } } public static void main(String args[]) { new getImg(). reftextcourse.getString("Course")).executeQuery(refQuery).setText(rs.

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

As part of its initialization. each must have been generated by different Statement objects. ResultSet: A table of data representing a database result set.A ResultSet object maintains a cursor pointing to its current row of data. which is usually generated by executing a statement that queries the database.drivers" system property. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists. it can be used in a while loop to iterate through the result set. and because it returns false when there are no more rows in the ResultSet object. Initially the cursor is positioned before the first row. Therefore. if the reading of one ResultSet object is interleaved with the reading of another. only one ResultSet object per Statement object can be open at the same time.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. Source Code: _________________________________________________________________________ 86 . Statement: The object used for executing a static SQL statement and returning the results it produces. the DriverManager class will attempt to load the driver classes referenced in the "jdbc. The next method moves the cursor to the next row. This allows a user to customize the JDBC Drivers used by their applications.Java Technology M.By default.

age_str = 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. class_str = rs. rollno_str = rs.sql. ResultSet rs.JdbcOdbcDriver").Sc IT Part II ___________________________________________________________________________ <!-.jdbc.Java Technology M.odbc. Statement s.getString(1). s = c. age_str.</b></td> </tr> <% try { Class.createStatement(). lastname_str. while( { firstname_str = rs.forName("sun.getString(4).getString(6).Create a simple java server page (JSP) for web application --> <%@page import="java. middlename_str = rs. Connection c.getString(3).getConnection("jdbc:odbc:Students"). lastname_str = rs.getString(2). %> <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 .*"%> <%! String firstname_str. c = DriverManager. rs = s. middlename_str. class_str.getString(5).executeQuery("Select * from StudentTable order by FirstName"). rollno_str.

close(). } catch(Exception e) {} %> </table> </body> </html> Output: _________________________________________________________________________ 88 .Sc IT Part II ___________________________________________________________________________ c.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.http package: The javax.servlet package: The javax. _________________________________________________________________________ 90 .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.ServletResponse res): Dispatches client requests to the protected service method. javax.servlet. There's no need to override this method.servlet. service(ServletRequest req.Java Technology M.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.

c. Class.JdbcOdbcDriver"). public class LoginForm extends HttpServlet { public void doPost(HttpServletRequest req.?)". PreparedStatement ps.d. ps=con. b=(String)req.*.HttpServletResponse res)throws IOException.getParameter("Name"). Statement st=con.Sc IT Part II ___________________________________________________________________________ Source Code: login.getParameter("Password"). // con=DriverManager.createStatement().sql.?.jdbc.getWriter().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. String Query="insert into login Values(?. Connection con. a=(String)req.*.io.setContentType("text/html").http.Java Technology M. import javax.ServletException { String a.getConnection("jdbc:odbc:TwoServletsDeptDatabase"). // if (a.equals("admin") && b.servlet. import javax. import java.prepareStatement(Query). PrintWriter out=res.servlet.e. try { res.f.*.forName("sun.equals("admin123")) { _________________________________________________________________________ 91 . int i.b.*.odbc.

println("</td></tr>"). } } } _________________________________________________________________________ 92 .getColumnCount().Java Technology M.close().i++) { out. } else { out.println("</table>"). out.println("<tr><td>").println("</body></html>").i<=num.println(ae. out.println("<html><body><table border=1 align=center><tr>"). int num=md. out. out.print("<th>"+md.getString(1).next()) { d=rs. out.getString(2). out.commit().Sc IT Part II ___________________________________________________________________________ out.executeQuery("select * from Dept").println("<b> <center>LOGIN SUCCESSFULL</center> </b><br> <br>").println("</td><td>").println("</tr>").getColumnName(i)+"</th>"). e=rs. out.getMetaData().getMessage()).println(e). for(i=1. out.html> <b>Try Again</b> </a></center>"). } con.println(f). } out. f=rs.println("<center><a href = http://localhost:8888/loginform. ResultSetMetaData md=rs.getString(3). } catch (Exception ae) { System.println("</td><td>"). out. ResultSet rs=st. out.println(d). con.out.println("<br> <br><b> <center>LOGIN UNSUCCESSFULL</center> </b><br> <br>"). } out. while(rs.

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

Java Technology M.Sc IT Part II ___________________________________________________________________________ _________________________________________________________________________ 94 .

Remote are available remotely. an interface that extends java. Any existing binding for the name is replaced. Naming. java. _________________________________________________________________________ 95 .rebind (String name.Remote: The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine.Remote obj): Rebinds the specified name to a new remote object.rmi package: Provides the Remote Method Invocation package.Sc IT Part II ___________________________________________________________________________ Practical 12 Problem Statement: Write a program to implement a Remote Procedure Call Description: java.rmi.Java Technology M. Only those methods specified in a "remote interface". UnicastRemoteObject: Used for exporting a remote object with JRMP and obtaining a stub that communicates to the remote object.rmi. Any object that is a remote object must directly or indirectly implement this interface.

java import java.*.rmi.n>0. import java. for(.Sc IT Part II ___________________________________________________________________________ Source Code: processinterface.n>0. public interface processinterface extends Remote { public int fact(int n) throws RemoteException.Java Technology M.n>0. } return (sum). import java. } public int sum(int n) throws RemoteException { int sum=0.Remote. } public int rev(int n) throws RemoteException { int rev=0.n=n/10. for(.n=n/10. public int rev(int n) throws import java. } processimplement. public class processimplement extends UnicastRemoteObject implements processinterface { processimplement() throws RemoteException{} public int fact(int n) throws RemoteException { int fact=1.) { rev=(rev*10)+(n%10). }} _________________________________________________________________________ 96 . public int sum(int n) throws RemoteException.) { sum=sum+(n%10). } return (fact).n--) { fact=fact*n. for(.rmi.rmi.RemoteException. } return (rev).server.*.rmi.

Reverse\n3.*.out. System. while(true) { System.rmi.server.rmi.. } catch(Exception e) { } } } import java. Naming. public class processserver { public static void main(String args[]) { try { processimplement pim=new processimplement(). System.Sum of Digits") import java.*.pim).in)).Java Technology M...rebind("rmi://localhost:1099/process".Factorial\n2.print("\nPlease enter a option from the above menu(Bye to exit):").println("\nWaiting for Client. public class processclient { public static void main(String args[]) { try { BufferedReader br=new BufferedReader(new InputStreamReader(System. System.out.readLine(). processinterface pi=(processinterface)Naming.lookup("rmi://localhost:1099/process").*.equalsIgnoreCase("bye")) _________________________________________________________________________ 97 . import java.println("\n\n1.out.*. String choice=br. if(choice. import java.").io.println("\n**********************Welcome to World of RMI*********************").. System..println("Server Registered").rmi...Sc IT Part II ___________________________________________________________________________ processserver.

fact(num)).println("\nThe Reverse of the number is:"+pi.out. else if(choice. else if (choice.Sc IT Part II ___________________________________________________________________________ { System. } System.out.exit(0).parseInt(br. } } catch(Exception e) { } } } _________________________________________________________________________ 98 .println("\nThe Factorial of the number is:"+pi.out.rev(num)). if(choice.println("\nThe Sum of digits of the number is:"+pi.out.print("\nEnter a number:").readLine()). int num=Integer.Java Technology M.equals("3")) System.equals("1")) System.sum(num)).equals("2")) System.

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