You are on page 1of 105

DMI COLLEGE OF ENGINEERING

(Affiliated to Anna University Chennai-600025)

PALANCHUR, CHENNAI - 602103.

DEPARTMENT OF INFORMATION TECHNOLOGY B.Tech Degree Examination

IT 2305- JAVA PROGRAMMING LAB LAB MANUAL


V - SEMESTER 2011-2012

INDEX EX.NO NAME OF THE EXPERIMENT 1 PAGE NO

1 2 3 4 5 6 7 8 9 10 11 12

JAVA PACKAGE WITH SIMPLE STACK AND QUEUE CLASS COMPLEX NUMBER MANIPULATION DATE CLASS SIMILAR TO JAVA.UTIL PACKAGE IMPLEMENTING DYNAMIC POLYMORPHISM IN JAVA JAVA INTERFACE FOR ADT STACK DNA FILE CREATION DEVELOPING A SIMPLE PAINT LIKE PROGRAM USING APPLET DEVELOPING A SCIENTIFIC CALCULATOR DEVELOPING A TEMPLATE FOR LINKED LIST DEVELOP A MULTI THREADED PRODUCER CONSUMER APLICATION GENERATING PRIME NUMBERS AND FIBONACCI SERIES MULTITHREADED GUI APPLICATION

3 13 18 23 29 37 44 55 82 86 91 97

Ex.No:1 CLASS AIM:

JAVA PACKAGE WITH SIMPLE STACK AND QUEUE

To write program to develop a java package for the stack and queue classes. ALGORITHM: Stack class: 1. Start the program. 2. Create a class with the class name Stack to demonstrate the application of the stack. 3. Create a constructor to initialize the top value of the stack. 4. Define the method push (). 5. If the top value is equal to 9, print stack is full. Otherwise push the value in to the stack. 6. Define the method pop (). 7. If the top value is less than zero, print stack underflow. Otherwise decrement the value of the stack. 8. Create a main class with the class name teststack. 9. Create an object for the class Stack to call the methods define inside that class. 10. Call the methods push () & pop () using the objects. 11. Stop the program.

Queue class: 3

1. Start the program. 2. Create a class with the name queue implement to demonstrate about a application of queue. 3. Declare a variable str as string and num as integer. 4. Create an object for a class queue implement. 5. Create a constructor to of the Linked List class. This class is used by importing the java.util. package. This constructor is used for constructing an empty list. 6. Get the value from the command line by using a variable str. 7. Using try and catch block to handle exception using IOException. 8. Print the elements in the queue using the statement. 9. Stop the program.

Stack class: package SQ; import java.io.*; /** * This class demonstrates about the application of Statck * @author Herbert Schildt * @version 1.6 */ class Stack { int stck[]=new int[10]; int tos; /** * Stack constructor initializes the top of the stack. * @param tos The value to be initialized to -1. */ Stack() { tos=-1; } /** * This method push an item on to the stack. * @param tos If the value is nine the stack is full otherwise array will incremented. */

void push(int item) 5

{ if(tos==9) System.out.println("Stack is full"); else stck[++tos]=item; } /** * This method pop an item on to the stack. * @param tos If the value is negative the stack is undeflow otherwise array will decremented. * @return stck[tos--] the stack array will return */ int pop() { if(tos<0) { System.out.println("Stack underflow"); return 0; } else return stck[tos--]; } }

class TestStack { 6

public static void main(String args[]) { /** * Two objects will be created to push and pop the items. * @param mystack1 The object of the class stack. * @param mystack2 The object of the class stack. */ Stack mystack1=new Stack(); Stack mystack2=new Stack(); for(int i=0;i<10;i++) mystack1.push(i); for(int i=10;i<20;i++) mystack2.push(i); System.out.println("Stack in mystack1:"); for(int i=0;i<10;i++) System.out.println(mystack1.pop()); System.out.println("Stack im mystack2"); for(int i=0;i<10;i++) System.out.println(mystack2.pop()); } }

Queue class: package SQ; import java.io.*; /** 7

* This class demonstrates about the application of Queue * @author Herbert Schildt * @version 1.6 */ import java.io.*; import java.util.*; public class QueueImplement{ LinkedList<Integer> list; String str; int num; public static void main(String[] args){ QueueImplement q = new QueueImplement(); }

/** * This constructor demonstrates the queue application * @param str the value get from commandline is stored. * @exception IOException on input error. * @see IOException */ public QueueImplement(){ try{ list = new LinkedList<Integer>(); InputStreamReader ir = new InputStreamReader(System.in); BufferedReader bf = new BufferedReader(ir); System.out.println("Enter number of elements : "); 8

str = bf.readLine(); if((num = Integer.parseInt(str)) == 0){ System.out.println("You have entered either zero/null."); System.exit(0); } else{ System.out.println("Enter elements : "); for(int i = 0; i < num; i++){ str = bf.readLine(); int n = Integer.parseInt(str); list.add(n); } } System.out.println("First element :" + list.removeFirst()); System.out.println("Last element :" + list.removeLast()); System.out.println("Rest elements in the list :"); while(!list.isEmpty()){ System.out.print(list.remove() + "\t"); } } catch(IOException e){ System.out.println(e.getMessage() + " is not a legal entry."); System.exit(0); } } } 9

OUTPUT: Stack class: E:\SQ>path=C:\Program Files\Java\jdk1.5.0\bin E:\SQ>set path=.;E:\; E:\SQ>javac TestStack.java E:\SQ>java SQ.TestStack 10

Stack in mystack1: 9 8 7 6 5 4 3 2 1 0 Stack in mystack2 19 18 17 16 15 14 13 12 11 10

Queue class: E:\SQ>javac QueueImplement.java E:\SQ>java SQ.QueueImplement 11

Enter number of elements : 4 Enter elements : 2 4 6 8 First element :2 Last element :8 Rest elements in the list : 4 6

Result: Thus the Stack and queue program was compiled and executed successfuly.

Ex.No:2

COMPLEX NUMBER MANIPULATION

AIM: To write a program to perform addition, subtraction, multiplication in complex numbers using constructors. ALGORITHM: 1: Start the program. 12

2: Create a class with a class name Complex Number. 3: Create a constructor with the arguments a and b with integer data type. 4: Define a method getcomplexvalue( ) to get the values of a and b. 5: Define static method named as addition, subtraction,multiplication to perform particular function defined inside the method. 6: Create an object for the class Complex Number and pass the values in the argument list. 7: Call the method by using object to get the values. 8: Print the result. 9: Stop the program.

