Sie sind auf Seite 1von 68

Java Basics

// Illustrate Java class First { public static void main ( String args[] ) { System.out.println ( "\nIntegral University" ) ; } }

Output :

// Illustrate use of classes and objects class Ar { int area ( int x , int y ) { return ( x * y ) ; } } class Area { public static void main ( String args [ ] ) { Ar ar = new Ar ( ) ; System.out.println ( "\nArea of Rectangle : " + ar.area ( 1 2) ) ; } }

Output :

// Illustrate use of constructors class Vol{ int a , b , c ; Vol ( int x , int y , int z ){ a=x; b=y; c=z; } int volume ( ) { return ( a * b * c ) ; } } class Cuboid { public static void main ( String args [ ] ) { Vol v = new Vol ( 1 , 2 , 3 ) ; System.out.println ( "\nVolume of cuboid : " + v.volume ( ) ) ; } }

Output :

// Illustrate use of command line arguments class Args { public static void main ( String args [ ] ) { int i ; for ( i = 0 ; i < args.length ; i++ ) System.out.println("Argument[" + ( i + 1 ) + "] : " + args [ i ] ); } }

Output :

// Illustrate use of Stream classes import java.io.*; class Input { public static void main ( String args [ ] ) throws IOException { int a , b ; DataInputStream ds = new DataInputStream ( System.in ) ; System.out.println ( "\nEnter first number : " ) ; a = Integer.parseInt ( ds.readLine ( ) ) ; System.out.println ( "Enter second number : " ) ; b = Integer.parseInt ( ds.readLine ( ) ) ; System.out.println ( "\nSum of numbers : " + ( a + b ) ) ; } }

Output :

Overriding
// creates a super class called Figure its defines a method called area ( ) that computes the area of an object. The program derives two subclasses from Figure. The first is Rectangle and the second is Triangle. Each of these subclasses overrides area ( ) so that it returns class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } double area() { System.out.println("Area for Figure is undefined."); return 0; } } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } class FindAreas { public static void main(String args[]) { Figure f = new Figure(10, 10); Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; figref = r; System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); figref = f; System.out.println("Area is " + figref.area()); } }

Output :

// Create the Abstract class and implements the method abstract class A { abstract void callme(); // concrete methods are still allowed in abstract classes void callmetoo() { System.out.println("This is a concrete method."); } } class B extends A { void callme() { System.out.println("B's implementation of callme."); } } class AbstractDemo { public static void main(String args[]) { B b = new B(); b.callme(); b.callmetoo(); } }

Output :

// Create a program that illustrates the Method Overloading class OverloadDemo { void test() { System.out.println("No parameters"); } void test(int a) { System.out.println("a: " + a); } void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } }

Output :

Inheritance
// A simple example of inheritance.

class A { int i, j; void showij() { System.out.println("i and j: " + i + " " + j); } } class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i+j+k)); } } class SimpleInheritance { public static void main(String args[]) { A superOb = new A(); B subOb = new B(); superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println(); subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); } }

10

Output:

11

// A Simple inheritance Using super to Call Superclass Constructors

class Box { private double width; private double height; private double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } // BoxWeight now fully implements all constructors. class BoxWeight extends Box { double weight; // weight of box // construct clone of an object BoxWeight(BoxWeight ob) { // pass object to constructor super(ob); weight = ob.weight; } // constructor when all parameters are specified BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } BoxWeight() { super(); weight = -1; } // constructor used when cube is created BoxWeight(double len, double m) { super(len); weight = m; } } class DemoSuper {

12

public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); BoxWeight mybox3 = new BoxWeight(); // default BoxWeight mycube = new BoxWeight(3, 2); BoxWeight myclone = new BoxWeight(mybox1); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); System.out.println(); vol = mybox3.volume(); System.out.println("Volume of mybox3 is " + vol); System.out.println("Weight of mybox3 is " + mybox3.weight); System.out.println(); vol = myclone.volume(); System.out.println("Volume of myclone is " + vol); System.out.println("Weight of myclone is " + myclone.weight); System.out.println(); vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); System.out.println("Weight of mycube is " + mycube.weight); System.out.println(); } }

Output:

13

Interfaces
// Creates an Interface interface Area { int calc_area ( int a , int b ) ; } class Rect implements Area { public int calc_area ( int a , int b ) { return ( a * b ) ; } } class Fig { public static void main ( String args [ ] ) { Rect r = new Rect ( ) ; System.out.println ( "\nArea : " + r.calc_area ( 1 , 2 ) ) ; } }

Output :

14

Packages
// Creates a package package Mypack ; public class Area { public void show ( int a , int b ) { System.out.println( "\nArea : " + ( a * b ) ) ; } }