COMPLEX NUMBER MANIPULATION

public class ComplexNumber { private int a; private int b; public ComplexNumber(){ } 13

public ComplexNumber(int a, int b){ this.a =a; this.b=b; } public String getComplexValue(){ if(this.b < 0){ return a+""+b+"i"; } else{ return a+"+"+b+"i"; } } public static String addition(ComplexNumber num1, ComplexNumber num2){ int a1= num1.a+num2.a; int b1= num1.b+num2.b; if(b1<0){ return a1+""+b1+"i"; } else { return a1+"+"+b1+"i"; } } public static String substraction(ComplexNumber num1, ComplexNumber num2){ int a1= num1.a-num2.a; int b1= num1.b-num2.b; if(b1<0){ return a1+""+b1+"i"; 14

} else { return a1+"+"+b1+"i"; } } public static String multiplication(ComplexNumber num1, ComplexNumber num2){ int a1= num1.a*num2.a; int b1= num1.b*num2.b; int vi1 = num1.a * num2.b; int vi2 = num2.a * num1.b; int vi; vi=vi1+vi2; if(vi<0){ return a1-b1+""+vi+"i"; } else { return a1-b1+"+"+vi+"i"; } } public static void main(String args[]){ ComplexNumber com1 = new ComplexNumber(-2,-3); ComplexNumber com2 = new ComplexNumber(-4,-5); System.out.println(com1.getComplexValue()); System.out.println(com2.getComplexValue()); System.out.println("Addition of both Complex Numbers are :" +ComplexNumber.addition(com1,com2)); System.out.println("Substraction of both Complex Numbers are :" +ComplexNumber.substraction(com1,com2));

15

System.out.println("Multiplication of both Complex Numbers are :" +ComplexNumber.multiplication(com1,com2)); } }

OUTPUT:

E:\Javaexecute>javac ComplexNumber.java

E:\Javaexecute>java ComplexNumber -2-3i -4-5i Addition of both Complex Numbers are :-6-8i Substraction of both Complex Numbers are :2+2i Multiplication of both Complex Numbers are :-7+22i 16

Result: Thus the complex number program was executed and compiled successfuly.

Ex.No:3

DATE CLASS SIMILAR TO JAVA.UTIL PACKAGE

AIM: To write a java program to display the dates of before and after days for a given date. ALGORITHM: 1. Start the program.

2. Create a class with name Date 3. Declare the variables month, day, year as private and create constructor with arguments. 17

4. Check the condition for exception. If the date is valid, It will proceed the program otherwise display the exception Invalid. 5. Use Boolean type for method to return the values as either true or false. 6. Check the values for month and values for day using if loops. 7. Check the year using if loop whether it is leap year or not. 8. Define methods isAfter() and isBefore() in program. 9. Define method compareTo() to compare the date. 10.In main() create object today and give current date as value for constructor fields 11.Call the all methods to display the dates.

DATE CLASS SIMILAR TO JAVA.UTIL PACKAGE

public class Date {

private final int month; private final int day; 18

private final int year;

public Date(int m, int d, int y) { if (!isValid(m, d, y)) throw new RuntimeException("Invalid"); month = m; day = d; year = y; }

private static boolean isValid(int m, int d, int y) { int[] DAYS = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (m < 1 || m > 12) return false; if (d < 1 || d > DAYS[m]) return false; if (m == 2 && d == 29 && !isLeapYear(y)) return false; return true; }

private static boolean isLeapYear(int y) { if (y % 400 == 0) return true; if (y % 100 == 0) return false; return (y % 4 == 0); } 19

public Date next() { if (isValid(month, day + 1, year)) return new Date(month, day + 1, year); else if (isValid(month + 1, 1, year)) return new Date(month + 1, 1, year); else return new Date(1, 1, year + 1); }

public boolean isAfter(Date b) { return compareTo(b) > 0; }

public boolean isBefore(Date b) { return compareTo(b) < 0; }

public int compareTo(Date b) { if (year != b.year) return year - b.year; if (month != b.month) return month - b.month; return day - b.day; }

public String toString() { return day + "-" + month + "-" + year; 20

public static void main(String[] args) { Date today = new Date(7, 12, 2010); System.out.println(today); Date nextDate = today.next(); System.out.println(nextDate); System.out.println(today.isAfter(nextDate)); System.out.println(today.next().isAfter(today)); System.out.println(today.isBefore(nextDate)); System.out.println(nextDate.compareTo(today)); } }

Output: 20-7-2011 21-7-2011 false true true 21

Result: Thus the Date class program was compiled and executed successfuly.

Ex.No:4

IMPLEMENTING DYNAMIC POLYMORPHISM IN JAVA

AIM: To write a java program for abstract class to find areas of different shapes. ALGORITHM: 1. Start the program. 2. Create an abstract class with class name Shape. 3. Create a constructor with arguments and declare variables dim1, dim2 and PI. 22

4. Declare an abstract method area() inside the class. 5. Create the classes Rectangle, Triangle, Circle, and Ellipse to find the area. 6. Define abstract method area() inside the subclasses and call the constructor of class Shape using super keyword. 7. In main(), create the objects for all classes and pass values to fields of constructors. 8. Create a reference variable figuref for abstract class. 9. Using reference variable of class Shape, call the method area() of all subclasses 10. Print the areas for all shapes. 11. Stop the program.

IMPLEMENTING DYNAMIC POLYMORPHISM IN JAVA

abstract class Shape { double dim1; double dim2; double PI=3.14; Shape(double a, double b) { dim1 = a; 23

dim2 = b; } // area is now an abstract method abstract double area(); }

class Rectangle extends Shape { 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 Shape { Triangle(double a, double b) { super(a, b); } 24

// override area for right triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } class Circle extends Shape { Circle(double a, double b) { super(a, b); } double area() { System.out.println("Inside Area for Circle."); return PI * dim1 * dim1; } } class Ellipse extends Shape { Ellipse(double a, double b) { super(a, b); }

25

double area() { System.out.println("Inside Area for Ellipse."); return PI * dim1 * dim2; } } class Square extends Shape { Square(double a, double b) { super(a, b); } double area() { System.out.println("Inside Area for Square."); return dim1 * dim1; } } class AbstractAreas { public static void main(String args[]) { // Figure f = new Figure(10, 10); // illegal now Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Circle c=new Circle(5,5); Ellipse e=new Ellipse(7,7); Square s=new Square(6,6); Shape figref; // this is OK, no object is created figref = r; 26

System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); figref = c; System.out.println("Area is " + figref.area()); figref = e; System.out.println("Area is " + figref.area()); figref = s; System.out.println("Area is " + figref.area()); } }

OUTPUT:

E:\SQ>java AbstractAreas Inside Area for Rectangle. Area is 45.0 Inside Area for Triangle. Area is 40.0 Inside Area for Circle. Area is 78.5 Inside Area for Ellipse. Area is 153.86 Inside Area for Square. Area is 36.0 27

Result: Thus the Dynamic polymorphism was compiled and executed successfuly.

Ex.No:5

JAVA INTERFACE FOR ADT STACK

AIM: To write the java program for ADT stack using interface. ALGORITHM: 1: Start the program 2: Create an interface which consists of three methods namely PUSH, POP and DISPLAY 3: Create a class which implements the above interface to implement the concept of stack through Array 4: Define all the methods of the interface to push any element, to pop the to element and to display the elements present in the stack. 5: Create another class which implements the same interface to implement the concept of stack through linked list. 6: Repeat STEP 4 for the above said class also. 7: In the main class, get the choice from the user to choose whether array implementation or linked list implementation of the stack. 28

8: Call the methods appropriately according to the choices madeby the user in the previous step. 9: Repeat step 6 and step 7 until the user stops his/her execution 10: Stop the program

JAVA INTERFACE FOR ADT STACK

import java.lang.*; import java.io.*; import java.util.*; interface Mystack { int n=10; public void pop(); public void push(); public void peek(); public void display(); } class Stackimp implements Mystack { 29

int stack[]=new int[n]; int top=-1; public void push() { try{ DataInputStream dis=new DataInputStream(System.in); if(top==(n-1)) { System.out.println("overflow"); return; } else { System.out.println("enter element"); int ele=Integer.parseInt(dis.readLine()); stack[++top]=ele; } } catch(Exception e) { System.out.println("e"); } } public void pop() { if(top<0) 30

{ System.out.println("underflow"); return; } else { int popper=stack[top]; top--; System.out.println("popped element" +popper); } } public void peek() { if(top<0) { System.out.println("underflow"); return; } else { int popper=stack[top]; System.out.println("popped element" +popper); } } public void display() { 31

if(top<0) { System.out.println("empty"); return; } else { String str=" "; for(int i=0;i<=top;i++) str=str+" "+stack[i]; System.out.println("elements are"+str); } } } class Stackadt { public static void main(String arg[])throws IOException { DataInputStream dis=new DataInputStream(System.in); Stackimp stk=new Stackimp(); int ch=0; do{ System.out.println("enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit"); ch=Integer.parseInt(dis.readLine()); switch(ch){ case 1:stk.push(); 32

break; case 2:stk.pop(); break; case 3:stk.peek(); break; case 4:stk.display(); break; case 5:System.exit(0); } }while(ch<=5); } }

33

OUTPUT:

E:\SQ>java Stackadt enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit 1 enter element 4 enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit 1 enter element 5 enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit 1 enter element 7 enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit 4 elements are 4 5 7 enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit 1 34

enter element 8 enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit 2 popped element8 enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit 4 elements are 4 5 7 enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit 3 popped element7 enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit 4 elements are 4 5 7 enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit 5

Result: Thus the Interface for ADT stack program was compiled and executed successfuly.

35

Ex. No: 6

DNA File Creation

Aim: To write a Java program to read a file that contains DNA sequences of arbitrary length one per line ,sort the sequences in descending order with respect to the number of 'TATA' subsequences present and finally write the sequences in sorted order into another file. Algorithm: 1. Start 2. Create an input text file DNA.txt and add the sequence as needed. 3. Read each line from the file to a string array. 4. Count the number of TATA sequence in each line and store the count in another array. 5. Arrange the data in the count array in descending order and also arrange the data in the string array in parallel with the count array. 6. Write the sorted DNA sequence to the output file File.txt 7. View the output file. 8. Stop.

36

DNA File creation: import java.util.*; import java.io.*; import java.util.Arrays; import java.util.Collections; class FileDemo { public static void main(String args[])throws IOException { String fileLine[] = new String[6]; BufferedReader br = new BufferedReader(new FileReader("dna.txt")); int i=0,z=0,k=0;; int[] count =new int[6]; int[] order =new int[6]; int result=0; String searchFor = "tata"; int len = searchFor.length(); System.out.println ("Reading data from DNA file............. "); while ((fileLine[k]=br.readLine()) != null ) 37

{ result=0; if (len > 0) { int start = fileLine[k].indexOf(searchFor); while (start != -1) { result++; start = fileLine[k].indexOf(searchFor, start+len); count[k]=result; z++; } }

if(k<5) k++; else break; } int temp,j; String temps; System.out.println ("Swapping data from DNA file............. "); for(i=0;i<(count.length-1);i++) { for(j=i;j<=(count.length-1);j++) 38

{ if(count[i]<count[j]) { temp=count[i]; count[i]=count[j]; count[j]=temp; temps=fileLine[i]; fileLine[i]=fileLine[j]; fileLine[j]=temps; } } } System.out.println file................. "); try { BufferedWriter writer=new BufferedWriter(new FileWriter("file1.txt")); for(i=0;i<6;i++) { writer.write(fileLine[i]); writer.newLine(); } writer.close(); System.out.println ("Writing of Sorted DNA sequence to Output file has been completed................. "); ("Writing Sorted DNA sequence to Output

} catch(IOException ex) 39

{ ex.printStackTrace(); }

} }

40

Input: /*dna.txt*/

attaaattaaaaaaaattata taaattaataaattagaattaaa aaaaaaacatcgtaaa tcaatatatataat ctaaaataaac gataaaaacaaataa

Output:

C:\Program Files\Java\jdk1.6.0\bin>javac FileDemo.java C:\Program Files\Java\jdk1.6.0\bin>java FileDemo Reading data from DNA file............. Swapping data from DNA file............. Writing Sorted DNA sequence to Output file................. Writing of Sorted DNA sequence to Output file has been completed................

/*File.txt*/

tcaatatatataat 41

attaaattaaaaaaaattata aaaaaaacatcgtaaa taaattaataaattagaattaaa ctaaaataaac gataaaaacaaataa

Result:

Thus the DNA sequences were read sorted and output was given to an output file.

42

Ex.No:7 APPLET

DEVELOPING A SIMPLE PAINT LIKE PROGRAM USING

Aim: To develop a simple paint like program using applet in java.

Algorithm: 1. Import the required class and packages. 2. Create a class Drawtest for creating an applet. 3. Initialize panles and controls in the init() method. 4. Define the destroy() method to destroy the same. 5. Create an instance for draw test class and call the init(0 and start() methods in the main method. 6. Add a new frame to the applet window and resize it to 300x300. 7. Declare a method get applet infor to display the applet information. 8. Declare two constants LINES,POINTS which are going to be the modes. 9. Define the paint method and perfoem the required operations. 10.Display the result according to the mode selected.

43

DEVELOPING A SIMPLE PAINT LIKE PROGRAM USING APPLET

import java.awt.event.*; import java.awt.*; import java.applet.*; import java.util.Vector; public class DrawTest extends Applet{ DrawPanel panel; DrawControls controls;

public void init() { setLayout(new BorderLayout()); panel = new DrawPanel(); controls = new DrawControls(panel); add("Center", panel); add("South",controls); }

public void destroy() { remove(panel); remove(controls); }

public static void main(String args[]) { Frame f = new Frame("DrawTest"); 44

DrawTest drawTest = new DrawTest(); drawTest.init(); drawTest.start();

f.add("Center", drawTest); f.setSize(300, 300); f.show(); } public String getAppletInfo() { return "A simple drawing program."; } }

class DrawPanel extends Panel implements MouseListener, MouseMotionListener { public static final int LINES = 0; public static final int POINTS = 1; int mode = LINES;

Vector lines = new Vector(); Vector colors = new Vector(); int x1,y1; int x2,y2;

public DrawPanel() { setBackground(Color.white); addMouseMotionListener(this); addMouseListener(this); 45

public void setDrawMode(int mode) { switch (mode) { case LINES: case POINTS: this.mode = mode; break; default: throw new IllegalArgumentException(); } }

public void mouseDragged(MouseEvent e) { e.consume(); switch (mode) { case LINES: x2 = e.getX(); y2 = e.getY(); break; case POINTS: default: colors.addElement(getForeground()); lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY())); x1 = e.getX(); y1 = e.getY(); 46

break; } repaint(); }

public void mouseMoved(MouseEvent e) { } public void mousePressed(MouseEvent e) { e.consume(); switch (mode) { case LINES: x1 = e.getX(); y1 = e.getY(); x2 = -1; break; case POINTS: default: colors.addElement(getForeground()); lines.addElement(new Rectangle(e.getX(), e.getY(), -1, -1)); x1 = e.getX(); y1 = e.getY(); repaint(); break; } }

47

public void mouseReleased(MouseEvent e) { e.consume(); switch (mode) { case LINES: colors.addElement(getForeground()); lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY())); x2 = -1; break; case POINTS: default: break; } repaint(); }