// Implements Package

import Mypack.* ; class Rect { public static void main ( String args[ ] ) { Area ar = new Area ( ) ; ar.show ( 1 , 2 ) ; } }

Output :

15

Exception Handling
// Create a program using try and catch statements class trycatch { public static void main(String [] ar) { try { int num1=0,num2 =5; int num3 = num2/num1; System.out.println(" the result = " +num3); } catch (ArithmeticException e) { System.out.println("Division by zero is performed"); } }

Output :

16

// Create a program using try and multiple catch statements

class trymcatch { public static void main(String [] ar) { try { int arr[]={1,1}; int num1=0,num2 =5; System.out.println(num2/arr[2]); int num3 = num2/num1; System.out.println(" the result = " +num3); } catch (ArithmeticException e) { System.out.println("Division by zero is performed"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error out of bound....."); } catch (Exception e) { System.out.println("some Other error"); } } }

Output :

17

// Create your own exception using throw class throwdemo { static void demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc"); throw e; } } public static void main(String ar[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println(e); } } }

Output :

18

Multithreaded programming
// Creating thread using the Thread class

class A extends Thread { public void run() { for (int i=0;i<10;i++) System.out.println("thread A"); } } class B extends Thread { public void run() { for (int i=0;i<10;i++) System.out.println("thread b"); } } class threademo { public static void main(String ar[]) { new A().start(); new B().start(); } }

Output :

19

// Creating threads using Runnable interface

class x implements Runnable { public void run() { for( int i=0;i<=10;i++) { System.out.println("thread x"); } } } class runnabledemo { public static void main(String ar[]) { x runnable = new x(); Thread th = new Thread (runnable); th.start(); }

Output :

20

// Create a program set the thread priorities class B extends Thread { public void run() { for (int i=0;i<10;i++) System.out.println("thread b"); } } class threadpriority { public static void main(String ar[]) { A th1 = new A(); B th2 = new B(); th1.setPriority(Thread.MAX_PRIORITY); th2.setPriority(Thread.MIN_PRIORITY); th2.start(); th1.start(); } }

Output :

21

Applets

// Create the Applet that display the text import java.awt.*; import java.applet.*; /* <applet code="SimpleApplet" width=200 height=60> </applet> */ public class SimpleApplet extends Applet { public void paint(Graphics g) { g.drawString("A Simple Applet", 20, 20); } }

Output :

22

// Create the Appletlife class that show the various stages of applet life cycle import java.awt.*; import java.applet.*; /* <applet code="Appletlife" width=300 height=100> </applet> */ public class Appletlife extends Applet { String str = "Hello ! "; public void init() { str = str + " init() "; } public void start() { str = str + " start() } public void stop() { } public void destroy() { } public void paint(Graphics g) { str = str + " paint() "; g.drawString(str,30,50); } }

";

Output :

23

Event Handling
// Demonstrate the mouse event handlers.

import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="MouseEvents" width=300 height=100> </applet> */ public class MouseEvents extends Applet implements MouseListener, MouseMotionListener { String msg = ""; int mouseX = 0, mouseY = 0; // coordinates of mouse public void init() { addMouseListener(this); addMouseMotionListener(this); } // Handle mouse clicked. public void mouseClicked(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse clicked."; repaint(); } // Handle mouse entered. public void mouseEntered(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse entered."; repaint(); } // Handle mouse exited. public void mouseExited(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse exited."; repaint(); } // Handle button pressed. public void mousePressed(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Down"; repaint(); } // Handle button released. public void mouseReleased(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Up"; repaint();

24

} // Handle mouse dragged. public void mouseDragged(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "*"; showStatus("Dragging mouse at " + mouseX + ", " + mouseY); repaint(); } // Handle mouse moved. public void mouseMoved(MouseEvent me) { // show status showStatus("Moving mouse at " + me.getX() + ", " + me.getY()); } // Display msg in applet window at current X,Y location. public void paint(Graphics g) { g.drawString(msg, mouseX, mouseY); } }

Output :

25

// Demonstrate the key event handlers

import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="SimpleKey" width=300 height=100> </applet> */ public class SimpleKey extends Applet implements KeyListener { String msg = ""; int X = 10, Y = 20; // output coordinates public void init() { addKeyListener(this); requestFocus(); // request input focus } public void keyPressed(KeyEvent ke) { showStatus("Key Down"); } public void keyReleased(KeyEvent ke) { showStatus("Key Up"); } public void keyTyped(KeyEvent ke) { msg += ke.getKeyChar(); repaint(); } // Display keystrokes. public void paint(Graphics g) { g.drawString(msg, X, Y); } }

Output :

26

AWT Graphics and Controls


// Draw rectangles

import java.awt.*; import java.applet.*; /* <applet code="Rectangles" width=300 height=200> </applet> */ public class Rectangles extends Applet { public void paint(Graphics g) { g.drawRect(10, 10, 60, 50); g.fillRect(100, 10, 60, 50); g.drawRoundRect(190, 10, 60, 50, 15, 15); g.fillRoundRect(70, 90, 140, 100, 30, 40); } }

Output :

27

// Draw Ellipses

import java.awt.*; import java.applet.*; /* <applet code="Ellipses" width=300 height=200> </applet> */ public class Ellipses extends Applet { public void paint(Graphics g) { g.drawOval(10, 10, 50, 50); g.fillOval(100, 10, 75, 50); g.drawOval(190, 10, 90, 30); g.fillOval(70, 90, 140, 100); } }

Output :

28

// Draw Arcs

import java.awt.*; import java.applet.*; /* <applet code="Arcs" width=300 height=200> </applet> */ public class Arcs extends Applet { public void paint(Graphics g) { g.drawArc(10, 40, 70, 70, 0, 75); g.fillArc(100, 40, 70, 70, 0, 75); g.drawArc(10, 100, 70, 80, 0, 175); g.fillArc(100, 100, 70, 90, 0, 270); g.drawArc(200, 80, 80, 80, 0, 180); } }

Output :

29

// Draw Polygon

import java.awt.*; import java.applet.*; /* <applet code="HourGlass" width=230 height=210> </applet> */ public class HourGlass extends Applet { public void paint(Graphics g) { int xpoints[] = {30, 200, 30, 200, 30}; int ypoints[] = {30, 30, 200, 200, 30}; int num = 5; g.drawPolygon(xpoints, ypoints, num); } }

Output :

30

// Demonstrate Labels

import java.awt.*; import java.applet.*; /* <applet code="LabelDemo" width=300 height=200> </applet> */ public class LabelDemo extends Applet { public void init() { Label one = new Label("One"); Label two = new Label("Two"); Label three = new Label("Three"); // add labels to applet window add(one); add(two); add(three); } }

Output :

31

// Demonstrate Buttons with Event Handling import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="ButtonDemo" width=250 height=150> </applet> */ public class ButtonDemo extends Applet implements ActionListener { String msg = ""; Button yes, no, maybe; public void init() { yes = new Button("Yes"); no = new Button("No"); maybe = new Button("Undecided"); add(yes); add(no); add(maybe); yes.addActionListener(this); no.addActionListener(this); maybe.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String str = ae.getActionCommand(); if(str.equals("Yes")) { msg = "You pressed Yes."; } else if(str.equals("No")) { msg = "You pressed No."; } else { msg = "You pressed Undecided."; } repaint(); } public void paint(Graphics g) { g.drawString(msg, 6, 100); } }

32

Output :

// Demonstrate check boxes with Event Handling

import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="CheckboxDemo" width=250 height=200> </applet> */ public class CheckboxDemo extends Applet implements ItemListener {

33

String msg = ""; Checkbox Win98, winNT, solaris, mac; public void init() { Win98 = new Checkbox("Windows 98/XP", null, true); winNT = new Checkbox("Windows NT/2000"); solaris = new Checkbox("Solaris"); mac = new Checkbox("MacOS"); add(Win98); add(winNT); add(solaris); add(mac); Win98.addItemListener(this); winNT.addItemListener(this); solaris.addItemListener(this); mac.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint(); } // Display current state of the check boxes. public void paint(Graphics g) { msg = "Current state: "; g.drawString(msg, 6, 80); msg = " Windows 98/XP: " + Win98.getState(); g.drawString(msg, 6, 100); msg = " Windows NT/2000: " + winNT.getState(); g.drawString(msg, 6, 120); msg = " Solaris: " + solaris.getState(); g.drawString(msg, 6, 140); msg = " MacOS: " + mac.getState(); g.drawString(msg, 6, 160); } }

Output :

34

// Demonstrate Choice lists. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="ChoiceDemo" width=300 height=180>

35

</applet> */ public class ChoiceDemo extends Applet implements ItemListener { Choice os, browser; String msg = ""; public void init() { os = new Choice(); browser = new Choice(); // add items to os list os.add("Windows 98/XP"); os.add("Windows NT/2000"); os.add("Solaris"); os.add("MacOS"); // add items to browser list browser.add("Netscape 3.x"); browser.add("Netscape 4.x"); browser.add("Netscape 5.x"); browser.add("Netscape 6.x"); browser.add("Internet Explorer 4.0"); browser.add("Internet Explorer 5.0"); browser.add("Internet Explorer 6.0"); browser.add("Lynx 2.4"); browser.select("Netscape 4.x"); // add choice lists to window add(os); add(browser); // register to receive item events os.addItemListener(this); browser.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint(); } // Display current selections. public void paint(Graphics g) { msg = "Current OS: "; msg += os.getSelectedItem(); g.drawString(msg, 6, 120); msg = "Current Browser: "; msg += browser.getSelectedItem(); g.drawString(msg, 6, 140); } }

Output :

36

// Demonstrate Lists with Event Handling

import java.awt.*;

37

import java.awt.event.*; import java.applet.*; /* <applet code="ListDemo" width=300 height=180> </applet> */ public class ListDemo extends Applet implements ActionListener { List os, browser; String msg = ""; public void init() { os = new List(4, true); browser = new List(4, false); os.add("Windows 98/XP"); os.add("Windows NT/2000"); os.add("Solaris"); os.add("MacOS"); // add items to browser list browser.add("Netscape 3.x"); browser.add("Netscape 4.x"); browser.add("Netscape 5.x"); browser.add("Netscape 6.x"); browser.add("Internet Explorer 4.0"); browser.add("Internet Explorer 5.0"); browser.add("Internet Explorer 6.0"); browser.add("Lynx 2.4"); browser.select(1); // add lists to window add(os); add(browser); // register to receive action events os.addActionListener(this); browser.addActionListener(this); } public void actionPerformed(ActionEvent ae) { repaint(); } // Display current selections. public void paint(Graphics g) { int idx[]; msg = "Current OS: "; idx = os.getSelectedIndexes(); for(int i=0; i<idx.length; i++) msg += os.getItem(idx[i]) + " "; g.drawString(msg, 6, 120); msg = "Current Browser: "; msg += browser.getSelectedItem(); g.drawString(msg, 6, 140); } }

Output :

38

// Demonstrate text field with Event Handling

import java.awt.*;

39

import java.awt.event.*; import java.applet.*; /*<applet code="TextFieldDemo" width=380 height=150> </applet> */ public class TextFieldDemo extends Applet implements ActionListener { TextField name, pass; public void init() { Label namep = new Label("Name: ", Label.RIGHT); Label passp = new Label("Password: ", Label.RIGHT); name = new TextField(12); pass = new TextField(8); pass.setEchoChar('?'); add(namep); add(name); add(passp); add(pass); // register to receive action events name.addActionListener(this); pass.addActionListener(this); } // User pressed Enter. public void actionPerformed(ActionEvent ae) { repaint(); } public void paint(Graphics g) { g.drawString("Name: " + name.getText(), 6, 60); g.drawString("Selected text in name: "+ name.getSelectedText(), 6, 80); g.drawString("Password: " + pass.getText(), 6, 100); } }

Output:

Applet : Layout Managers

40

// Create a GUI program using FlowLayout Manager

public class flowlayoutdemo extends Applet { public void init() { setLayout(new FlowLayout(FlowLayout.CENTER)); Button a,b,c; a = new Button("Add"); b = new Button("Update"); c = new Button("Delete"); add(a); add(b); add(c); } } /*<applet code = flowlayoutdemo width=300 height=200> </applet> */

Output :

// Create a GUI program using BorderLayout Manager

import java.awt.*;

41

import java.applet.*; public class borderlayoutdemo extends Applet { public void init() { setLayout(new BorderLayout()); Button a,b,c,d; a = new Button("Add"); b = new Button("Update"); c = new Button("Delete"); d = new Button("Reset"); add(a,BorderLayout.EAST); add(b,BorderLayout.NORTH); add(c,BorderLayout.SOUTH); add(d,BorderLayout.WEST); } } /*<applet code = borderlayoutdemo width=300 height=200> </applet> */

Output :

// Create a GUI program using GridLayout Manager

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

42

public class gridlayoutdemo extends Applet { public void init() { setLayout(new GridLayout(2,2)); Button a,b,c,d; a = new Button("Add"); b = new Button("Update"); c = new Button("Delete"); d = new Button("Reset"); add(a); add(b); add(c); add(d); } }

Output :

43

Swings
// Customer Registration Form using Swing extends by JApplet

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class swingDemo extends JApplet { JTextField txt1=new JTextField(); JTextField txt2=new JTextField(); JTextField txt3=new JTextField(); JTextField txt4=new JTextField(); JLabel lb1=new JLabel("Customer No:"); JLabel lb2=new JLabel("Name:"); JLabel lb3=new JLabel("Address"); JLabel lb4=new JLabel("Phone No:"); JPanel p1=new JPanel(); JButton btn1=new JButton("Reset"); JButton btn2=new JButton("Save"); JButton btn3=new JButton("Update"); JButton btn4=new JButton("Show"); JButton btn5=new JButton("Delete"); JPanel p2=new JPanel(); JPanel p3=new JPanel(); JPanel p4=new JPanel(); JLabel lbl5=new JLabel("Customer No:"); JComboBox cb=new JComboBox(); JPanel p5=new JPanel(); JPanel p6=new JPanel(); JPanel p7=new JPanel(); JPanel p8=new JPanel(); JOptionPane op; public swingDemo() { p3.add(lbl5); p3.add(cb); p6.add(btn4); p6.add(btn5); p3.setLayout(new p6.setLayout(new p7.setLayout(new p7.add(p3); p7.add(p6); p8.add(p7); p8.setLayout(new p2.add(btn1); p2.add(btn2); p2.add(btn3); p1.add(lb1); p1.add(txt1); p1.add(lb2); p1.add(txt2);

GridLayout(1,2)); GridLayout(1,2)); GridLayout(2,1));

FlowLayout());

44

p1.add(lb3); p1.add(txt3); p1.add(lb4); p1.add(txt4); //p1.add(lb1); p1.setLayout(new GridLayout(4,2)); p2.setLayout(new FlowLayout()); //p3.setLayout(new GridLayout(2,2)); p4.add(p1); p4.add(p2); p4.setLayout(new GridLayout(2,1)); getContentPane().setLayout(new FlowLayout()); p5.setLayout(new GridLayout(1,2)); p5.add(p4); p5.add(p8); getContentPane().add(p5); //getContentPane().add(p3); } public void init() { } } /* <applet code=swingDemo height=200 width=500> </applet> */

Output :

45

// Customer Registration Form using Swing extends by JFrame

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class swingDemo1 extends JFrame { JTextField txt1=new JTextField(); JTextField txt2=new JTextField(); JTextField txt3=new JTextField(); JTextField txt4=new JTextField(); JLabel lb1=new JLabel("Customer No:"); JLabel lb2=new JLabel("Name:"); JLabel lb3=new JLabel("Address"); JLabel lb4=new JLabel("Phone No:"); JPanel p1=new JPanel(); JButton btn1=new JButton("Reset"); JButton btn2=new JButton("Save"); JButton btn3=new JButton("Update"); JButton btn4=new JButton("Show"); JButton btn5=new JButton("Delete"); JPanel p2=new JPanel(); JPanel p3=new JPanel(); JPanel p4=new JPanel(); JLabel lbl5=new JLabel("Customer No:"); JComboBox cb=new JComboBox(); JPanel p5=new JPanel(); JPanel p6=new JPanel(); JPanel p7=new JPanel(); JPanel p8=new JPanel(); JOptionPane op; public swingDemo1() { p3.add(lbl5); p3.add(cb); p6.add(btn4); p6.add(btn5); p3.setLayout(new GridLayout(1,2)); p6.setLayout(new GridLayout(1,2)); p7.setLayout(new GridLayout(2,1)); p7.add(p3); p7.add(p6); p8.add(p7); p8.setLayout(new FlowLayout()); p2.add(btn1); p2.add(btn2); p2.add(btn3); p1.add(lb1); p1.add(txt1); p1.add(lb2); p1.add(txt2); p1.add(lb3); p1.add(txt3); p1.add(lb4); p1.add(txt4); //p1.add(lb1); p1.setLayout(new GridLayout(4,2));

46

p2.setLayout(new FlowLayout()); p4.add(p1); p4.add(p2); p4.setLayout(new GridLayout(2,1)); getContentPane().setLayout(new FlowLayout()); p5.setLayout(new GridLayout(1,2)); p5.add(p4); p5.add(p8); getContentPane().add(p5); } public static void main(String arr[]) { swingDemo1 sd=new swingDemo1(); sd.setVisible(true); sd.setSize(200,500); } }

Output :

47

// Implementing JButton import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JButtonDemo2 { JFrame jtfMainFrame; JButton jbnButton1, jbnButton2; JTextField jtfInput; JPanel jplPanel; public JButtonDemo2() { jtfMainFrame = new JFrame("Which Button Demo"); jtfMainFrame.setSize(50, 50); jbnButton1 = new JButton("Button 1"); jbnButton2 = new JButton("Button 2"); jtfInput = new JTextField(20); jplPanel = new JPanel(); jbnButton1.setMnemonic(KeyEvent.VK_I); //Set ShortCut Keys jbnButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jtfInput.setText("Button 1!"); } } ); jbnButton2.setMnemonic(KeyEvent.VK_I); jbnButton2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jtfInput.setText("Button 2!"); } }); jplPanel.setLayout(new FlowLayout()); jplPanel.add(jtfInput); jplPanel.add(jbnButton1); jplPanel.add(jbnButton2); jtfMainFrame.getContentPane().add(jplPanel, BorderLayout.CENTER); jtfMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jtfMainFrame.pack(); jtfMainFrame.setVisible(true); } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName( ); } catch (Exception e) { } JButtonDemo2 application = new JButtonDemo2(); } }

48

Output :

49

// Implementing JLabel import import import import import import import java.awt.GridLayout; java.awt.event.WindowAdapter; java.awt.event.WindowEvent; javax.swing.JLabel; javax.swing.JPanel; javax.swing.JFrame; javax.swing.ImageIcon;

public class JlabelDemo extends JPanel { JLabel jlbLabel1, jlbLabel2, jlbLabel3; public JlabelDemo() { ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG","My Website"); // Creating an Icon setLayout(new GridLayout(3, 1)); // 3 rows, 1 column Panel having Grid Layout jlbLabel1 = new JLabel("Image with Text", icon, JLabel.CENTER); // We can position of the text, relative to the icon: jlbLabel1.setVerticalTextPosition(JLabel.BOTTOM); jlbLabel1.setHorizontalTextPosition(JLabel.CENTER); jlbLabel2 = new JLabel("Text Only Label"); jlbLabel3 = new JLabel(icon); // Label of Icon Only // Add labels to the Panel add(jlbLabel1); add(jlbLabel2); add(jlbLabel3); } public static void main(String[] args) { JFrame frame = new JFrame("jLabel Usage Demo"); frame.addWindowListener(new WindowAdapter() { // Shows code to Add Window Listener public void windowClosing(WindowEvent e) { System.exit(0); } } frame.setContentPane(new JlabelDemo()); frame.pack(); frame.setVisible(true); } }

50

Output :

51

// Implementing JCheckBox import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JCheckBoxDemo extends JPanel { JCheckBox JCheckBox JCheckBox JCheckBox jcbChin; jcbGlasses; jcbHair; jcbTeeth;

StringBuffer choices; JLabel jlbPicture; CheckBoxListener myListener = null; public JCheckBoxDemo() { myListener = new CheckBoxListener(); jcbChin = new JCheckBox("Chin"); jcbChin.setMnemonic(KeyEvent.VK_C); jcbChin.setSelected(true); jcbChin.addItemListener(myListener); jcbGlasses = new JCheckBox("Glasses"); jcbGlasses.setMnemonic(KeyEvent.VK_G); jcbGlasses.setSelected(true); jcbGlasses.addItemListener(myListener); jcbHair = new JCheckBox("Hair"); jcbHair.setMnemonic(KeyEvent.VK_H); jcbHair.setSelected(true); jcbHair.addItemListener(myListener); jcbTeeth = new JCheckBox("Teeth"); jcbTeeth.setMnemonic(KeyEvent.VK_T); jcbTeeth.setSelected(true); jcbTeeth.addItemListener(myListener); choices = new StringBuffer("caght"); jlbPicture = new JLabel(new ImageIcon("geek-" + choices.toString().trim() + ".gif")); jlbPicture.setToolTipText(choices.toString().trim()); JPanel jplCheckBox = new JPanel(); jplCheckBox.setLayout(new GridLayout(0, 1)); jplCheckBox.add(jcbChin); jplCheckBox.add(jcbGlasses); jplCheckBox.add(jcbHair); jplCheckBox.add(jcbTeeth); setLayout(new BorderLayout());

52

add(jplCheckBox, BorderLayout.WEST); add(jlbPicture, BorderLayout.CENTER); setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); } class CheckBoxListener implements ItemListener { public void itemStateChanged(ItemEvent e) { int index = 0; char c = '-'; Object source = e.getSource(); if (source == jcbChin) { index = 0; c = 'c'; } else if (source == jcbGlasses) { index = 1; c = 'g'; } else if (source == jcbHair) { index = 2; c = 'h'; } else if (source == jcbTeeth) { index = 3; c = 't'; } if (e.getStateChange() == ItemEvent.DESELECTED) c = '-'; choices.setCharAt(index, c); jlbPicture.setIcon(new ImageIcon("geek-" + choices.toString().trim() + ".gif")); jlbPicture.setToolTipText(choices.toString()); } }

public static void main(String s[]) { JFrame frame = new JFrame("JCheckBox Usage Demo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } frame.setContentPane(new JCheckBoxDemo()); frame.pack(); frame.setVisible(true); } }

53

Output :

54

// Implement JMenu import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JMenuDemo implements ActionListener, ItemListener { JTextArea jtAreaOutput; JScrollPane jspPane; public JMenuBar createJMenuBar() { JMenuBar mainMenuBar; JMenu menu1, menu2, submenu; JMenuItem plainTextMenuItem, textIconMenuItem, iconMenuItem, subMenuItem; JRadioButtonMenuItem rbMenuItem; JCheckBoxMenuItem cbMenuItem; ImageIcon icon = createImageIcon("jmenu.jpg"); mainMenuBar = new JMenuBar(); menu1 = new JMenu("Menu 1"); menu1.setMnemonic(KeyEvent.VK_M); mainMenuBar.add(menu1); plainTextMenuItem = new JMenuItem("Menu item with Plain Text", KeyEvent.VK_T); plainTextMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK)); plainTextMenuItem.addActionListener(this); menu1.add(plainTextMenuItem); textIconMenuItem = new JMenuItem("Menu Item with Text & Image",icon); textIconMenuItem.setMnemonic(KeyEvent.VK_B); textIconMenuItem.addActionListener(this); menu1.add(textIconMenuItem); iconMenuItem = new JMenuItem(icon); iconMenuItem.setMnemonic(KeyEvent.VK_D); iconMenuItem.addActionListener(this); menu1.add(iconMenuItem); menu1.addSeparator(); ButtonGroup itemGroup = new ButtonGroup(); rbMenuItem = new JRadioButtonMenuItem("Menu Item with Radio Button"); rbMenuItem.setSelected(true); rbMenuItem.setMnemonic(KeyEvent.VK_R); itemGroup.add(rbMenuItem); rbMenuItem.addActionListener(this); menu1.add(rbMenuItem); rbMenuItem = new JRadioButtonMenuItem("Menu Item 2 with Radio Button"); itemGroup.add(rbMenuItem); rbMenuItem.addActionListener(this); menu1.add(rbMenuItem); menu1.addSeparator(); cbMenuItem = new JCheckBoxMenuItem("Menu Item with check box"); cbMenuItem.setMnemonic(KeyEvent.VK_C); cbMenuItem.addItemListener(this); menu1.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Menu Item 2 with check box"); cbMenuItem.addItemListener(this);

55

menu1.add(cbMenuItem); menu1.addSeparator(); submenu = new JMenu("Sub Menu"); submenu.setMnemonic(KeyEvent.VK_S); subMenuItem = new JMenuItem("Sub MenuItem 1"); subMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.CTRL_MASK)); subMenuItem.addActionListener(this); submenu.add(subMenuItem); subMenuItem = new JMenuItem("Sub MenuItem 2"); submenu.add(subMenuItem); subMenuItem.addActionListener(this); menu1.add(submenu); menu2 = new JMenu("Menu 2"); menu2.setMnemonic(KeyEvent.VK_N); mainMenuBar.add(menu2); return mainMenuBar; } public Container createContentPane() { JPanel jplContentPane = new JPanel(new BorderLayout()); jplContentPane.setLayout(new BorderLayout()); jplContentPane.setOpaque(true); jtAreaOutput = new JTextArea(5, 30); jtAreaOutput.setEditable(false); jspPane = new JScrollPane(jtAreaOutput); jplContentPane.add(jspPane, BorderLayout.CENTER); return jplContentPane; } protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = JMenuDemo.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn't find image file: " + path); return null; } } private static void createGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("JMenu Usage Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuDemo app = new JMenuDemo(); frame.setJMenuBar(app.createJMenuBar()); frame.setContentPane(app.createContentPane()); frame.setSize(500, 300); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { JMenuItem source = (JMenuItem) (e.getSource());

56

String s = "Menu Item source: " + source.getText( )+ " (an instance of " + getClassName(source) + ")"; jtAreaOutput.append(s + "\n"); jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument().getLength()); } public void itemStateChanged(ItemEvent e) { JMenuItem source = (JMenuItem) (e.getSource()); String s = "Menu Item source: "+ source.getText()+ " (an instance of " + getClassName(source)+ ")"+ "\n"+ " State of check Box: "+ ((e.getStateChange() == ItemEvent.SELECTED) ? "selected": "unselected"); jtAreaOutput.append(s + "\n"); jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument().getLength()); } protected String getClassName(Object o) { String classString = o.getClass().getName(); int dotIndex = classString.lastIndexOf("."); return classString.substring(dotIndex + 1); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createGUI(); } } ); } }

Output :

57

// Implementing JTabbedPane import import import import import import import javax.swing.JTabbedPane; javax.swing.ImageIcon; javax.swing.JLabel; javax.swing.JPanel; javax.swing.JFrame; java.awt.*; java.awt.event.*;

public class JTabbedPaneDemo extends JPanel { public JTabbedPaneDemo() { ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG"); JTabbedPane jtbExample = new JTabbedPane(); JPanel jplInnerPanel1 = createInnerPanel("Tab 1 Contains Tooltip and Icon"); jtbExample.addTab("One", icon, jplInnerPanel1, "Tab 1"); jtbExample.setSelectedIndex(0); JPanel jplInnerPanel2 = createInnerPanel("Tab 2 Contains Icon only"); jtbExample.addTab("Two", icon, jplInnerPanel2); JPanel jplInnerPanel3 = createInnerPanel("Tab 3 Contains Tooltip and Icon"); jtbExample.addTab("Three", icon, jplInnerPanel3, "Tab 3"); JPanel jplInnerPanel4 = createInnerPanel("Tab 4 Contains Text only"); jtbExample.addTab("Four", jplInnerPanel4); setLayout(new GridLayout(1, 1)); add(jtbExample); } protected JPanel createInnerPanel(String text) { JPanel jplPanel = new JPanel(); JLabel jlbDisplay = new JLabel(text); jlbDisplay.setHorizontalAlignment(JLabel.CENTER); jplPanel.setLayout(new GridLayout(1, 1)); jplPanel.add(jlbDisplay); return jplPanel; } public static void main(String[] args) { JFrame frame = new JFrame("TabbedPane Source Demo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } frame.getContentPane().add(new JTabbedPaneDemo(),BorderLayout.CENTER); frame.setSize(400, 125); frame.setVisible(true); } }

58

Output :

59

JDBC
// Implement JDBC import java.sql.*; import java.io.*; public class jdbcdemo { public static void main(String[] args) { Connection cn; Statement st; ResultSet rs; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); cn=DriverManager.getConnection("jdbc:odbc:stu"); st=cn.createStatement(); rs=st.executeQuery("select * from stu"); while(rs.next()) { System.out.print(rs.getString("rollno")); System.out.print(" "); System.out.print(rs.getString("name")); System.out.println(); } } catch (Exception ex) { System.out.println(" database not connected"); } } }

Output :

60

Servlets
// Illustrate Servlets import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); } }

Output :

61

// To pass Request parameters through a Servelet import import import import java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class RequestParamExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("GET Request. No Form Data Posted"); } public void doPost(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException { Enumeration e = request.getParameterNames(); PrintWriter out = res.getWriter (); while (e.hasMoreElements()) { String name = (String)e.nextElement(); String value = request.getParameter(name); out.println(name + " = " + value); } }

Output :

62

Remote Method Invocation


// Server Application import java.rmi.*; import java.rmi.server.*; public class hserver extends UnicastRemoteObject implements Hello { public hserver ( ) throws RemoteException { super ( ) ; } public String Hello ( ) { System.out.println ( "Invocation Succesful " ) ; return "Hello form RMI Server" ; } public static void main ( String args[ ] ) { try { hserver hs = new hserver ( ) ; Naming.rebind("Server",hs); System.out.println("Object is registered"); System.out.println("Server is waiting for client request"); } catch(Exception e) { System.out.println( "Error : " + e.getMessage ( ) ) ; } } }

// Remote Interface import java.rmi.*; public interface Hello extends Remote { public String Hello( ) throws RemoteException; }

63

// Client Application import java.rmi.*; public class hclient { public String msg = " " ; static Hello h = null ; public static void main(String args[]) { try { h = ( Hello )Naming.lookup("Server"); System.out.println("Client Hello"); System.out.println( "Server" + h.Hello( ) ); } catch(Exception e) { System.out.println( "Error" + e.getMessage ( ) ) ; } } }

Output : Server Side

64

Client Side

65

Java Server Pages


// Create a JSP page <%@ page import = "num.NumberGuessBean" %> <jsp:useBean id="numguess" class="num.NumberGuessBean" scope="session"/> <jsp:setProperty name="numguess" property="*"/> <html> <head><title>Number Guess</title></head> <body bgcolor="white"> <font size=4> <% if (numguess.getSuccess()) { %> Congratulations! You got it. And after just <%= numguess.getNumGuesses() %> tries.<p> <% numguess.reset(); %> Care to <a href="numguess.jsp">try again</a>? <% } else if (numguess.getNumGuesses() == 0) { %> Welcome to the Number Guess game.<p> I'm thinking of a number between 1 and 100.<p> <form method=get> What's your guess? <input type=text name=guess> <input type=submit value="Submit"> </form> <% } else { %> Good guess, but nope. Try <b><%= numguess.getHint() %></b>. You have made <%= numguess.getNumGuesses() %> guesses.<p> I'm thinking of a number between 1 and 100.<p> <form method=get> What's your guess? <input type=text name=guess> <input type=submit value="Submit"> </form> <% } %>

66

Output :

67

68