public void mouseEntered(MouseEvent e) { }

public void mouseExited(MouseEvent e) { }

public void mouseClicked(MouseEvent e) { }

public void paint(Graphics g) { int np = lines.size(); 48

/* draw the current lines */ g.setColor(getForeground()); for (int i=0; i < np; i++) { Rectangle p = (Rectangle)lines.elementAt(i); g.setColor((Color)colors.elementAt(i)); if (p.width != -1) { g.drawLine(p.x, p.y, p.width, p.height); } else { g.drawLine(p.x, p.y, p.x, p.y); } } if (mode == LINES) { g.setColor(getForeground()); if (x2 != -1) { g.drawLine(x1, y1, x2, y2); } } } }

class DrawControls extends Panel implements ItemListener { DrawPanel target;

public DrawControls(DrawPanel target) { 49

this.target = target; setLayout(new FlowLayout()); setBackground(Color.lightGray); target.setForeground(Color.red); CheckboxGroup group = new CheckboxGroup(); Checkbox b; add(b = new Checkbox(null, group, false)); b.addItemListener(this); b.setForeground(Color.red); add(b = new Checkbox(null, group, false)); b.addItemListener(this); b.setForeground(Color.green); add(b = new Checkbox(null, group, false)); b.addItemListener(this); b.setForeground(Color.blue); add(b = new Checkbox(null, group, false)); b.addItemListener(this); b.setForeground(Color.pink); add(b = new Checkbox(null, group, false)); b.addItemListener(this); b.setForeground(Color.orange); add(b = new Checkbox(null, group, true)); b.addItemListener(this); b.setForeground(Color.black); target.setForeground(b.getForeground()); Choice shapes = new Choice(); 50

shapes.addItemListener(this); shapes.addItem("Lines"); shapes.addItem("Points"); shapes.setBackground(Color.lightGray); add(shapes); }

public void paint(Graphics g) { Rectangle r = getBounds(); g.setColor(Color.lightGray); g.draw3DRect(0, 0, r.width, r.height, false);

int n = getComponentCount(); for(int i=0; i<n; i++) { Component comp = getComponent(i); if (comp instanceof Checkbox) { Point loc = comp.getLocation(); Dimension d = comp.getSize(); g.setColor(comp.getForeground()); g.drawRect(loc.x-1, loc.y-1, d.width+1, d.height+1); } } }

public void itemStateChanged(ItemEvent e) { if (e.getSource() instanceof Checkbox) { 51

target.setForeground(((Component)e.getSource()).getForeground()); } else if (e.getSource() instanceof Choice) { String choice = (String) e.getItem(); if (choice.equals("Lines")) { target.setDrawMode(DrawPanel.LINES); } else if (choice.equals("Points")) { target.setDrawMode(DrawPanel.POINTS); } } } }

OUTPUT:

52

Result: Thus the Applet-Paint program was compiled and executed successfuly. .

Ex.No:8 Aim:

DEVELOPING A SCIENTIFIC CALCULATOR

To develop a scientific calculator in java. Algorithm: 1. Import the necessary packages. 53

2. Create a class calculator JFrame class and ActionListener interface. 3. Create a new font using String name,int style,int size). 4. Set up the JMenu bar and add Mnemenics to them by using setMnemonic() method. 5. Set the frame layout for the applet and set the background color to gray using setBackground() method . 6. Create a container using JPanel(). 7. Create numeric JButtons for operators and numbers using JButtons(). 8. Set all the Numbered JButtons to blue .the rest to red usig setForeGround() method. 9. Declare the method getNumberInDisplay() to get by the calculator. 10.Use display result to display the method. 11.Declare the main function and create the instance for calculator and set the attributes setTitle(),setSize(),setResizable(). 12.Stop the program.

DEVELOPING A SCIENTIFIC CALCULATOR

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

public class Calculator extends JFrame implements ActionListener{ // Variables final int MAX_INPUT_LENGTH = 20; final int INPUT_MODE = 0; final int RESULT_MODE = 1; final int ERROR_MODE = 2; int displayMode;

boolean clearOnNextDigit, percent; double lastNumber; String lastOperator;

private JMenu jmenuFile, jmenuHelp; private JMenuItem jmenuitemExit, jmenuitemAbout;

private JLabel jlbOutput; private JButton jbnButtons[]; private JPanel jplMaster, jplBackSpace, jplControl;

/* * Font(String name, int style, int size) Creates a new Font from the specified name, style and point size. */

Font f12 = new Font("Times New Roman", 0, 12); Font f121 = new Font("Times New Roman", 1, 12); 55

// Constructor public Calculator() { /* Set Up the JMenuBar. * Have Provided All JMenu's with Mnemonics * Have Provided some JMenuItem components with Keyboard Accelerators */

jmenuFile = new JMenu("File"); jmenuFile.setFont(f121); jmenuFile.setMnemonic(KeyEvent.VK_F);

jmenuitemExit = new JMenuItem("Exit"); jmenuitemExit.setFont(f12); jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_X, ActionEvent.CTRL_MASK)); jmenuFile.add(jmenuitemExit);

jmenuHelp = new JMenu("Help"); jmenuHelp.setFont(f121); jmenuHelp.setMnemonic(KeyEvent.VK_H);

jmenuitemAbout = new JMenuItem("About Calculator"); jmenuitemAbout.setFont(f12); 56

jmenuHelp.add(jmenuitemAbout);

JMenuBar mb = new JMenuBar(); mb.add(jmenuFile); mb.add(jmenuHelp); setJMenuBar(mb);

//Set frame layout manager

setBackground(Color.gray);

jplMaster = new JPanel();

jlbOutput = new JLabel("0"); jlbOutput.setHorizontalTextPosition(JLabel.RIGHT); jlbOutput.setBackground(Color.WHITE); jlbOutput.setOpaque(true);

// Add components to frame getContentPane().add(jlbOutput, BorderLayout.NORTH);

jbnButtons = new JButton[23]; // GridLayout(int rows, int cols, int hgap, int vgap)

JPanel jplButtons = new JPanel();

// container for Jbuttons

57

// Create numeric Jbuttons for (int i=0; i<=9; i++) { // set each Jbutton label to the value of index jbnButtons[i] = new JButton(String.valueOf(i)); }

// Create operator Jbuttons jbnButtons[10] = new JButton("+/-"); jbnButtons[11] = new JButton("."); jbnButtons[12] = new JButton("="); jbnButtons[13] = new JButton("/"); jbnButtons[14] = new JButton("*"); jbnButtons[15] = new JButton("-"); jbnButtons[16] = new JButton("+"); jbnButtons[17] = new JButton("sqrt"); jbnButtons[18] = new JButton("1/x"); jbnButtons[19] = new JButton("%");

jplBackSpace = new JPanel(); jplBackSpace.setLayout(new GridLayout(1, 1, 2, 2));

jbnButtons[20] = new JButton("Backspace"); jplBackSpace.add(jbnButtons[20]);

jplControl = new JPanel(); 58

jplControl.setLayout(new GridLayout(1, 2, 2 ,2));

jbnButtons[21] = new JButton(" CE "); jbnButtons[22] = new JButton("C");

jplControl.add(jbnButtons[21]); jplControl.add(jbnButtons[22]);

//

Setting all Numbered JButton's to Blue. The rest to Red for (int i=0; i<jbnButtons.length; i++) { jbnButtons[i].setFont(f12);

if (i<10) jbnButtons[i].setForeground(Color.blue);

else jbnButtons[i].setForeground(Color.red); }

// Set panel layout manager for a 4 by 5 grid jplButtons.setLayout(new GridLayout(4, 5, 2, 2));

//Add buttons to keypad panel starting at top left // First row for(int i=7; i<=9; i++) {

jplButtons.add(jbnButtons[i]); 59

// add button / and sqrt jplButtons.add(jbnButtons[13]); jplButtons.add(jbnButtons[17]);

// Second row for(int i=4; i<=6; i++) { jplButtons.add(jbnButtons[i]); }

// add button * and x^2 jplButtons.add(jbnButtons[14]); jplButtons.add(jbnButtons[18]);

// Third row for( int i=1; i<=3; i++) { jplButtons.add(jbnButtons[i]); }

//adds button - and % jplButtons.add(jbnButtons[15]); jplButtons.add(jbnButtons[19]);

60

//Fourth Row // add 0, +/-, ., +, and = jplButtons.add(jbnButtons[0]); jplButtons.add(jbnButtons[10]); jplButtons.add(jbnButtons[11]); jplButtons.add(jbnButtons[16]); jplButtons.add(jbnButtons[12]);

jplMaster.setLayout(new BorderLayout()); jplMaster.add(jplBackSpace, BorderLayout.WEST); jplMaster.add(jplControl, BorderLayout.EAST); jplMaster.add(jplButtons, BorderLayout.SOUTH);

// Add components to frame getContentPane().add(jplMaster, BorderLayout.SOUTH); requestFocus();

//activate ActionListener for (int i=0; i<jbnButtons.length; i++){ jbnButtons[i].addActionListener(this); }

jmenuitemAbout.addActionListener(this); jmenuitemExit.addActionListener(this);

clearAll(); 61

//add WindowListener for closing frame and ending program addWindowListener(new WindowAdapter() {

public void windowClosed(WindowEvent e) { System.exit(0); } } ); } //End of Contructor Calculator

// Perform action public void actionPerformed(ActionEvent e){ double result = 0;

if(e.getSource() == jmenuitemAbout){ JDialog dlgAbout = new CustomABOUTDialog(this, "About Java Swing Calculator", true); dlgAbout.setVisible(true); }else if(e.getSource() == jmenuitemExit){ System.exit(0); }

// Search for the button pressed until end of array or key found for (int i=0; i<jbnButtons.length; i++) 62

{ if(e.getSource() == jbnButtons[i]) { switch(i) { case 0: addDigitToDisplay(i); break;

case 1: addDigitToDisplay(i); break;

case 2: addDigitToDisplay(i); break;

case 3: addDigitToDisplay(i); break;

case 4: addDigitToDisplay(i); break;

case 5: 63

addDigitToDisplay(i); break;

case 6: addDigitToDisplay(i); break;

case 7: addDigitToDisplay(i); break;

case 8: addDigitToDisplay(i); break;

case 9: addDigitToDisplay(i); break;

case 10:

// +/-

processSignChange(); break;

case 11:

// decimal point

addDecimalPoint(); break; 64

case 12:

// =

processEquals(); break;

case 13:

// divide

processOperator("/"); break;

case 14:

// *

processOperator("*"); break;

case 15:

// -

processOperator("-"); break;

case 16:

// +

processOperator("+"); break;

case 17:

// sqrt

if (displayMode != ERROR_MODE) { try { 65

if (getDisplayString().indexOf("-") == 0) displayError("Invalid input for function!");

result = Math.sqrt(getNumberInDisplay()); displayResult(result); }

catch(Exception ex) { displayError("Invalid input for function!"); displayMode = ERROR_MODE; } } break;

case 18:

// 1/x

if (displayMode != ERROR_MODE){ try { if (getNumberInDisplay() == 0) displayError("Cannot divide by zero!");

result = 1 / getNumberInDisplay(); displayResult(result); } 66

catch(Exception ex)

displayError("Cannot divide by zero!"); displayMode = ERROR_MODE; } } break;

case 19:

// %

if (displayMode != ERROR_MODE){ try {

result = getNumberInDisplay() / 100; displayResult(result); }

catch(Exception ex)

displayError("Invalid input for function!"); displayMode = ERROR_MODE; } } break;

case 20:

// backspace

if (displayMode != ERROR_MODE){ setDisplayString(getDisplayString().substring(0,getDisplayString().length() 1)); 67

if (getDisplayString().length() < 1) setDisplayString("0"); } break;

case 21:

// CE

clearExisting(); break;

case 22:

// C

clearAll(); break; } } } }

void setDisplayString(String s){ jlbOutput.setText(s); }

String getDisplayString (){ return jlbOutput.getText(); }

68

void addDigitToDisplay(int digit){ if (clearOnNextDigit) setDisplayString("");

String inputString = getDisplayString();

if (inputString.indexOf("0") == 0){ inputString = inputString.substring(1); }

if ((!inputString.equals("0") || digit > 0) && inputString.length() < MAX_INPUT_LENGTH) { setDisplayString(inputString + digit); }

displayMode = INPUT_MODE; clearOnNextDigit = false; }

void addDecimalPoint(){ displayMode = INPUT_MODE;

if (clearOnNextDigit) setDisplayString(""); 69

String inputString = getDisplayString();

// If the input string already contains a decimal point, don't // do anything to it. if (inputString.indexOf(".") < 0) setDisplayString(new String(inputString + ".")); }

void processSignChange(){ if (displayMode == INPUT_MODE) { String input = getDisplayString();

if (input.length() > 0 && !input.equals("0")) { if (input.indexOf("-") == 0) setDisplayString(input.substring(1));

else setDisplayString("-" + input); }

else if (displayMode == RESULT_MODE) { 70

double numberInDisplay = getNumberInDisplay();

if (numberInDisplay != 0) displayResult(-numberInDisplay); } }

void clearAll()

setDisplayString("0"); lastOperator = "0"; lastNumber = 0; displayMode = INPUT_MODE; clearOnNextDigit = true; }

void clearExisting(){ setDisplayString("0"); clearOnNextDigit = true; displayMode = INPUT_MODE; }

double getNumberInDisplay()

String input = jlbOutput.getText(); return Double.parseDouble(input); }

71

void processOperator(String op) { if (displayMode != ERROR_MODE) { double numberInDisplay = getNumberInDisplay();

if (!lastOperator.equals("0")) { try { double result = processLastOperator(); displayResult(result); lastNumber = result; }

catch (DivideByZeroException e) { } }

else { lastNumber = numberInDisplay; }

clearOnNextDigit = true; lastOperator = op; 72

} }

void processEquals(){ double result = 0;

if (displayMode != ERROR_MODE){ try { result = processLastOperator(); displayResult(result); }

catch (DivideByZeroException e)

displayError("Cannot divide by zero!"); }

lastOperator = "0"; } }

double processLastOperator() throws DivideByZeroException { double result = 0; double numberInDisplay = getNumberInDisplay();

if (lastOperator.equals("/")) 73

{ if (numberInDisplay == 0) throw (new DivideByZeroException());

result = lastNumber / numberInDisplay; }

if (lastOperator.equals("*")) result = lastNumber * numberInDisplay;

if (lastOperator.equals("-")) result = lastNumber - numberInDisplay;

if (lastOperator.equals("+")) result = lastNumber + numberInDisplay;

return result; }

void displayResult(double result){ setDisplayString(Double.toString(result)); lastNumber = result; displayMode = RESULT_MODE; clearOnNextDigit = true; }

74

void displayError(String errorMessage){ setDisplayString(errorMessage); lastNumber = 0; displayMode = ERROR_MODE; clearOnNextDigit = true; }

public static void main(String args[]) { Calculator calci = new Calculator(); Container contentPane = calci.getContentPane(); // contentPane.setLayout(new BorderLayout()); calci.setTitle("Java Swing Calculator"); calci.setSize(241, 217); calci.pack(); calci.setLocation(400, 250); calci.setVisible(true); calci.setResizable(false); }

//End of Swing Calculator Class.

class DivideByZeroException extends Exception{ public DivideByZeroException() { super(); } 75

public DivideByZeroException(String s) { super(s); } }

class CustomABOUTDialog extends JDialog implements ActionListener { JButton jbnOk;

CustomABOUTDialog(JFrame parent, String title, boolean modal){ super(parent, title, modal); setBackground(Color.black);

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

StringBuffer text = new StringBuffer(); text.append("Calculator Information\n\n"); text.append("Developer: Hemanth\n"); text.append("Version: 1.0");

JTextArea jtAreaAbout = new JTextArea(5, 21); jtAreaAbout.setText(text.toString()); jtAreaAbout.setFont(new Font("Times New Roman", 1, 13)); jtAreaAbout.setEditable(false);

76

p1.add(jtAreaAbout); p1.setBackground(Color.red); getContentPane().add(p1, BorderLayout.CENTER);

JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER)); jbnOk = new JButton(" OK "); jbnOk.addActionListener(this);

p2.add(jbnOk); getContentPane().add(p2, BorderLayout.SOUTH);

setLocation(408, 270); setResizable(false);

addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Window aboutDialog = e.getWindow(); aboutDialog.dispose(); } } );

pack(); }

77

public void actionPerformed(ActionEvent e) { if(e.getSource() == jbnOk) this.dispose(); } } {

OUTPUT: 78

Result: Thus the Scientific calculator program was compiled and executed successfuly.

Ex.No:9

DEVELOPING A TEMPLATE FOR LINKED LIST

Aim: To develop a template for linked list in java. Algorithm: 79

1. Import the necessary packages. 2. Declare the main function within the class Linked list demo. 3. Insert items in to the list using add() method use addLast() to isert at the end. 4. Display the contents of the lists. 5. Use remove() method to declare a specific element. 6. Use remove() first(0,removeLast() to delete the element at the first and at the last. 7. Display the lsit and hadle the exceptions .

DEVELOPING A TEMPLATE FOR LINKED LIST

import java.util.*; class LinkedListDemo { 80

public static void main(String args[]) { LinkedList<String> l1=new LinkedList<String>(); l1.add("F"); l1.add("B"); l1.add("D"); l1.add("E"); l1.add("C"); l1.addLast("Z"); l1.addLast("A"); l1.add(1,"A2"); System.out.println("Original contents of l1:" + l1); l1.remove("F"); l1.remove(2); System.out.println("Contents of l1 after deflection: " + l1); l1.removeFirst(); l1.removeLast(); System.out.println("l1 after deleting first and last: " + l1); String val=l1.get(2); l1.set(2, val + "Changed"); System.out.println("l1 after change: " + l1); } }

81

OUTPUT:

E:\SQ>java LinkedListDemo Original contents of l1:[F, A2, B, D, E, C, Z, A] Contents of l1 after deflection: [A2, B, E, C, Z, A] l1 after deleting first and last: [B, E, C, Z] l1 after change: [B, E, CChanged, Z] 82

Result: Thus the Linked list program was compiled and executed successfuly. .

Ex.No:10 APPLICATION Aim:

DEVELOP A MULTI THREADED PRODUCER CONSUMER

To develop a multithreaded producer and consumer application in java. Algorithm: 1. Import the necessary packages. 2. Create two threads producer and consumer. 3. Declare a constant MAXQUEUE in producer thread. 83

4. Create an instance for vector named messages to implement a queue. 5. In the run() method of producer thread put the messages on the queue using putmessages() and suspend the thread for one sec using sleep(1000). 6. Declare the getmessage() method and ceck whether there is any message if no wait for one. 7. After receiving the message remove the message and return it. 8. Create a constructor to assign values to them. 9. In the run method of consumer class call the getmessage() method of producer thread and print the message. 10.Suspend the thread for 2 sec using sleep(2000). 11.Create two instances with different name for consumer thread. 12.Display the message.

DEVELOP A MULTI THREADED PRODUCER CONSUMER APLICATION

import java.util.Vector;

class Producer extends Thread { static final int MAXQUEUE = 5; private Vector messages = new Vector();

84

public void run() { try { while ( true ) { putMessage(); sleep( 1000 ); } } catch( InterruptedException e ) { } }

private synchronized void putMessage() throws InterruptedException {

while ( messages.size() == MAXQUEUE ) wait(); messages.addElement( new java.util.Date().toString() ); notify(); }

// Called by Consumer public synchronized String getMessage() throws InterruptedException { notify(); while ( messages.size() == 0 ) wait(); String message = (String)messages.firstElement(); 85

messages.removeElement( message ); return message; } }

class Consumer extends Thread { Producer producer; String name;

Consumer(String name, Producer producer) { this.producer = producer; this.name = name; }

public void run() { try { while ( true ) { String message = producer.getMessage(); System.out.println(name + " got message: " + message); sleep( 2000 ); } } catch( InterruptedException e ) { } }

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

Producer producer = new Producer(); producer.start();

// Start two this time new Consumer( "One", producer ).start(); new Consumer( "Two", producer ).start(); } }

OUTPUT:

E:\SQ>java Consumer Two got message: Wed Sep 01 11:57:54 GMT+05:30 2010 One got message: Wed Sep 01 11:57:55 GMT+05:30 2010 Two got message: Wed Sep 01 11:57:56 GMT+05:30 2010 One got message: Wed Sep 01 11:57:57 GMT+05:30 2010 Two got message: Wed Sep 01 11:57:58 GMT+05:30 2010 One got message: Wed Sep 01 11:57:59 GMT+05:30 2010 Two got message: Wed Sep 01 11:58:00 GMT+05:30 2010 One got message: Wed Sep 01 11:58:01 GMT+05:30 2010 Two got message: Wed Sep 01 11:58:02 GMT+05:30 2010 87

One got message: Wed Sep 01 11:58:03 GMT+05:30 2010 One got message: Wed Sep 01 11:58:04 GMT+05:30 2010 Two got message: Wed Sep 01 11:58:18 GMT+05:30 2010 One got message: Wed Sep 01 11:58:19 GMT+05:30 2010 Two got message: Wed Sep 01 11:58:20 GMT+05:30 2010 One got message: Wed Sep 01 11:58:21 GMT+05:30 2010 Two got message: Wed Sep 01 11:58:22 GMT+05:30 2010

Result: Thus the Multithreaded program was compiled and executed successfuly. .

Ex.No:11 SERIES Aim:

GENERATING PRIME NUMBERS AND FIBONACCI

To generate prime numbers and fibonacci series using java. Algorithm: 1. Import the necessary packages. 2. Create tow threads MyThread1 and MyThread2. 3. In MyThread1 create instances for piped reader and piped writer. 4. Create a constructor and assign values to them. 5. In mythread2 create instances for pipedreader and piped writer. 6. Create a constructor and assign values to them. 7. Declare a class Multithreaded programming and create two list using ArrayList. 8. Create instances for pipedreader and pipedwriter prl and pwl respectively. 88

9. Get the Fibonacci series from the stream pr2 and store them in lsit2 by using retainAll() method and print them.

89

GENERATING PRIME NUMBERS AND FIBONACCI SERIES

import java.io.*; import java.util.*; class MyThread1 extends Thread { private PipedReader pr; private PipedWriter pw; MyThread1(PipedReader pr, PipedWriter pw) { this.pr = pr; this.pw = pw; } public void run() { try { int i; for (i=1;i<10;i++) { int j; for (j=2; j<i; j++) { int n = i%j; if (n==0) { break; } } if(i == j) 90

{ pw.write(i+"\n"); } }

pw.close(); } catch (IOException e) { } } } class MyThread2 extends Thread { private PipedReader pr; private PipedWriter pw;

MyThread2(PipedReader pr, PipedWriter pw) { this.pr = pr; this.pw = pw; } public void run() { try { int f1, f2 = 1, f3 = 1; for (int i = 1; i <10; i++) { pw.write(f3+"\n"); f1 = f2; f2 = f3; f3 = f1 + f2; 91

} pw.close(); } catch (IOException e) { } } } class MultithreadedProgram { public static void main(String[] args) throws Exception { ArrayList list1=new ArrayList(); ArrayList list2=new ArrayList(); PipedWriter pw1 = new PipedWriter(); PipedReader pr1 = new PipedReader(pw1); MyThread1 mt1 = new MyThread1(pr1, pw1); System.out.println("Prime Numbers: "); mt1.start(); int item1; while ((item1 = pr1.read()) != -1){ char ch1=((char) item1); System.out.print(Character.toString(ch1)); list1.add(Character.toString(ch1)); } pr1.close(); PipedWriter pw2 = new PipedWriter(); PipedReader pr2 = new PipedReader(pw2); MyThread2 mt2 = new MyThread2(pr2, pw2); System.out.println("Fibonacci Numbers: "); 92

mt2.start(); int item2; while ((item2 = pr2.read()) != -1){ char ch2=((char) item2); System.out.print(Character.toString(ch2)); list2.add(Character.toString(ch2)); } pr2.close(); System.out.println("Elements common to both lists are:"); list1.retainAll(list2); for(int i=0;i<list1.size();i++){ System.out.print(list1.get(i)); }

} }

OUTPUT: E:\SQ>java MultithreadedProgram Prime Numbers: 2 93

3 5 7 Fibonacci Numbers: 1 2 3 5 8 13 21 34 55 Elements common to both lists are: 2 3 5

Result: Thus the program was compiled and executed successfuly. . Ex.No:12 MULTITHREADED GUI APPLICATION

Aim: To develop a multithreaded GUI application in java. Algorithm: 94

1. Create the class ball which implements a ball which moves and bounces of the edges of a rectangle. 2. Using the move() method move the ball to the nect postion by reversing the direction if it bits one of the edges. 3. Get the shapes of the ball at its current position. 4. Invoke the runnable() method to show the animated bouncing balls. 5. Using the sleep() method assign the time for ball to bounce in a given interval of time. 6. Construct the frame with the component for showing bouncing ball and start and close buttons. 7. Add the thread to the frame and button to the container. 8. Create a constructor to assign values to them. 9. Add a bouncing ball to the canvas and starts a thread to make it bounce. 10.Display the output.

MULTITHREADED GUI APPLICATION

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

import java.util.*; import java.awt.geom.*; /** A ball that moves and bounces off the edges of a rectangle * @version 1.33 2007-05-17 * @author Cay Horstmann */ class Ball { /** Moves the ball to the next position, reversing direction if it hits one of the edges */ public void move(Rectangle2D bounds) { x += dx; y += dy; if (x < bounds.getMinX()) { x = bounds.getMinX(); dx = -dx; } if (x + XSIZE >= bounds.getMaxX()) { x = bounds.getMaxX() - XSIZE; 96

dx = -dx; } if (y < bounds.getMinY()) { y = bounds.getMinY(); dy = -dy; } if (y + YSIZE >= bounds.getMaxY()) { y = bounds.getMaxY() - YSIZE; dy = -dy; } }

/** Gets the shape of the ball at its current position. */ public Ellipse2D getShape() { return new Ellipse2D.Double(x, y, XSIZE, YSIZE); } private static final int XSIZE = 15; private static final int YSIZE = 15; private double x = 0; private double y = 0; private double dx = 1; 97

private double dy = 1; } class BallComponent extends JComponent { /** * Add a ball to the panel. * @param b the ball to add */ public void add(Ball b) { balls.add(b); }

public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; for (Ball b : balls) { g2.fill(b.getShape()); } } private ArrayList<Ball> balls = new ArrayList<Ball>(); } /** * Shows animated bouncing balls. * @version 1.33 2007-05-17 98

* @author Cay Horstmann */ public class BounceThread { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { JFrame frame = new BounceFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } }

/** * A runnable that animates a bouncing ball. */ class BallRunnable implements Runnable { /** * Constructs the runnable. * @aBall the ball to bounce 99

* @aPanel the component in which the ball bounces */ public BallRunnable(Ball aBall, Component aComponent) { ball = aBall; component = aComponent; }

public void run() { try { for (int i = 1; i <= STEPS; i++) { ball.move(component.getBounds()); component.repaint(); Thread.sleep(DELAY); } } catch (InterruptedException e) { } }

private Ball ball; private Component component; 100

public static final int STEPS = 1000; public static final int DELAY = 5; }

/** * The frame with panel and buttons. */ class BounceFrame extends JFrame { /** * Constructs the frame with the component for showing the bouncing ball and Start and Close * buttons */ public BounceFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setTitle("BounceThread");

comp = new BallComponent(); add(comp, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); addButton(buttonPanel, "Start", new ActionListener() { public void actionPerformed(ActionEvent event) { addBall(); 101

} });

addButton(buttonPanel, "Close", new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); add(buttonPanel, BorderLayout.SOUTH); }

/** * Adds a button to a container. * @param c the container * @param title the button title * @param listener the action listener for the button */ public void addButton(Container c, String title, ActionListener listener) { JButton button = new JButton(title); c.add(button); button.addActionListener(listener); }

102

/** * Adds a bouncing ball to the canvas and starts a thread to make it bounce */ public void addBall() { Ball b = new Ball(); comp.add(b); Runnable r = new BallRunnable(b, comp); Thread t = new Thread(r); t.start(); }

private BallComponent comp; public static final int DEFAULT_WIDTH = 450; public static final int DEFAULT_HEIGHT = 350; public static final int STEPS = 1000; public static final int DELAY = 3; }

103

OUTPUT:

104

Result: Thus the Multithreaded GUI application was compiled and executed successfuly.

105