P. 1
java

java

|Views: 1,081|Likes:
Published by sreekanth294
java
java

More info:

Published by: sreekanth294 on Dec 20, 2012
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

01/12/2014

pdf

text

original

JAVA

A Helpful Hand

Indus Institute of Technology & Engineering MCA Department

ALL THE BEST

MCA-III

Page 1

JAVA
Final programs (25) list which has to be written in Lab observation book
Week 1:
1. Write a Java program that prints all real solutions to the quadratic equation ax2 + bx + c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b2 -4ac is negative, display a message stating that there are no real solutions. 2. The Fibonacci sequence is defined by the following rule. The fist two values in the sequence are 1 and 1. Every subsequent value is the run of the two values preceding it. Write a Java program that uses both recursive and non recursive functions to print the nth value in the Fibonacci sequence. Week 2: 3. Write a Java program that prompts the user for an integer and then prints out all prime numbers up to that. Integer. 4. Write a Java program to multiply two given matrices. 5. Write a Java Program that reads a line of integers, and then displays each integers, and the sum of all the integers (use string tokenizer class) Week 3: 6. Write a Java program that checks whether a given string is a palindrome or not. Ex: MADAM is a palindrome. 7. Write a Java program for sorting a given list of names in ascending order. 8. Write a java program to make frequency count of words in a given text. Week 4: 9. Write a Java program that reads on file name from the user then displays information about whether the file exists, whether the file is readable, whether the file is writable, the type of file and the length of the file in bytes. 10. Write a Java program that reads a file and displays a file and displays the file on the screen, with a line number before each line. 11. Write a Java program that displays the number of characters, lines and words in a text file. Week 5:

MCA-III

Page 2

JAVA
12. Write a Java program that: a) Implements stack ADT. Week 6: 13. Write an applet that displays a simple message. 14. Develop an applet that displays receives an Integer in one text field, and computes its factorial value and returns it in another text field, when the button named “ Compute “ is clicked. Week 7: 15. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the + - X % operations. Add a text field to display the result. Week 8: 16. Write a Java program for handling mouse events.

NOTE: write keyboard events in addition to Written mouse events (already written)
Week 9: 17. Write a Java program for creating multiple threads. First Thread displays “Good Morning” every one second, the second thread displays “Hello” every two seconds and the third thread displays “Welcome” every three seconds. 18. Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication. Week 11: 19. Write a Java program that implements a simple client/server application. The client sends data to a server. The server receives the data, uses it to produce a result, and then sends the result back to the client. The client displays the result on the console. For ex: The data sent from the client is the radius of a circle, and the result produced by the server is the area of the circle.

MCA-III

Page 3

JAVA
Week 12: 20. Write a Java program that allows the user to draw lines, rectangles and Ovals 21. Write a java Program to display the table using JTable Component. 22.Write a Swing program using JTable 23. Write a Swing Program using JTabbed. 24. Write a Swing Program using JTree. 25.Write a java program to display TextBox, Radio Buttons, CheckBox.

MCA-III

Page 4

OOP facilitates creating reusable code that can eventually save a lot of work. A feature called polymorphism permits to create multiple definitions for operators and functions. Data and its functions are encapsulated into a single entity. OOP introduces many new ideas and involves MCA-III Page 5 . The fundamental change in OOP is that a program is designed around the data being operated upon rather upon the operations themselves.JAVA OBJECT ORIENTED PROGRAMMING: OOP Concepts: The object oriented paradigm is built on the foundation laid by the structured programming concepts. Another feature called inheritance permits to derive new classes from old ones.

Classes enable programmers to break an application up into small. Inheritance saves time. Benefits of object oriented programming: Data security is enforced. or objects.JAVA a different approach to programming than the procedural programming. C++ is a superset of the C Programming language. User defined data types can be easily constructed. Basic concepts of Object oriented programming: MCA-III Page 6 . Thus. C++ is a powerful and flexible programming language. The principal enhancement being the object –oriented concept of a class. A Class is a user defined type that encapsulates many important mechanisms. Large complexity in the software development cn be easily managed. where Bjarne Stroustrup developed the language in the early 1980s. with minor exceptions. Basic C++ Knowledge: C++ began its life in Bell Labs. Inheritance emphasizes inventions of new data types. manageable pieces.

Class: The entire set of data and code of an object can be made of a user defined data type with the help of a class. we can create any number of objects belonging to that class A class is thus a collection of objects of similar type. a bank account. a table of data or any item that the program has to handle. Once a class has been defined. I fact. will create an object mango belonging to the class fruit. Data Abstraction and Encapsulation: The wrapping up of data and functions in to a single unit is known as encapsulation. thy may represent a person. Data encapsulation is the most striking feature of a class. Objects are variables of the type class. and orange are members of the class fruit. MCA-III Page 7 . apple. for example: mango. and only those functions which are wrapped in the class can access.JAVA Object: Objects are the basic run time entities in an object-oriented system. The data is not accessible to the outside world. a place. ex: fruit mango.

Abstraction : Abstraction referes to the act of representing essential features without including the background details or explanations. since the classes use the concept of data abstraction .thy are known as abstraction data type(ADT). Inheritance : Inheritance is the process by which objects of one class acquire the properties of objects of another class. MCA-III Page 8 .JAVA This insulation of the data from direct access by the program is called data hiding. Inheritance supports the concept of hierarchical classification.

JAVA for example: Bird Attributes Flying bird Non flying bird Attributes : Attributes: Robin Swallow Penguin Kiwi Attributes Attributes Attributes Attributes The bird 'robin ' is a part of the class 'flying bird' which is agian a part of the class 'bird'. POLYMORPHISM: Polymorphism is another important oop concept. Polymorphism means the ability to take more than one form. The concept of inheritance provide the idea of reusability. an operation may MCA-III Page 9 .

JAVA exhibit different instances. It will read the item and return the value to you. An object's functions. Shape Circle Object Box Object Triangle Object The Object-Oriented Approach The fundamental idea behind object-oriented languages is to combine into a single program entity both data and the functions that operate on that data. Data and its MCA-III Page 10 . If you want to read a data item in an object. The data is hidden. Such an entity is called an object. Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface. You can't access the data directly. The process of making an operator to exhibit different behaviors in different instance is known as operator overloading. The behavior depends upon the types of data used in the operation. typically provide the only way to access its data. you call a member function in the object. so it is safe from accidental alteration. Polymorphism is extensively used if implementing inheritance. called member functions in C++ (because they belong to a particular class of objects).

JAVA functions are said to be encapsulated into a single entity. Encapsulation and data hiding are key terms in the description of object-oriented languages. MCA-III Page 11 .

object oriented programming language developed by Sun Microsystems of USA in 1991. C++ C Java MCA-III Page 12 . While C++ is a superset of C. portable. one of the inventors if the language. This goal had a strong impact on the development team to make the language simple. Java is neither a superset nor a subset of C or C++. highly reliable and powerful language.JAVA Java History: Java is a general-purpose. Java also adds some new features. Originally called “oak” by James Gosling.

The source code is then compiled using the java compiler javac and executed using the java interpreter java. We need create a source code file using a text editor. A complied java program can be converted into a source code. The java debugger jdb is used to find errors. MCA-III Page 13 .JAVA Process of building and running java application programs: Text Editor Java Source Code Javado c HTML files Javac Java Class File Javah Header Files Java (only file name) Jdb (database) Java progra m The way these tools are applied to build and run application programs is create a program.

JAVA SOLUTIONS Program Statement : Write a Java program that prints all real solutions to the quadratic equation ax2+bx+c = 0.c.*. Program : import java. InputStreamReader obj=new InputStreamReader(System. display a message stating that there are no real solutions.disc. class Quadratic { public static void main(String args[])throws IOException { double x1.io. MCA-III Page 14 .b. If the discriminant b2-4ac is negative.a. Read in a. BufferedReader br=new BufferedReader(obj).x2. b. c and use the quadratic formula.in).

readLine()). System.println("roots are "+x1+".b. b=Double. disc=(b*b)-(4*a*c). MCA-III Page 15 .readLine()).println("enter a.readLine()). x2=(-b+Math. x1=(-b+Math.out. if(disc==0) { System.sqrt(disc))/(2*a). } else if(disc>0) { System.out.out. c=Double.sqrt(disc))/(2*a).println("roots are real and unequal"). x1=x2=-b/(2*a).println("roots are real and equal ").out.parseDouble(br.parseDouble(br."+x2). a=Double.parseDouble(br.JAVA System.c values").

"+x2). } } } Input & Output : MCA-III Page 16 .println("roots are "+x1+".out.out.println("roots are imaginary").JAVA System. } else { System.

The first 2 values in the sequence are 1.a=1.i++) { c=a+b. System. Program : /*Non Recursive Solution*/ import java.t.out. t=input.print(" "+b). int i.c=0. Write a Java program that uses both recursive and non-recursive functions to print the nth value of the Fibonacci sequence.JAVA Program Statement : The Fibonacci sequence is defined by the following rule.Scanner.nextInt(). System. System.print(a).out.util.out. for(i=0. a=b. 1. MCA-III Page 17 .b=1. class Fib { public static void main(String args[ ]) { Scanner input=new Scanner(System.in).println("Enter value of t:").i<t-2. Every subsequent value is the sum of the 2 values preceding it.

} System.print(t+"th value of the series is: "+c).print(" "+c).out. System.out.println(). } } Input & Output : MCA-III Page 18 .JAVA b=c. System.out.

JAVA MCA-III Page 19 .

else return (fib(n-1)+fib(n-2)).lang. } } class RecFibDemo { public static void main(String args[])throws IOException { MCA-III Page 20 .JAVA /* Recursive Solution*/ import java. import java.*. else if(n==2) return (1). class Demo { int fib(int n) { if(n==1) return (1).*.io.

for(int i=1.println(" "+res). System.println("enter last number"). System. BufferedReader br=new BufferedReader(obj). } } Input & Output : MCA-III Page 21 . int res=0.println(n+"th value of the series is "+res).i++) { res=ob.out.readLine()).JAVA InputStreamReader InputStreamReader(System.parseInt(br.fib(i).println("fibonacci series is as follows").println(). obj=new System.out. System.in).out. int n=Integer.out. } System. Demo ob=new Demo().i<=n.out.

JAVA MCA-III Page 22 .

j++) { MCA-III Page 23 .j<i.out. Program : Import java.JAVA Program Statement : WAJP that prompts the user for an integer and then prints out all the prime numbers up to that Integer.println ("Prime numbers up to "+num+" are:").util.i++) for (int j=2. for (int i=1.* class Test { void check(int num) { System.i<=num.

out. int n=input. else if((i%j!=0)&&(j==i-1)) System. } } } //end of class Test class Prime { public static void main(String args[ ]) { Test obj1=new Test().JAVA if(i%j==0) break.check(n). } } MCA-III Page 24 . System.in).println("Enter the value of n:").nextInt().print(“ “+i).out. Scanner input=new Scanner(System. obj1.

JAVA Input & Output : MCA-III Page 25 .

Program : import java.io. MCA-III Page 26 .*. Ex: MADAM is a palindrome.JAVA Program Statement : WAJP that checks whether a given string is a palindrome or not.

equals(s2)) System. String s2=sb.out. String s1=br.out.in)). } } MCA-III Page 27 .println("palindrome"). if(s1. else System. sb.readLine().toString().JAVA class Palind { public static void main(String args[ ])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.println("Enter the string to check for palindrome:"). System.append(s1). StringBuffer sb=new StringBuffer().reverse(). sb.out.println("not palindrome").

JAVA Input & Output MCA-III Page 28 .

String arr[ ].*. Program : import java.JAVA Program Statement : WAJP for sorting a given list of names in ascending order.j.io.i. class Test { int len. MCA-III Page 29 .

i++) arr[i]=br. System.JAVA Test(int n) { len=n.i<len.i++) { for(int j=i+1.i<len-1. } { MCA-III Page 30 .readLine(). arr[j]=s1.j<len.println ("Enter the strings U want to sort----").compareTo(arr[j]))>0) { String s1=arr[i].out. arr=new String[n]. for (int i=0. arr[i]=arr[j].in)). return arr. } String[ ] getArray()throws IOException { BufferedReader br=new BufferedReader (new InputStreamReader(System. } String[ ] check()throws ArrayIndexOutOfBoundsException for (i=0.j++) { if ((arr[i].

} void display()throws ArrayIndexOutOfBoundsException { System.out. obj1.out.println(arr[i]).i<len.i++) System.JAVA } } return arr.check().display(). obj1. for (i=0. obj1. } } //end of the Test class class Ascend { public static void main(String args[ ])throws IOException { Test obj1=new Test(4). } } Input & Output : MCA-III Page 31 .println ("Sorted list is---").getArray().

JAVA MCA-III Page 32 .

in). class Test { int r1.out.int r2.util.*.int c) { int arr[][]=new int[r][c]. Test(int r1.JAVA Program Statement : WAJP to multiply two given matrices. Program : import java.c2.c1. this.c1=c1.c2=c2. System. } int[ ][ ] getArray(int r. this.println("Enter the elements for "+r+"X"+c+" Matrix:").r1=r1.int c2) { this. Scanner input=new Scanner(System. this.r2=r2. MCA-III Page 33 .int c1.r2.

out.i++) for(int j=0.k++) c[i][j]=c[i][j]+a[i][k]*b[k][j].out. MCA-III Page 34 . } return c.j++) arr[i][j]=input.j++) System.k<r2. for (int i=0.i++) { for (int j=0.nextInt().j++) { c[i][j]=0.JAVA for(int i=0.int b[ ][ ]) { int c[][]=new int[r1][c2]. for (int i=0. } void putArray(int res[ ][ ]) { System.println ("The resultant "+r1+"X"+c2+" Matrix is:"). for (int k=0.i<r1. return arr.j<c2.j<c2.print(res[i][j]+" ").i++) for (int j=0.j<c.i<r1.i<r. } int[ ][ ] findMul(int a[ ][ ].

3. //to get the matrix from user System. obj1.3). System.2).3.3. } } MCA-III //to perform the multiplication // to display the resultant matrix Page 35 .println().JAVA System. y=obj2.y).println("MATRIX-2:").2).findMul(x.out.println("MATRIX-1:").3.out.getArray(3. int x[ ][ ].out.getArray(2.y[ ][ ]. z=obj1.putArray(z).z[ ][ ].2). Test obj2=new Test(2. x=obj1. } } } //end of Test class class MatrixMul { public static void main(String args[ ])throws IOException { Test obj1=new Test(2.

JAVA Input & Output : MCA-III Page 36 .

JAVA MCA-III Page 37 .

30. MCA-III Page 38 . import java.40.*.lang.*.JAVA Program Statement : WAJP that reads a line of integers and then displays each integer and the sum of all integers.20.util. (use StringTokenizer class) Program : // Using StringTokenizer class import java.50". class tokendemo { public static void main(String args[ ]) { String s="10. int sum=0.

out.length.".i<n.false). System.println("integers are ").JAVA StringTokenizer a=new StringTokenizer(s. int arr[]=new int[n].out. int n=args.println("length is "+n). while(a. } System.".parseInt(a.hasMoreTokens()) { int b=Integer.println(" "+b).nextToken()). } } // Alternate solution using command line arguments class Arguments { public static void main(String args[ ]) { int sum=0. for(int i=0. System. MCA-III Page 39 .out.println("sum of integers is "+sum).parseInt(args[i]).i++) arr[i]=Integer. System. sum=sum+b.out.

System.i<n.println(arr[i]). } } Input & Output : MCA-III Page 40 .println("The enterd values are:").i++) sum=sum+arr[i]. System.println("sum of enterd integers is:").JAVA System.i<n.out. for(int i=0.i++) System.println(sum).out.out. for(int i=0.out.

JAVA MCA-III Page 41 .

p("Parent: " + f1.canRead() ? "is readable" : "is not readable"). whether the file is readable. the type of file and the length of the file in bytes.lastModified()). p(f1. } public static void main(String args[ ]) { File f1 = new File(args[0]).File.JAVA Program Statement : WAJP that reads on file name from the user.getPath()). p(f1. class FileDemo { static void p(String s) { System. p("File size: " + f1. p("Abs Path: " + f1. p(f1.length() + " Bytes"). wheteher the file is writable.getAbsolutePath()).isDirectory() ? "" : "not" + " a directory")).isFile() ? "is normal file" : "might be a named pipe").println(s). p("File Name: " + f1. p("is " + (f1. p(f1.getParent()). } } MCA-III Page 42 . p("Path: " + f1. Program : import java. p("File last modified: " + f1.io.canWrite() ? "is writeable" : "is not writeable").exists() ? "exists" : "does not exist").isAbsolute() ? "is absolute" : "is not absolute"). then displays information about whether the file exists. p(f1.out.getName()).

JAVA Input & Output : : MCA-III Page 43 .

JAVA
Program Statement :

WAJP that reads a file and displays the file on the screen, with a line number before each line.

Program :

import java.io.*; class LineNum{ public static void main(String args[]){ String thisline; for(int i=0;i<args.length;i++) { try{ LineNumberReader br=new LineNumberReader(new FileReader(args[i])); while((thisline=br.readLine())!=null) { System.out.println(br.getLineNumber()+"."+thisline); } }catch(IOException e){ System.out.println("error:"+e);

MCA-III

Page 44

JAVA
} } } }

Input & Output :

MCA-III

Page 45

JAVA

MCA-III

Page 46

JAVA
Program Statement : WAJP that displays the number of characters, lines and words in a text file.

Program :

import java.io.*; public class FileStat { public static void main(String args[ ])throws IOException { long nl=0,nw=0,nc=0; String line; BufferedReader br=new BufferedReader(new FileReader(args[0])); while ((line=br.readLine())!=null) { nl++; nc=nc+line.length(); int i=0; boolean pspace=true; while (i<line.length()) { char c=line.charAt(i++); boolean cspace=Character.isWhitespace(c); if (pspace&&!cspace)

MCA-III

Page 47

readLine())!=null) { nl++. MCA-III Page 48 . System. String line.out.util. import java.*. StringTokenizer st = new StringTokenizer(line).length(). nc=nc+line.out.println("Number of Characters"+nl). public class FileStat { public static void main(String args[ ])throws IOException { long nl=0. } } System. pspace=cspace. }} // Alternate solution using StringTokenizer import java. while ((line=br.io. BufferedReader br=new BufferedReader(new FileReader(args[0])).nw=0.*.println("Number of Characters"+nc).out.println("Number of Characters"+nw).JAVA nw++.nc=0. System.

JAVA nw += st. } System. System.out.out.println("Number of Characters"+nc).out.println("Number of Characters"+nl).countTokens().println("Number of Characters"+nw). }} Input & Output : MCA-III Page 49 . System.

MCA-III Page 50 . private int top.io. int pop().*. interface stack { void push(int item). } class Stackimpl { private int stck[].JAVA Program Statement : WAJP that: (a) (b) (c) Implements a Stack ADT Converts Infix expression to Postfix expression Evaluates a Postfix expression Program : import java.

} void push(int item) { if(top==stck.length-1) System.out. top=-1.JAVA Stackimpl(int size) { stck=new int[size].println("stack is full insertion is not possible"). } int pop() { if(top==-1) { MCA-III Page 51 . else stck[++top]=item.

out. } else return stck[top--].out. BufferedReader br=new BufferedReader(new InputStreamReader(System.JAVA System. System.println("enter the size of the array"). } } class Stackdemo { public static void main(String args[])throws IOException { int a[]. int n=Integer.in)).parseInt(br.println("stack is empty deletion is not possible"). return 0. MCA-III Page 52 .readLine()).

i++) a[i]=Integer.println("enter numbers into the stack").i<n. System.out.pop()).i<n.i++) obj1.println(" "+obj1. for(int i=0.").println("The following numbers are poped out. a=new int[n].out. System.i++) System.parseInt(br. System.readLine()).out.out.push(a[i]). for(int i=0. } } MCA-III Page 53 .i<n.JAVA Stackimpl obj1=new Stackimpl(n).println("numbers are inserted"). for(int i=0.

JAVA Input & Output : MCA-III Page 54 .

awt.drawString(“Hello Java”.JAVA Program Statement : Write an Applet that displays a simple message.applet. import java.*. 10. 100). } } Input & Output : MCA-III Page 55 . /* <applet </applet> */ code = “HelloJava” width = 200 height = 60 > public class HelloJava extends Applet { public void paint(Graphics g) { g.*. Program : import java.

JAVA MCA-III Page 56 .

JAVA Program Statement : Write an Applet that computes the payment of a loan based on the amount of the loan.*. import java. /* <applet code = "LoanPayment" width=500 height=300 > <param name = monthlyRate value=true> </applet> */ public class LoanPayment extends Applet implements ActionListener { TextField amt_t. the interest rate is per month. if true.event. otherwise the interest rate is annual. the interest rate and the number of months. period_t. rate_t.*. Button compute = new Button("Compute"). Program : import java.*. MCA-III Page 57 . import java. boolean monthlyRate.applet.awt.awt. It takes one parameter from the browser: Monthly rate.

RIGHT). add(compute). MCA-III Page 58 . Label rate_l = new Label("Rate: ". rate_t = new TextField(10). Label. amt_t = new TextField(10). add(rate_l). add(period_t).JAVA public void init() { Label amt_l = new Label("Amount: "). period_t = new TextField(10). add(amt_l).setText("0"). add(rate_t). add(period_l). amt_t.CENTER).setText("0"). Label period_l = new Label("Period: ". period_t. add(amt_t). Label.setText("0"). rate_t.

drawString("Input the Loan Amt. } public void paint(Graphics g) { double amt=0.JAVA monthlyRate = Boolean. 50.getText(). MCA-III Page 59 . payment=0. compute.addActionListener(this). rate=0. rate_t. period_s = period_t. period_t.addActionListener(this).getText(). period=0.parseDouble(amt_s).valueOf(getParameter("monthlyRate")).getText(). String amt_s. rate = Double. try { amt_s = amt_t. rate_s. rate_s = rate_t. amt = Double. payment_s. amt_t.addActionListener(this). period_s. g. Rate and Period in each box and press Compute".addActionListener(this).100).parseDouble(rate_s).

} } Input & Output : MCA-III Page 60 . 150). 150).JAVA period = Double. 50. } public void actionPerformed(ActionEvent ae) { repaint(). payment_s = String. } catch (Exception e) { } if (monthlyRate) payment = amt * period * rate * 12 / 100.drawString("The LOAN PAYMENT amount is: ". g. g.parseDouble(period_s).valueOf(payment). else payment = amt * period * rate / 100.drawString(payment_s. 250.

JAVA MCA-III Page 61 .

x / % operations.minus.equal.add(calc).n0.n4. static JTextField result=new JTextField("0".plus.*. } } class CalculatorPanel extends JPanel implements ActionListener { JButton n1. getContentPane().n3.mul.n6. MCA-III Page 62 .*.n5.n7.swing.JAVA Program Statement : WAJP that works as a simple calculator.n2. Add atext field to display the result.awt.awt.n8.45). Program : import javax. Use a grid layout to arrange buttons for the digits and for the + .*. //<applet code=Calculator height=300 width=200></applet> public class Calculator extends JApplet { public void init() { CalculatorPanel calc=new CalculatorPanel().event.n9. import java.div.dot. import java.

} else result.setText(result.setSize(300. result. JOptionPane p=new JOptionPane(). result.setText(no).setText(no).secVal=0.200).BorderLayout. } public CalculatorPanel() { setLayout(new BorderLayout()).NORTH).res.JAVA static String lastCommand=null. else if(lastCommand=="=") { result.getText()+no). add(result. double preRes=0.equals("0")) result.setEditable(false). MCA-III Page 63 . lastCommand=null.getText()). private static void assign(String no) { if((result.

4)). n4=new JButton("4"). n8. panel.add(n8). panel. panel. n7=new JButton("7").JAVA JPanel panel=new JPanel().addActionListener(this).add(n9).addActionListener(this). n9=new JButton("9"). panel. n8=new JButton("8"). div=new JButton("/").add(n4).add(div). n4.setLayout(new GridLayout(4. panel.addActionListener(this). n7. n5.addActionListener(this).addActionListener(this). div. panel.add(n7). n9.addActionListener(this). MCA-III Page 64 . panel.add(n5). n5=new JButton("5").

addActionListener(this).add(n1).add(mul).add(dot)."). panel.add(n6).addActionListener(this). panel.add(n3). panel. n2.add(minus). MCA-III Page 65 . panel. n3.addActionListener(this). panel. n1=new JButton("1").addActionListener(this).add(n2). n6. n2=new JButton("2"). panel.addActionListener(this). n3=new JButton("3"). mul. dot=new JButton(".JAVA n6=new JButton("6").addActionListener(this). minus=new JButton("-"). mul=new JButton("*"). panel. n1. minus.

getSource()==n6) assign("6").addActionListener(this).getSource()==n4) assign("4").getSource()==n8) assign("8").add(plus). equal. } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==n2) assign("2").addActionListener(this). equal=new JButton("="). else if(ae. plus=new JButton("+"). else if(ae. panel.CENTER).add(equal). else if(ae. MCA-III Page 66 . plus.getSource()==n7) assign("7").addActionListener(this). n0=new JButton("0").add(n0). else if(ae. else if(ae. n0. add(panel. else if(ae.getSource()==n3) assign("3"). panel.getSource()==n1) assign("1"). else if(ae. panel.getSource()==n5) assign("5").addActionListener(this).JAVA dot.BorderLayout.

"))==-1) result. } else if(ae.getSource()==div) { preRes=Double.getSource()==n0) assign("0").getText()). else if(ae.setText("0"). result. MCA-III Page 67 .getText()+".getSource()==minus) { preRes=Double.parseDouble(result.setText("0"). lastCommand="/".parseDouble(result.parseDouble(result.getSource()==equal) { secVal=Double.setText(result. lastCommand="-".getText()).JAVA else if(ae.getText()). } else if(ae.getSource()==dot) { if(((result.").indexOf(".getSource()==n9) assign("9"). else if(ae. } else if(ae. result.getText()).

JAVA if(lastCommand.getText()). } else if(ae. result.getText()).parseDouble(result.equals("*")) res=preRes*secVal. lastCommand="*".setText(" "+res). lastCommand="+".setText("0"). result. else if(lastCommand.getSource()==mul) { preRes=Double. else if(lastCommand.equals("+")) res=preRes+secVal.equals("-")) res=preRes-secVal.equals("/")) res=preRes/secVal.getSource()==plus) { preRes=Double. } else if(ae.parseDouble(result. result.setText("0"). lastCommand="=". MCA-III Page 68 . else if(lastCommand.

JAVA } } } Input & Output : MCA-III Page 69 .

public void mouseClicked(MouseEvent me) { // save coordinates mouseX = 0. MCA-III Page 70 . int mouseX = 0.".applet. Program : import java.*. msg = "Mouse clicked.awt.*. import java. addMouseMotionListener(this). mouseY = 0. /* <applet code="MouseEvents" width=300 height=100> </applet> */ public class MouseEvents extends Applet implements MouseListener. } // Handle mouse clicked. // coordinates of mouse public void init() { addMouseListener(this).JAVA Program Statement : WAJP for handling mouse events.*.event. import java.awt. repaint(). } // Handle mouse entered. mouseY = 10. MouseMotionListener { String msg = "".

mouseY = me. repaint().".getX(). mouseY = 10. mouseY = me. } // Handle mouse dragged. msg = "Up". public void mousePressed(MouseEvent me) { // save coordinates mouseX = me.getY(). MCA-III Page 71 . } // Handle button released. repaint(). msg = "Mouse entered.getX().getX(). } // Handle mouse exited. repaint(). mouseY = 10.JAVA public void mouseEntered(MouseEvent me) { // save coordinates mouseX = 0. msg = "Mouse exited. public void mouseReleased(MouseEvent me) { // save coordinates mouseX = me. msg = "Down". } // Handle button pressed. repaint(). public void mouseExited(MouseEvent me) { // save coordinates mouseX = 0.getY(). mouseY = me. public void mouseDragged(MouseEvent me) { // save coordinates mouseX = me.getY().".

public void mouseMoved(MouseEvent me) { // show status showStatus("Moving mouse at " + me.JAVA msg = "*". } } Input & Output : MCA-III Page 72 . repaint().drawString(msg.getY()). public void paint(Graphics g) { g. " + me.getX() + ".Y location. } // Display msg in applet window at current X. " + mouseY). mouseX. showStatus("Dragging mouse at " + mouseX + ". } // Handle mouse moved. mouseY).

NewThread(String threadname) { name = threadname. MCA-III Page 73 . // name of thread Thread t.JAVA Program Statement : WAJP for creating multiple threads. Program : class NewThread implements Runnable { String name.

} } MCA-III Page 74 . } catch (InterruptedException e) { System. new NewThread("Three").").out.JAVA t = new Thread(this. System.out.sleep(10000). Thread.out. t.println(name + " exiting. // start threads new NewThread("Two").out. // Start the thread } // This is the entry point for thread.println("New thread: " + t).").println(name + ": " + i). } System. try { // wait for other threads to end Thread.out. name). } } catch (InterruptedException e) { System. i > 0.out. public void run() { try { for(int i = 5.sleep(1000). } System.println(name + "Interrupted"). i--) { System.println("Main thread exiting.println("Main thread Interrupted").start(). } } class MultiThreadDemo { public static void main(String args[]) { new NewThread("One").

JAVA Input & Output : MCA-III Page 75 .

JAVA MCA-III Page 76 .

println(“Got: “ + n).JAVA Program Statement : WAJP that correctly implements Producer-Consumer problem using the concept of Inter Thread Communication. boolean valueSet = false. return n. synchronized int get() { if (!valueSet) try { wait(). } catch (InterruptedException e) { } System.out. valueSet = false. notify(). Program : class Q { int n. } MCA-III Page 77 .

new Thread(this.n = n.JAVA synchronized void put(int n) { if (valueSet) try { wait(). } catch (InterruptedException e) { } this. valueSet = true.out. “Producer”). notify(). System. } MCA-III Page 78 .q = q. } } class Producer implements Runnable { Q q. Producer(Q q) { this.println(“Put: “ + n).start().

“Consumer”).JAVA public void run() { int i = 0.q = q. Consumer(Q q) { this. while(true) { q.get(). } } MCA-III Page 79 . } } } class Consumer implements Runnable { Q q.start(). new Thread(this.put(i++). } public void run() { while(true) { q.

out. new Consumer(q). } } Input & Output : MCA-III Page 80 . System.JAVA } class PC { public static void main (String args[ ]) { Q q = new Q().println(“Press Ctrl-C to stop”). new Producer(q).

JAVA MCA-III Page 81 .

160).*.green). g. g. Design your own user interface (with Swings & AWT).40).drawString("40%".drawString("PI CHART".blue). /*<applet code=PiChart.class width=600 height=600></applet>*/ public class PiChart extends Applet { public void paint(Graphics g) { setBackground(Color.150.JAVA Program Statement : WAJP that lets users create Pie charts. g.130.150).setColor(Color.white). g. g.magenta). MCA-III Page 82 .setColor(Color.setColor(Color.applet. Program : import java. import java.fillOval(50.200.*.50.awt. g.

100).0.setColor(Color. g.setColor(Color.drawString("5%".white).50.150.120).setColor(Color.50.120).350. g. g.blue).360.140. g.150.180).setColor(Color. g.black).black).50. g.30).100). g.150.setColor(Color.setColor(Color.setColor(Color.drawString("25%".150).100).150.setColor(Color.JAVA g.120).yellow).30.fillArc(50.fillArc(250.50.black).setColor(Color. g. g.90.fillArc(250.150.330.drawString("15%". g. g. g. MCA-III Page 83 .setColor(Color.50. g. g.90).50.drawString("35%".yellow).magenta). g.fillArc(50. g.drawString("30%".90.0.fillOval(250.150.150. g.150.150.150.150.150).120.black).white). g. g.fillArc(250. g.

JAVA g.setColor(Color.white).160).drawString("50%".280. } } Input & Output : MCA-III Page 84 . g.

JAVA MCA-III Page 85 .

} public void paint(Graphics g) { switch(ch) { case 1:{ your MCA-III Page 86 .*.3-ovals)").ch. rectangles and ovals.JAVA Program Statement : WAJP that allows user to draw lines.showInputDialog("enter choice(1-lines.awt. Program : import javax.2-rectangles.Graphics. public void init() { String input.parseInt(input).swing. import java. ch=Integer. input=JOptionPane. public class choice extends JApplet { int i.

50+10*i.i++) { g.drawLine(10. } break. } case 2:{ for(i=1.i<=10.10*i.i++) { g.50+10*i).JAVA for(i=1.50+10*i.50+10*i). } break. }}}} MCA-III Page 87 .10. } case 3:{ for(i=1.10*i.250.i<=10.drawOval(10*i.10*i). } break.i++) { g.drawRect(10*i.i<=10.

JAVA Input & Output : MCA-III Page 88 .

JAVA MCA-III Page 89 .

uses it to produce a result and then sends the result back to the client.*. Program : // Server Program import java. import java. The server receives the data. For ex: The data sent from the client is the radius of a circle and the result produced by the server is the area of the circle.io. public class Server { public void static main (String args [ ] ) { try { // create a server socket ServerSocket s = new ServerSocket(8000).util.*.*.net. // start listening for connections on srver socket MCA-III Page 90 .JAVA Program Statement : WAJP that implements a simple client/server application. The client sends data to a server. import java. The client displays the result on the console.

getInputStream())). //convert string to double double radius = new Double(st.getOutputStream().accept(). process. // continuously read from client. true). // create a buffered reader stream to get data from client BufferedReader isFromClient = new BufferedReader(new InputStreamReader (connectToClient. send back while (true) { // read a line and create string tokenizer StringTokenizer st = new StringTokenizer(isFromClient.readLine()).doubleValue(). // display radius on console MCA-III Page 91 . // create a buffer reader to send result to client PrintWriter osToClient = new PrintWriter(connectToClient.JAVA Socket connectToClient = s.nextToken()).

// send result to client osToClient. // comput area double area = radius * radius *Math.println(e).println(“Area found: “ +area). } } catch (IOException e) { System.out.println(“Radius received from client: “ + radius). } } } // Client Program import java.println(area).io.*.JAVA System.PI.out.err. MCA-III Page 92 . // print result on console System.

8000). // continuously send radius and get area while (true) { Scanner input=new Scanner(System. // create a buffer output stream to send data to server PrintWriter osToServer = new PrintWriter(connectToClient.getInputStream())). // create a buffered input stream to get result from server BufferedReader isFromServer = new BufferedReader(new InputStreamReader (connectToServer. true).JAVA import java.net.getOutputStream().*. import java. public class Client { public void static main (String args [ ] ) { try { // create a socket to connect to server Socket connectToServer = new Socket(“local host”.in). MCA-III Page 93 .util.*.

err.out.JAVA System.println(radius).println(e). } } } MCA-III Page 94 .out.doubleValue().nextDouble(). // print result on console System. double radius =input.print(“Please enter a radius: “).readLine()). // get area from server StringTokenizer st = new StringTokenizer(isFromServer. // display radius on console osToServer. } } catch (IOException e) { System. // convert string to double Double area = new Double(st.nextToken()).println(“Area received from the server is: “ +area).

JAVA Input & Output : MCA-III Page 95 .

JAVA MCA-III Page 96 .

return dim1 * dim2.println("Area for Figure is undefined.out. dim2 = b. Figure(double a. } } class Triangle extends Figure { Triangle(double a. double b) { MCA-III Page 97 . double dim2.JAVA Program Statement : WAJP that illustrates how runtime polymorphism is achieved. b). } double area() { System.println("Inside Area for Rectangle. } } class Rectangle extends Figure { Rectangle(double a. double b) { dim1 = a. } // override area for rectangle double area() { System.")."). double b) { super(a. Program : class Figure { double dim1.out. return 0.

out. 8).area()). figref = t. figref = r.out. b).out. 10).out. return dim1 * dim2 / 2. } // override area for right triangle double area() { System.area()).area()). figref = f.println("Area is " + figref. System. 5).println("Area is " + figref.println("Inside Area for Triangle."). Figure figref. System. Rectangle r = new Rectangle(9. } } class FindAreas { public static void main(String args[]) { Figure f = new Figure(10.JAVA super(a. Triangle t = new Triangle(10. } } MCA-III Page 98 . System.println("Area is " + figref.

JAVA Input & Output : MCA-III Page 99 .

y<a[i]. Program : import java. int sum=0.i++) sum=sum+a[i]. } for(int i=0.y++) System.out. MCA-III Page 100 .i++) { a[i]=r.i<5.i<5. Find its sum and average. for (int i=0.nextInt(10).JAVA Program Statement : WAJP to generate a set of random numbers.print(a[i]).out. System. The program should also display ‘*’ based on the random numbers generated.print(" *"). for(int y=0.util. class RandNum { public static void main(String ax[ ]) { int a[ ]=new int[5].out. Random r=new Random().*.println(""). System.

println("Sum="+sum).length).JAVA System. System.println("Avg="+(double)sum/a.out.out. } } Input & Output : MCA-III Page 101 .

JAVA MCA-III Page 102 .

Triangle and Hexagon. such that each one of the classes contains only the method numberOfSides().JAVA Program Statement : WAJP to create an abstract class named Shape. that contains the number of sides in the given geometrical figure. Program : abstract class Shape { abstract void numberOfSides(). Provide three classes named Trapezoid. that contains an empty method named numberOfSides(). } class Trapezoid extends Shape{ MCA-III Page 103 .

Triangle r=new Triangle().println(" Trapezoidal has four sides"). } } class Triangle extends Shape { void numberOfSides() { System.JAVA void numberOfSides() { System.println("Hexagon has six sides").out.out. MCA-III Page 104 .out.println("Triangle has three sides"). Hexagon h=new Hexagon(). } } class ShapeDemo { public static void main(String args[ ]) { Trapezoid t=new Trapezoid(). Shape s. } } class Hexagon extends Shape { void numberOfSides() { System.

s=r.JAVA s=t.numberOfSides(). s. s. s=h.numberOfSides(). } } Input & Output : MCA-III Page 105 .numberOfSides(). s.

throws).util.rear.JAVA Program Statement : WAJP to implement a Queue. MCA-III Page 106 . using user defined Exception Handling (also make use of throw. Queue() { rear=-1. int q[ ]=new int[10].Scanner. Program : import java. front=-1. } } { class Queue { int front. class ExcQueue extends Exception { ExcQueue(String s) super(s).

else front++. if (front==rear) front=rear=-1. rear++. } } MCA-III Page 107 . return(temp). if (front==-1) front=0. q[rear]=n. } int dequeue() throws ExcQueue { if (front==-1) throw new ExcQueue("Queue is empty"). int temp=q[front].JAVA } void enqueue(int n) throws ExcQueue { if (rear==9) throw new ExcQueue("Queue is full").

getMessage()). } try { System.println(a. try { a. a.println(a.getMessage()). System.out.out.println(e.out.dequeue()).enqueue(20).out.out. System.JAVA class UseQueue { public static void main(String args[ ]) { Queue a=new Queue(). } catch (ExcQueue e) { System.dequeue()).println(e.println(a. } catch(ExcQueue e) { System. } } } Input & Output : MCA-III Page 108 .dequeue()).enqueue(5).

JAVA MCA-III Page 109 .

println("Good Morning"). . (Repeat the same by implementing Runnable) Program : // Using Thread class class One extends Thread { public void run() { for ( .out. ) { try{ sleep(1000). }catch(InterruptedException e){} System. } } } class Two extends Thread { public void run() MCA-III { Page 110 . the second thread displays “Hello” every 2 seconds and the third displays “Welcome” every 3 seconds. First thread displays “Good Morning” every 1 sec.JAVA Program Statement : WAJP that creates 3 threads by extending Thread class.

} } } class MyThread { public static void main(String args[ ]) { MCA-III Page 111 . } } } class Three extends Thread { public void run() { for ( .println("Welcome"). ) { try{ sleep(3000). . .JAVA for ( . }catch(InterruptedException e){} System.out. ) { try{ sleep(2000).out.println("Hello"). }catch(InterruptedException e){} System.

Thread t3=new Thread(obj3).start(). Thread t2=new Thread(obj2).start().sleep(2000). }catch(InterruptedException e){} t3. try{ t.start(). Thread t1=new Thread(obj1). try{ t. One obj1=new One(). try{ t.sleep(1000). }catch(InterruptedException e){} t2.JAVA Thread t = new Thread(). t1.sleep(3000). Three obj3=new Three(). Two obj2=new Two(). }catch(InterruptedException e){} } MCA-III Page 112 .

"One"). }catch(InterruptedException e){} } public void run() { for ( . try{ Thread. ) { try{ Thread. .println("Good Morning").out. }catch(InterruptedException e){} System.JAVA } // Using Runnable interface class One implements Runnable { One( ) { new Thread(this.sleep(1000).start(). } } } MCA-III Page 113 .sleep(1000).

}catch(InterruptedException e){} } public void run() for ( .JAVA class Two implements Runnable { Two( ) { new Thread(this.out.start(). try{ Thread. }catch(InterruptedException e){} System. } } } class Three implements Runnable { Three( ) { MCA-III Page 114 .println("Hello"). .sleep(2000). "Two").sleep(2000). ) { try{ { Thread.

Three obj3=new Three(). . "Three").sleep(3000).sleep(3000).out. ) { try{ Thread. }catch(InterruptedException e){} System.JAVA new Thread(this.start(). try{ Thread. } MCA-III Page 115 . }catch(InterruptedException e){} } public void run() { for ( . Two obj2=new Two().println("Welcome"). } } } class MyThread { public static void main(String args[ ]) { One obj1=new One().

JAVA } Input & Output : MCA-III Page 116 .

System.i++) sum=sum+(double)(1/i).i.println("enter value of n:"). n=input.nextInt(). double sum=0.JAVA Program Statement : WAJP that will compute the following series: (a) (b) (c) 1 + 1/2 + 1/3+ …….out.util.in).i<=n. MCA-III Page 117 .println("Result:"+sum).Scanner.+ 1/n import java. Scanner input= new Scanner(System. for(i=1. class Series1 { public static void main(String arg[ ]) { int n. System.out.+ 1/n 1 + 1/2 + 1/ 22 + 1/ 23 + … … + 1/ 2n ex = 1 + x/1! + x2/2! + x3/3! + … … Program : // (a) 1 + 1/2 + 1/3+ …….

JAVA
} }

Input & Output :

// (b)1 + 1/2 + 1/ 22 + 1/ 23 + … … + 1/ 2n

import java.util.Scanner; class Series2 { public static void main(String arg[ ]) { int n; double sum=0,i; Scanner input= new Scanner(System.in); System.out.println("enter value of n:"); n=input.nextInt();

MCA-III

Page 118

JAVA
for(i=1;i<=n;i++) sum=sum+(double)(1/Math.pow(2,i-1));

System.out.println("Result:"+sum); } }

Input & Output :

MCA-III

Page 119

JAVA

// (c) ex = 1 + x/1! + x2/2! + x3/3! + … …

import java.util.*; class Series3{ public static void main(String arg[ ]) { int n,x; double sum=0,i,d=1; Scanner input= new Scanner(System.in); System.out.println("enter value of n:"); n=input.nextInt(); System.out.println("enter value of x:"); x=input.nextInt(); for (i=1;i<=n;i++) { sum=sum+(double)((Math.pow(x,i-1)/d)); d=d*i; } System.out.println("Result :"+sum); } } MCA-III Page 120

JAVA

Input & Output :

MCA-III

Page 121

println("Who is the inventor of Java ?"). if the answer is (e) To display the correct answer.io.str2.in)). str1="James Gosling".*.out. while(count!=3) { MCA-III Page 122 .JAVA Program Statement : WAJP to do the following: (a) (b) (c) (d) wrong To output the question “Who is the inventor of Java?” To accept an answer To printout “GOOD” and then stop if the answer is correct To output the message “TRY AGAIN”. int count=0. System. BufferedReader br=new BufferedReader(new InputStreamReader(System. class Ask { public static void main(String a[ ])throws Exception { String str1. when the answer is wrong even at the third attempt Program : import java.

} } if(count==3) System.JAVA str2=br. if(str1.out.out. } } Input & Output : MCA-III Page 123 . } else { if(count<2) System.readLine().out. break.println("!!! GOOD !!!").println("TRY AGAIN !").equalsIgnoreCase(str2)) { System. count++.println("Correct Answer is : "+str1).

JAVA : MCA-III Page 124 .

k++) s[k]=a[i][j].length.k=0.j.r.length.4}. rows=a.7. int a[ ][ ]={{1. for (i=0. Program : class TransMatrix { public static void main(string args[ ]) { int i.i++) for (j=0.j++. int d[ ]=new int[rows*cols]. cols=a[0]. int b[ ][ ]=new int[rows*cols].{5. int s[ ]=new int[rows*cols]. i=j=k=r=c=0.2.8}}. int rows.c.3.j<cols.i<rows.cols. MCA-III Page 125 .6.JAVA Program Statement : WAJP to transpose a matrix using ‘arraycopy’ command.

j<cols. for(i=0.i.j++) System.JAVA while(r<rows) { while(c<cols) { System.i++) { for(j=0.i. System.print(" "+b[i][j]).i<rows. MCA-III Page 126 .out. t++. } j=c=0. for (i=0.out.d. k++.out.l).i<cols.println("\nb matrix:").out.i++) { for(j=0.print(" "+a[i][j]). } System.println("a matrix:").out. b[j++][k]=d[i++]. } System.arraycopy(s.j++) System.j<rows.println(). c++.

} } } Input & Output : INPUT : OUTPUT : MCA-III Page 127 .JAVA System.println().out.

case 2: return new Hamster (). case 1: return new Gerbil ().JAVA Program Statement : Create an inheritance hierarchy of Rodent. switch (rr. In the base class provide methods that are common to all Rodents and override these in the derived classes to perform different behaviors. class Rodent{ void place() {} void tail() {} void eat() {} public static Rodent randRodent(){ Random rr=new Random().nextInt(4)) { case 0: return new Mouse(). Hamster etc. Mouse. MCA-III Page 128 . Gerbil.Random.util. Create an array of Rodent. fill it with different specific types of Rodents and call your base class methods. Program : import java. depending on the specific type of Rodent.

clothes”).out.println(“Mice eat cardboards.JAVA case 3: return new Beaver (). } } class Mouse extends Rodent { void place() { System.out. papers.println(“Mice are found all over the world”). } void tail() { System. } } class Gerbil extends Rodent { void place() { MCA-III Page 129 . } void eat() { System. } return new Rodent().out.println(“Mice have long and hairless tail”).

out.println(“Gerbils have long tail”). } } class Hamster extends Rodent { void place() { System. parts of plants”).println(“Hamsters are found in Western Europe to China – Dry regions only”). } void eat() { System.println(“Gerbils eat seeds.println(“Hamsters have short tail”). } void tail() { System.out.out. } void eat() { System.println(“Gerbils are found in arid parts of Africa and Asia”). roots.JAVA System.println(“Hamsters eat cereals”).out.out. } MCA-III Page 130 . } void tail() { System.out. insects.

println(“Beavers have broad tail”). } } public class Rodents{ public static void main(String args[ ]) { Rodent r[] = new Rodent[6]. for (int i=0. } void tail() { System.out.length. for (int i=0.JAVA } class Beaver extends Rodent { void place() { System. } void eat() { System. i++) r[i] = Rodent.length.println(“Beavers eat bark”). i<r. i++) { MCA-III Page 131 .println(“Beavers are found in Northern Europe and North America”).out. i<r.randRodent().out.

place().eat().JAVA r[i]. } } } MCA-III Page 132 . r[i].tail(). r[i].

JAVA Input & Output : MCA-III Page 133 .

applet. from 0 to 7 int col. */ /* <applet code="ChessBoard.awt. It is assumed that the size of the applet is 160 by 160 pixels. // Top-left corner of square MCA-III Page 134 . // Column number.y. import java.*. Program : import java. // Row number.JAVA Program Statement : WAJP to print a chessboard pattern. public class ChessBoard extends Applet { /* This applet draws a red-and-black checkerboard.*.class" width=200 height=160> </applet> */ public void paint(Graphics g) { int row. from 0 to 7 int x.

setColor(Color. 40). 40. g. row < 8.white).setColor(Color. y. } } // end for row } // end paint() } // end class Input & Output : MCA-III Page 135 . if ( (row % 2) == (col % 2) ) g. col < 8.fillRect(x. row++ ) { for ( col = 0.black). else g. y = row * 40. col++) { x = col * 40.JAVA for ( row = 0.

JAVA

MCA-III

Page 136

JAVA
SOME OTHER PROGRAMS APPLET PROGRAMS 1. // Demonstrate BorderLayout. import java.awt.*; import java.applet.*; import java.util.*; /* <applet code="BorderLayoutDemo" width=400 height=200> </applet> */

public class BorderLayoutDemo extends Applet { public void init() { setLayout(new BorderLayout());

add(new Button("This is across the top."), BorderLayout.NORTH); add(new Label("The footer message might go here."), BorderLayout.SOUTH); add(new Button("Right"), BorderLayout.EAST); add(new Button("Left"), BorderLayout.WEST);

MCA-III

Page 137

JAVA

String msg = "The reasonable man adapts " + "himself to the world;\n" + "the unreasonable one persists in " + "trying to adapt the world to himself.\n" + "Therefore all progress depends " + "on the unreasonable man.\n\n" + " - George Bernard Shaw\n\n";

add(new TextArea(msg), BorderLayout.CENTER); } } 2. // Demonstrate Buttons import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="ButtonDemo" width=250 height=150> </applet> */

MCA-III

Page 138

JAVA
public class ButtonDemo extends Applet implements ActionListener { String msg = ""; Button yes, no, maybe; TextField f1;

public void init() { yes = new Button("Yes"); no = new Button("No"); maybe = new Button("Undecided"); f1=new TextField(19); add(yes); add(no); add(maybe); add(f1); yes.addActionListener(this); no.addActionListener(this); maybe.addActionListener(this); }

public void actionPerformed(ActionEvent ae) { String str = ae.getActionCommand();

MCA-III

Page 139

6.setText(str). // Demonstrate Buttons MCA-III Page 140 .".equals("Yes")) { msg = "You pressed Yes. } public void paint(Graphics g) { g.equals("No")) { msg = "You pressed No. } else { msg = "You pressed Undecided.JAVA if(str. } else if(str.". f1.". } repaint().drawString(msg. } } 3. 100).

import java. no = new Button("No"). maybe = new Button("Undecided").awt. MCA-III Page 141 .*. maybe. static Button yes.*. public void ButtonDemo1() { yes = new Button("Yes"). add(maybe).*.JAVA import java. /* <applet code="ButtonDemo" width=250 height=150> </applet> */ public class ButtonDemo1 extends Frame implements ActionListener { static String msg = "".applet.event.awt. import java. add(no). no.

setSize(300. maybe.".equals("Yes")) { msg = "You pressed Yes. } public void actionPerformed(ActionEvent ae) { String str = ae. } } public static void main(String s[]) { ButtonDemo1 b1=new ButtonDemo1().getActionCommand(). if(str. } else if(str.addActionListener(this). } else { msg = "You pressed Undecided.addActionListener(this).JAVA yes.". no. MCA-III Page 142 .".300).equals("No")) { msg = "You pressed No. b1.addActionListener(this).

b1. MCA-III Page 143 .*. System.out. import java.applet. /* <applet code="CardLayoutDemo" width=300 height=100> </applet> */ public class CardLayoutDemo extends Applet implements ActionListener. solaris.add(maybe).awt.event.JAVA b1.add(no). b1. b1.*.*.awt.println(msg). import java.add(yes). winNT. MouseListener { Checkbox Win98. } } 4. mac. import java.setVisible(true). // Demonstrate CardLayout.

// add Windows check boxes to a panel Panel winPan = new Panel(). null. osCards = new Panel(). cardLO = new CardLayout().JAVA Panel osCards. Button Win. osCards.add(Win98). MCA-III Page 144 . public void init() { Win = new Button("Windows"). Other = new Button("Other"). add(Win). Other. solaris = new Checkbox("Solaris"). add(Other). winNT = new Checkbox("Windows NT"). true).setLayout(cardLO). mac = new Checkbox("MacOS"). CardLayout cardLO. winPan. // set panel layout to card layout Win98 = new Checkbox("Windows 98".

// add cards to main applet panel add(osCards). osCards. // add panels to card deck panel osCards.JAVA winPan. // register to receive action events Win.add(winNT). } MCA-III Page 145 .addActionListener(this). Other. otherPan.add(otherPan. // register mouse events addMouseListener(this).add(solaris).add(winPan. "Windows").add(mac).addActionListener(this). // Add other OS check boxes to a panel Panel otherPan = new Panel(). "Other"). otherPan.

JAVA // Cycle through panels. "Other").next(osCards).show(osCards. } // Provide empty implementations for the other MouseListener methods.getSource() == Win) { cardLO. } else { cardLO. "Windows"). public void mousePressed(MouseEvent me) { cardLO.show(osCards. MCA-III Page 146 . public void mouseClicked(MouseEvent me) { } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mouseReleased(MouseEvent me) { } public void actionPerformed(ActionEvent ae) { if(ae.

cbg.applet. solaris. solaris = new Checkbox("Solaris". CheckboxGroup cbg. Win98 = new Checkbox("Windows 98".*. winNT. MCA-III Page 147 . import java. // Demonstrate check box group.*. cbg. winNT = new Checkbox("Windows NT".*. Checkbox Win98. public void init() { cbg = new CheckboxGroup(). false). false). cbg. import java. true).JAVA } } } 5. /* <applet code="CBGroup" width=250 height=200> </applet> */ public class CBGroup extends Applet implements ItemListener { String msg = "".awt. import java.awt.event. mac.

} public void itemStateChanged(ItemEvent ie) { repaint(). msg += cbg.addItemListener(this). 100). g.JAVA mac = new Checkbox("MacOS".drawString(msg. MCA-III Page 148 .addItemListener(this). 6. add(winNT). false). add(mac).addItemListener(this). public void paint(Graphics g) { msg = "Current selection: ". add(Win98). cbg. winNT.addItemListener(this). Win98.getLabel(). mac. } // Display current state of the check boxes. add(solaris). solaris.getSelectedCheckbox().

mac = new Checkbox("MacOS").JAVA } } 6. winNT = new Checkbox("Windows NT").event. solaris. /* <applet code="CheckboxDemo" width=250 height=200> </applet> */ public class CheckboxDemo extends Applet implements ItemListener { String msg = "". winNT.*.*. solaris = new Checkbox("Solaris"). import java. MCA-III Page 149 . Checkbox Win98. true).*. public void init() { Win98 = new Checkbox("Windows 98". import java.awt. // Demonstrate check boxes.applet. import java.awt. mac. null.

} // Display current state of the check boxes.addItemListener(this). add(mac).getState().addItemListener(this). g. add(winNT). Win98. solaris. 100).getState(). add(solaris).addItemListener(this). winNT. 6. } public void itemStateChanged(ItemEvent ie) { repaint().drawString(msg. 6. g. msg = " Windows 98: " + Win98. 80). MCA-III Page 150 .drawString(msg.JAVA add(Win98). msg = " Windows NT: " + winNT. mac.addItemListener(this). public void paint(Graphics g) { msg = "Current state: ".

*.getState().getState(). 140).drawString(msg. import java.drawString(msg. 120).*.awt. 6.drawString(msg. /* <applet code="ChoiceDemo" width=300 height=180> </applet> */ public class ChoiceDemo extends Applet implements ItemListener { Choice os. import java. 160). import java. msg = " Solaris: " + solaris.awt. public void init() { MCA-III Page 151 . 6. // Demonstrate Choice lists. 6.event. g. } } 7. msg = " MacOS: " + mac.JAVA g.applet. g.*. browser. String msg = "".

0"). browser.add("Netscape 3.add("Lynx 2.add("Internet Explorer 2. // add items to os list os. browser.add("Solaris"). browser.x"). MCA-III Page 152 . browser.add("Windows NT").x").add("MacOS").add("Internet Explorer 3. os. browser.JAVA os = new Choice().select("Netscape 4.add("Netscape 1. browser. os. browser.4"). browser = new Choice().add("Netscape 2.0"). os.add("Netscape 4. browser.1").add("Windows 98"). // add items to browser list browser.x").0").add("Internet Explorer 4.x").

// register to receive item events os.drawString(msg.getSelectedItem(). g. add(browser).addItemListener(this).getSelectedItem(). MCA-III Page 153 . msg += browser. 6. } public void itemStateChanged(ItemEvent ie) { repaint(). public void paint(Graphics g) { msg = "Current OS: ". 120).drawString(msg. msg = "Current Browser: ". msg += os. browser. } // Display current selections. 140). g. 6.JAVA // add choice lists to window add(os).addItemListener(this).

f.setSize(width. public class DialogDemo extends Applet { Frame f. import java. int width = Integer. int height = Integer. height).parseInt(getParameter("width")). height).awt. public void init() { f = new MenuFrame("Menu Demo"). f.JAVA } } 8. setSize(width.*. import java.parseInt(getParameter("height")). MCA-III Page 154 .applet.setVisible(true).Applet. /* <applet code="DialogDemo" width=250 height=200> </applet> */ // Create frame window.

event. import java. import java.setVisible(true).awt. import java.applet. } } 9.setVisible(false).JAVA } public void start() { f.*.*. } public void stop() { f.awt.*. // Use left-aligned flow layout. /* <applet code="FlowLayoutDemo" width=250 height=200> </applet> */ public class FlowLayoutDemo extends Applet implements ItemListener { MCA-III Page 155 .

winNT. Checkbox Win98. winNT. solaris. winNT = new Checkbox("Windows NT"). mac. add(Win98). add(mac).addItemListener(this). add(winNT). solaris. solaris = new Checkbox("Solaris").addItemListener(this). null.LEFT)). // register to receive item events Win98. true).addItemListener(this). mac = new Checkbox("MacOS"). mac. add(solaris). MCA-III Page 156 .addItemListener(this). public void init() { // set left-aligned flow layout setLayout(new FlowLayout(FlowLayout.JAVA String msg = "". Win98 = new Checkbox("Windows 98".

6. g.JAVA } // Repaint when status of a check box changes. 120).drawString(msg. msg = " Mac: " + mac. msg = " Windows NT: " + winNT. 160). g. 100). g. public void itemStateChanged(ItemEvent ie) { repaint().getState(). 6.drawString(msg.getState(). 6. } } MCA-III Page 157 . 140). 6. g. g. 80). } // Display current state of the checkboxes. 6.drawString(msg. msg = " Solaris: " + solaris. public void paint(Graphics g) { msg = "Current state: ". msg = " Windows 98: " + Win98.getState().drawString(msg.drawString(msg.getState().

*.awt. // Demonstrate GridLayout import java. j < n. } } MCA-III Page 158 . setFont(new Font("SansSerif".BOLD. public void init() { setLayout(new GridLayout(n. /* <applet code="GridLayoutDemo" width=300 height=200> </applet> */ public class GridLayoutDemo extends Applet { static final int n = 4.JAVA 10.applet. import java. 24)). i++) { for(int j = 0. j++) { int k = i * n + j. for(int i = 0. Font. i < n. if(k > 0) add(new Button("" + k)). n)).*.

*. add(new Label("The footer message might go here. BorderLayout. // Demonstrate BorderLayout with insets. MCA-III Page 159 .util."). add(new Button("This is across the top. setLayout(new BorderLayout()). /* <applet code="InsetsDemo" width=400 height=200> </applet> */ public class InsetsDemo extends Applet { public void init() { // set background color so insets can be easily seen setBackground(Color.*.NORTH).awt.cyan).SOUTH). import java.JAVA } } 11. import java.*.applet."). BorderLayout. import java.

\n" + "Therefore all progress depends " + "on the unreasonable man. 10). add(new Button("Left").*.\n\n" + " .JAVA add(new Button("Right").WEST). 10.CENTER). String msg = "The reasonable man adapts " + "himself to the world. BorderLayout.awt. 10. add(new TextArea(msg).\n" + "the unreasonable one persists in " + "trying to adapt the world to himself.George Bernard Shaw\n\n".*. } } 12.EAST). BorderLayout. BorderLayout. // Demonstrate Lists. } // add insets public Insets getInsets() { return new Insets(10. import java.event.awt. MCA-III Page 160 . import java.

1").*.add("Windows NT"). true).applet. public void init() { os = new List(4. browser = new List(4.add("MacOS"). browser. MCA-III Page 161 . String msg = "". os.JAVA import java.add("Windows 98").add("Solaris"). os. os. /* <applet code="ListDemo" width=300 height=180> </applet> */ public class ListDemo extends Applet implements ActionListener { List os.add("Netscape 1. // add items to os list os. // add items to browser list browser. false).

add("Netscape 4. browser. browser.0").x").JAVA browser.add("Internet Explorer 4. browser.add("Netscape 3.add("Netscape 2. // add lists to window add(os).addActionListener(this).x"). // register to receive action events os.0").add("Internet Explorer 3. browser.add("Lynx 2.4").addActionListener(this).add("Internet Explorer 2. add(browser).0"). } public void actionPerformed(ActionEvent ae) { MCA-III Page 162 .x"). browser. browser.select(1). browser. browser.

120). import java. 140). 6.drawString(msg. import java.getSelectedItem(). msg += browser. } } 13. i<idx. for(int i=0.drawString(msg. msg = "Current Browser: ". public void paint(Graphics g) { int idx[].awt. i++) msg += os.length. msg = "Current OS: ". // Create frame window.*.getItem(idx[i]) + " ". idx = os. 6. g. public class MenuDemo extends Applet { Frame f. MCA-III Page 163 .getSelectedIndexes(). g.Applet.applet. } // Display current selections.JAVA repaint().

int height = Integer.setVisible(false). int width = Integer. } public void start() { f. setSize(new Dimension(width. f. height)). // Illustrate menus.JAVA /* <applet code=MenuDemo width=300 height=100> </applet>*/ public void init() { f = new MenuFrame("Menu Demo"). } public void stop() { f.parseInt(getParameter("width")). height).setVisible(true).setSize(width. f. MCA-III Page 164 . } } 14.setVisible(true).parseInt(getParameter("height")).

*. MCA-III Page 165 .JAVA import java.event. CheckboxMenuItem debug. import java.awt. // create the menu items Menu file = new Menu("File"). // create menu bar and add it to frame MenuBar mbar = new MenuBar(). setMenuBar(mbar).awt.*. test. MenuFrame(String title) { super(title).*. /* <applet code="MenuDemo" width=250 height=250> </applet> */ // Create a subclass of Frame class MenuFrame extends Frame { String msg = "".applet. import java.

// these are checkable menu items MCA-III Page 166 .add(item9 = new MenuItem("-")). edit..")). file. item7. file. file.JAVA MenuItem item1. MenuItem item10."))... sub. sub. sub.add(item1 = new MenuItem("New.add(item11 = new MenuItem("Second")). file.add(item5 = new MenuItem("Quit. mbar.")). edit.add(item12 = new MenuItem("Third")). item4. edit.. file.add(item6 = new MenuItem("Cut")).add(sub). edit. Menu sub = new Menu("Special").add(item2 = new MenuItem("Open. Menu edit = new Menu("Edit"). item2.add(item8 = new MenuItem("Paste")). item8. item3..add(item10 = new MenuItem("First")). item11. MenuItem item6. item5. edit. item12.add(item3 = new MenuItem("Close")).add(item4 = new MenuItem("-")).add(item7 = new MenuItem("Copy")).. item9.add(file).

addActionListener(handler). item4.addActionListener(handler).add(edit).addActionListener(handler). item6.addActionListener(handler).addActionListener(handler). // create an object to handle action and item events MyMenuHandler handler = new MyMenuHandler(this).addActionListener(handler).addActionListener(handler).add(test). item12. MCA-III Page 167 .addActionListener(handler).addActionListener(handler). test = new CheckboxMenuItem("Testing"). item5. item8. item11.add(debug). // register it to receive those events item1. item10.addActionListener(handler). item2.addActionListener(handler). item9. edit.addActionListener(handler).JAVA debug = new CheckboxMenuItem("Debug"). item3. edit. item7. mbar.

drawString("Testing is off. 10.getState()) g.". } public void paint(Graphics g) { g.drawString(msg. // register it to receive those events addWindowListener(adapter). // create an object to handle window events MyWindowAdapter adapter = new MyWindowAdapter(this). 240).". test. 10. 200). if(test. else g. } MCA-III Page 168 . 10.addItemListener(handler).drawString("Debug is off.drawString("Debug is on.addItemListener(handler).getState()) g. if(debug.JAVA debug. 240). 10.". 220). else g. 220).".drawString("Testing is on. 10.

ItemListener { MenuFrame menuFrame. public MyMenuHandler(MenuFrame menuFrame) { this. String arg = (String)ae. public MyWindowAdapter(MenuFrame menuFrame) { this.menuFrame = menuFrame. } public void windowClosing(WindowEvent we) { menuFrame.")) MCA-III Page 169 .menuFrame = menuFrame. if(arg. } // Handle action events public void actionPerformed(ActionEvent ae) { String msg = "You selected "..setVisible(false).JAVA } class MyWindowAdapter extends WindowAdapter { MenuFrame menuFrame.getActionCommand().equals("New.. } } class MyMenuHandler implements ActionListener.

else if(arg.".".".")) msg += "Quit.. else if(arg.".". else if(arg.". else if(arg.". else if(arg.equals("Cut")) msg += "Cut.. else if(arg. else if(arg.". else if(arg.equals("Quit.equals("Edit")) msg += "Edit.". else if(arg.")) msg += "Open. else if(arg.".equals("Third")) msg += "Third. else if(arg.equals("First")) msg += "First..equals("Copy")) msg += "Copy..equals("Paste")) msg += "Paste.equals("Debug")) MCA-III Page 170 .JAVA msg += "New.".equals("Open.equals("Close")) msg += "Close.equals("Second")) msg += "Second.

int height = Integer.".msg = msg.equals("Testing")) msg += "Testing. menuFrame. menuFrame. } // Handle item events public void itemStateChanged(ItemEvent ie) { menuFrame. public void init() { f = new MenuFrame("Menu Demo"). } } /* // Create frame window. else if(arg. setSize(new Dimension(width.repaint().repaint(). int width = Integer. MCA-III Page 171 .parseInt(getParameter("width")).". height)).parseInt(getParameter("height")).JAVA msg += "Debug. public class MenuDemo extends Applet { Frame f.

setVisible(true).*. } } */ 13. } public void start() { f. import java.event.setVisible(false). f. /* <applet code="DialogDemo" width=250 height=250> </applet> */ MCA-III Page 172 . // Demonstrate Dialog box. import java.awt. height).setVisible(true).*.applet.*. import java.setSize(width.JAVA f. } public void stop() { f.awt.

} } MCA-III Page 173 . add(new Label("Press this button:")).addActionListener(this). } public void actionPerformed(ActionEvent ae) { dispose(). 10. title. false). 70). setSize(300. b. String title) { super(parent. class SampleDialog extends Dialog implements ActionListener { SampleDialog(Frame parent.drawString("This is in the dialog box". add(b = new Button("Cancel")). Button b. } public void paint(Graphics g) { g. 200). setLayout(new FlowLayout()).JAVA // Create a subclass of Dialog.

add(file).add(item2 = new MenuItem("Open. mbar.add(new MenuItem("-")). item2.. // create menu bar and add it to frame MenuBar mbar = new MenuBar(). MenuItem item1. class MenuFrame extends Frame { String msg = "".. file..add(item3 = new MenuItem("Close")).")).")). test. // create the menu items Menu file = new Menu("File"). file. item3.. item4. MenuFrame(String title) { super(title). file. file..")). file.. CheckboxMenuItem debug. setMenuBar(mbar).add(item1 = new MenuItem("New.add(item4 = new MenuItem("Quit.JAVA // Create a subclass of Frame. MCA-III Page 174 .

MenuItem item8. Menu sub = new Menu("Special". edit. test = new CheckboxMenuItem("Testing"). edit.add(item9 = new MenuItem("Second")). sub. item7.add(edit).add(item5 = new MenuItem("Cut")).add(item8 = new MenuItem("First")).add(sub).add(item10 = new MenuItem("Third")). item6. sub. edit.add(item7 = new MenuItem("Paste")). edit. // these are checkable menu items debug = new CheckboxMenuItem("Debug"). edit. mbar.add(new MenuItem("-")). true). sub. item9. item10. MCA-III Page 175 . MenuItem item5. edit. edit.add(item6 = new MenuItem("Copy")).add(debug).JAVA Menu edit = new Menu("Edit").add(test).

item5.addActionListener(handler). item2.addActionListener(handler).addItemListener(handler). item7.addActionListener(handler). item9. item6.addActionListener(handler).addActionListener(handler). MCA-III Page 176 . debug.addActionListener(handler).addItemListener(handler). test.addActionListener(handler). // create an object to handle window events MyWindowAdapter adapter = new MyWindowAdapter(this).JAVA // create an object to handle action and item events MyMenuHandler handler = new MyMenuHandler(this). // register it to receive those events addWindowListener(adapter). item3.addActionListener(handler).addActionListener(handler). item8. item4. // register it to receive those events item1.addActionListener(handler). item10.

10. public MyWindowAdapter(MenuFrame menuFrame) { this.". 220).". 10.". else g.". 10. } public void windowClosing(WindowEvent we) { MCA-III Page 177 .getState()) g.drawString("Debug is on.drawString("Testing is on. 10. } } class MyWindowAdapter extends WindowAdapter { MenuFrame menuFrame. 220).drawString("Debug is off. 10.menuFrame = menuFrame.getState()) g.drawString(msg. else g. 200). 240). 240).drawString("Testing is off. if(debug. if(test.JAVA } public void paint(Graphics g) { g.

". ItemListener { MenuFrame menuFrame.dispose(). else if(arg.getActionCommand().setVisible(true). d. "New Dialog Box"). public MyMenuHandler(MenuFrame menuFrame) { this. } // Handle action events public void actionPerformed(ActionEvent ae) { String msg = "You selected ".equals("Open. String arg = (String)ae. if(arg. // Activate a dialog box when New is selected.")) MCA-III Page 178 .JAVA menuFrame. } } class MyMenuHandler implements ActionListener. SampleDialog d = new SampleDialog(menuFrame.")) { msg += "New...equals("New. } // Try defining other dialog boxes for these options.menuFrame = menuFrame...

equals("Debug")) msg += "Debug.equals("Copy")) msg += "Copy.".". else if(arg.equals("Close")) msg += "Close.JAVA msg += "Open. else if(arg.equals("Quit. else if(arg.equals("Second")) msg += "Second.".equals("Third")) msg += "Third.equals("Edit")) msg += "Edit. else if(arg.equals("First")) msg += "First.".". else if(arg.equals("Paste")) msg += "Paste. else if(arg. else if(arg.")) msg += "Quit..".". else if(arg.equals("Cut")) msg += "Cut. else if(arg. else if(arg.equals("Testing")) MCA-III Page 179 ."..".".". else if(arg.

} } /* // Create frame window.parseInt(getParameter("width")). f. menuFrame. height). height).parseInt(getParameter("height")).msg = msg. public void init() { f = new MenuFrame("Menu Demo"). public class DialogDemo extends Applet { Frame f.repaint().JAVA msg += "Testing. } public void itemStateChanged(ItemEvent ie) { menuFrame.repaint().". menuFrame. setSize(width. int height = Integer.setSize(width. int width = Integer. MCA-III Page 180 .

awt.*.awt. */ import java. } public void stop() { f.setVisible(true). /* Demonstrate File Dialog box.*.event. This is an application. } public void start() { f.setVisible(true). // Create a subclass of Frame class SampleFrame extends Frame { SampleFrame(String title) { MCA-III Page 181 . } } */ 14.setVisible(false).JAVA f. not an applet. import java.

setVisible(false). public MyWindowAdapter(SampleFrame sampleFrame) { this. } } class MyWindowAdapter extends WindowAdapter { SampleFrame sampleFrame. } } // Create frame window. // register it to receive those events addWindowListener(adapter). class FileDialogDemo { public static void main(String args[]) { Frame f = new SampleFrame("File Dialog Demo"). // create an object to handle window events MyWindowAdapter adapter = new MyWindowAdapter(this).sampleFrame = sampleFrame. MCA-III Page 182 . } public void windowClosing(WindowEvent we) { sampleFrame.JAVA super(title).

/* <applet code="SBDemo" width=300 height=200> </applet> */ public class SBDemo extends Applet implements AdjustmentListener.*.applet. fd. Scrollbar vertSB. MouseMotionListener { String msg = "".JAVA f. horzSB.*. public void init() { MCA-III Page 183 .setSize(100. 100). // Demonstrate scroll bars.setVisible(true).awt.awt. } } 15.*.setVisible(true).event. import java. import java. "File Dialog"). f. FileDialog fd = new FileDialog(f. import java.

} public void adjustmentValueChanged(AdjustmentEvent ae) { repaint(). int height = Integer.addAdjustmentListener(this).addAdjustmentListener(this).JAVA int width = Integer. width). 0. 0. add(vertSB). 0. } MCA-III Page 184 .HORIZONTAL. // register to receive adjustment events vertSB.VERTICAL. vertSB = new Scrollbar(Scrollbar.parseInt(getParameter("height")). horzSB = new Scrollbar(Scrollbar.parseInt(getParameter("width")). 1. addMouseMotionListener(this). horzSB. add(horzSB). height). 0. 1.

repaint().getY(). 6.getValue(). Horizontal: " + horzSB. public void mouseDragged(MouseEvent me) { int x = me.getValue()). vertSB.setValue(y). } // Necessary for MouseMotionListener public void mouseMoved(MouseEvent me) { } // Display current value of scroll bars. msg += ".drawString(msg. 160).getX().drawString("*". public void paint(Graphics g) { msg = "Vertical: " + vertSB. horzSB.getValue().JAVA // Update scroll bars to reflect mouse dragging. // show current mouse drag position g. MCA-III Page 185 . vertSB. int y = me. horzSB. g.getValue().setValue(x).

import java.applet.R.awt. import java.\n" + "And the other way is to make it so complicated\n" + "that there are no obvious deficiencies.*.\n" + "One way is to make it so simple\n" + "that there are obviously no deficiencies.\n" + "That wish has come true. // Demonstrate TextArea. /* <applet code="TextAreaDemo" width=300 height=250> </applet> */ public class TextAreaDemo extends Applet { public void init() { String val = "There are two ways of constructing " + "a software design.A.*.\n\n" + " -C. Hoare\n\n" + "There's an old story about the person who wished\n" + "his computer were as easy to use as his telephone.JAVA } } 16.\n" + MCA-III Page 186 .

AT&T. } } 17.*. // Demonstrate text field.applet.*.awt. public void init() { MCA-III Page 187 .awt.JAVA "since I no longer know how to use my telephone.*. 30). /* <applet code="TextFieldDemo" width=380 height=150> </applet> */ public class TextFieldDemo extends Applet implements ActionListener { TextField name. TextArea text = new TextArea(val.\n\n" + " -Bjarne Stroustrup. import java. (inventor of C++)".event. add(text). 10. pass. import java. import java.

addActionListener(this). Label. add(namep).setEchoChar('?'). Label.RIGHT). Label passp = new Label("Password: ". pass. pass. name = new TextField(12). } // User pressed Enter. // register to receive action events name. pass = new TextField(8).addActionListener(this). add(name). } public void paint(Graphics g) { MCA-III Page 188 . add(pass).RIGHT). add(passp).JAVA Label namep = new Label("Name: ". public void actionPerformed(ActionEvent ae) { repaint().

getText(). 6. 60). // Demonstrate text field.drawString("Name: " + name.drawString("Selected text in name: " + name.awt. import java.event. MCA-III Page 189 .JAVA g. import java.awt.*. /* <applet code="TextFieldDemo1" width=380 height=150> </applet> */ class SampleFrame extends Frame { SampleFrame(String title) { super(title). g.*.*. 6.getText().applet. 100). // create an object to handle window events MyWindowAdapter adapter = new MyWindowAdapter(this). g. 80).getSelectedText(). // register it to receive those events addWindowListener(adapter). } } 18. 6.drawString("Password: " + pass. import java.

public MyWindowAdapter(SampleFrame sampleFrame) { this. Frame f. } public void windowClosing(WindowEvent we) { sampleFrame.sampleFrame = sampleFrame. pass. Button b1.setVisible(false).JAVA } } class MyWindowAdapter extends WindowAdapter { SampleFrame sampleFrame. } } public class TextFieldDemo1 extends Applet implements ActionListener { TextField name. String s1. public void init() { MCA-III Page 190 .

add(pass). add(passp).RIGHT). name = new TextField(12).JAVA Label namep = new Label("Name: ". Label.setEchoChar('?').addActionListener(this). b1=new Button("ok").RIGHT). public void actionPerformed(ActionEvent ae) { MCA-III Page 191 . Label. add(b1). b1. pass. add(namep).addActionListener(this).addActionListener(this). pass = new TextField(8). } // User pressed Enter. pass. add(name). // register to receive action events name. Label passp = new Label("Password: ".

6. String s=ae. g. 6.drawString("Name: " + name. if(s.setVisible(true).equals("ok")) f=new SampleFrame("button press"). 80).event. } } 19. 6.drawString("Selected text in name: " + name.awt. import java. f.getSelectedText().awt.setSize(200. import java.JAVA repaint().getText().applet. 60).getActionCommand(). import java. } public void paint(Graphics g) { g. f. 100).200). MCA-III Page 192 .drawString("Password: " + pass.*.*.*.getText(). g.

drawString("This is in the dialog box". 200). add(new Label("Press this button:")). setLayout(new FlowLayout()). 10. } } MCA-III Page 193 . String title) { super(parent. class SampleDialog1 extends Dialog implements ActionListener { SampleDialog1(Frame parent. setSize(300. 70).JAVA // Create a subclass of Dialog. false). Button b. b. title. } public void paint(Graphics g) { g.addActionListener(this). } public void actionPerformed(ActionEvent ae) { dispose(). add(b = new Button("Cancel")).

file.")). setMenuBar(mbar).")). item2.")).add(file).JAVA class MenuFrame extends Frame { String msg = "".. MenuItem item1. MCA-III Page 194 . MenuFrame(String title) { super(title). file. file. item3. mbar. CheckboxMenuItem debug...add(item1 = new MenuItem("New. test.. // create the menu items Menu file = new Menu("File"). file..add(new MenuItem("-")). file. item4. // create menu bar and add it to frame MenuBar mbar = new MenuBar().add(item3 = new MenuItem("Close")).add(item4 = new MenuItem("Quit..add(item2 = new MenuItem("Open.

addItemListener(handler). // create an object to handle action and item events MyMenuHandler handler = new MyMenuHandler(this). item2.addActionListener(handler). file. debug. item4.add(debug). test. item3.add(test).addActionListener(handler).JAVA // these are checkable menu items debug = new CheckboxMenuItem("Debug"). // create an object to handle window events MCA-III Page 195 . file.addItemListener(handler).addActionListener(handler). // register it to receive those events item1. test = new CheckboxMenuItem("Testing").addActionListener(handler).

getState()) g. 240). 10.".".getState()) g. 220). } } class MyWindowAdapter extends WindowAdapter { MenuFrame menuFrame. 10. } public void paint(Graphics g) { g.drawString("Testing is on. else g. else g. 240).drawString(msg. 220).". 10. if(test.drawString("Debug is off. 10. public MyWindowAdapter(MenuFrame menuFrame) { MCA-III Page 196 .JAVA MyWindowAdapter adapter = new MyWindowAdapter(this).". // register it to receive those events addWindowListener(adapter). 10.drawString("Testing is off.drawString("Debug is on. 200). if(debug.

".getActionCommand().dispose(). public MyMenuHandler(MenuFrame menuFrame) { this. } // Handle action events public void actionPerformed(ActionEvent ae) { String msg = "You selected ". if(arg.equals("New. } public void windowClosing(WindowEvent we) { menuFrame. } } class MyMenuHandler implements ActionListener. // Activate a dialog box when New is selected..menuFrame = menuFrame. String arg = (String)ae. MCA-III Page 197 .")) { msg += "New.menuFrame = menuFrame. ItemListener { MenuFrame menuFrame.JAVA this..

else if(arg.equals("Quit")) msg += "Quite.LOAD). d.equals("Debug")) msg += "Debug. MCA-III Page 198 . else if(arg.". d. else if(arg. } else if(arg.equals("Close")) msg += "Close.equals("Open. else if(arg.". } // Try defining other dialog boxes for these options. "open Dialog Box".")){ msg += "Open.setVisible(true).. System.equals("Testing")) msg += "Testing. "New Dialog Box").setVisible(true).out.".println("Hello World!").JAVA SampleDialog1 d = new SampleDialog1(menuFrame.FileDialog.. FileDialog d = new FileDialog(menuFrame.".".

msg = msg.repaint().JAVA menuFrame. 300). f. f = new MenuFrame("Menu Demo"). menuFrame. } } class f1 { public static void main(String[] args) { Frame f. } } MCA-III Page 199 .repaint().setSize(300. f.setVisible(true). } public void itemStateChanged(ItemEvent ie) { menuFrame.

event.awt.*.awt. public void init() { // Get content pane Container contentPane = getContentPane(). import java. // Add buttons to content pane MCA-III Page 200 .JAVA SWINGS PROGRAMS 1. contentPane.*. import java. /* <applet code="JButtonDemo" width=250 height=300> </applet> */ public class JButtonDemo extends JApplet implements ActionListener { JTextField jtf.*.swing. import javax.setLayout(new FlowLayout()).

add(jb).addActionListener(this). contentPane.gif"). JButton jb = new JButton(france).addActionListener(this). jb. jb. jb.addActionListener(this).setActionCommand("France").gif").add(jb).setActionCommand("Italy"). ImageIcon germany = new ImageIcon("germany. ImageIcon italy = new ImageIcon("italy. MCA-III Page 201 . jb. jb. jb. jb = new JButton(italy). jb = new JButton(japan).setActionCommand("Japan").setActionCommand("Germany").addActionListener(this). ImageIcon japan = new ImageIcon("japan.JAVA ImageIcon france = new ImageIcon("france. jb. contentPane. contentPane.add(jb).gif").gif"). jb = new JButton(germany). jb.

// Add text field to content pane jtf = new JTextField(15).*. MCA-III Page 202 . } public void actionPerformed(ActionEvent ae) { jtf.JAVA contentPane. contentPane.getActionCommand()).awt.event. import javax. import java.awt.add(jb).setText(ae. import java. /* <applet code="JCheckBoxDemo" width=400 height=50> </applet> */ public class JCheckBoxDemo extends JApplet implements ItemListener { JTextField jtf.*.swing.*.add(jtf). } } 2.

contentPane. cb.addItemListener(this). cb. normal). cb. cb = new JCheckBox("C++".setSelectedIcon(selected). cb.gif").JAVA public void init() { // Get content pane Container contentPane = getContentPane().setLayout(new FlowLayout()). cb. contentPane. // Create icons ImageIcon normal = new ImageIcon("normal. // Add check boxes to the content pane JCheckBox cb = new JCheckBox("C".gif").setRolloverIcon(rollover).setRolloverIcon(rollover).gif").setSelectedIcon(selected).add(cb). ImageIcon rollover = new ImageIcon("rollover. normal). MCA-III Page 203 . ImageIcon selected = new ImageIcon("selected.

cb. contentPane. // Add text field to the content pane jtf = new JTextField(15). cb.setSelectedIcon(selected).setSelectedIcon(selected). } public void itemStateChanged(ItemEvent ie) { JCheckBox cb = (JCheckBox)ie. cb. contentPane. cb. contentPane.add(cb). cb. contentPane. cb.getItem().add(cb).setRolloverIcon(rollover).addItemListener(this).addItemListener(this). cb = new JCheckBox("Java".add(jtf). normal). MCA-III Page 204 .setRolloverIcon(rollover). normal).add(cb). cb = new JCheckBox("Perl".addItemListener(this).JAVA cb.

MCA-III Page 205 .JAVA jtf.setLayout(new FlowLayout()).awt.setText(cb.getText()). public void init() { // Get content pane Container contentPane = getContentPane(). contentPane. } } 3.*.awt. germany.*.*. import java.swing.event. import java. import javax. /* <applet code="JComboBoxDemo" width=300 height=100> </applet> */ public class JComboBoxDemo extends JApplet implements ItemListener { JLabel jl. japan. ImageIcon france. italy.

add(jc).addItemListener(this). MCA-III Page 206 . import javax.*.gif")).JAVA // Create a combo box and add it // to the panel JComboBox jc = new JComboBox(). jc.addItem("Germany"). jc. } } 4.getItem(). contentPane.*.addItem("Italy").swing. jc. jl. contentPane. jc.addItem("Japan").gif")). import java. // Create label jl = new JLabel(new ImageIcon("france. jc. } public void itemStateChanged(ItemEvent ie) { String s = (String)ie.add(jl).awt.addItem("France").setIcon(new ImageIcon(s + ".

ii. // Add label to the content pane contentPane. } } 5.gif").*.add(jl). JLabel.awt.JAVA /* <applet code="JLabelDemo" width=250 height=150> </applet> */ public class JLabelDemo extends JApplet { public void init() { // Get content pane Container contentPane = getContentPane(). import java. // Create an icon ImageIcon ii = new ImageIcon("france. MCA-III Page 207 .CENTER). // Create a label JLabel jl = new JLabel("France".

/* <applet code="JRadioButtonDemo" width=300 height=50> </applet> */ public class JRadioButtonDemo extends JApplet implements ActionListener { JTextField tf. import javax.add(b1). contentPane.addActionListener(this). // Add radio buttons to content pane JRadioButton b1 = new JRadioButton("A").awt. public void init() { // Get content pane Container contentPane = getContentPane().*.event.swing.setLayout(new FlowLayout()).JAVA import java. MCA-III Page 208 . b1.*. contentPane.

setText(ae.JAVA JRadioButton b2 = new JRadioButton("B"). // Define a button group ButtonGroup bg = new ButtonGroup().add(b1).addActionListener(this).add(b2). contentPane. // Create a text field and add it // to the content pane tf = new JTextField(5). b3.add(b3).add(b3).addActionListener(this). contentPane. b2.add(tf).add(b2). JRadioButton b3 = new JRadioButton("C"). } public void actionPerformed(ActionEvent ae) { tf.getActionCommand()). MCA-III Page 209 . bg. bg. contentPane. bg.

// Add 400 buttons to a panel JPanel jp = new JPanel(). i < 20.setLayout(new BorderLayout()). contentPane.*. import java.awt.setLayout(new GridLayout(20. int b = 0.swing. for(int i = 0. 20)). i++) { MCA-III Page 210 . /* <applet code="JScrollPaneDemo" width=300 height=250> </applet> */ public class JScrollPaneDemo extends JApplet { public void init() { // Get content pane Container contentPane = getContentPane().*. jp. import javax.JAVA } } 6.

JScrollPane jsp = new JScrollPane(jp. /* <applet code="JTabbedPaneDemo" width=400 height=100> </applet> */ MCA-III Page 211 .*. ++b.CENTER). h). j < 20.add(jsp. int h = ScrollPaneConstants. v. j++) { jp.HORIZONTAL_SCROLLBAR_AS_NEEDED. // Add scroll pane to the content pane contentPane. import javax.swing. BorderLayout.JAVA for(int j = 0.add(new JButton("Button " + b)). } } 7. } } // Add panel to a scroll pane int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED.

new ColorsPanel()). JButton b2 = new JButton("London").add(jtp). getContentPane(). jtp. new FlavorsPanel()). jtp.addTab("Flavors". MCA-III Page 212 . add(b2). new CitiesPanel()). JButton b3 = new JButton("Hong Kong"). add(b1).addTab("Colors". jtp.addTab("Cities". } } class CitiesPanel extends JPanel { public CitiesPanel() { JButton b1 = new JButton("New York").JAVA public class JTabbedPaneDemo extends JApplet { public void init() { JTabbedPane jtp = new JTabbedPane().

add(cb2). JButton b4 = new JButton("Tokyo"). JCheckBox cb3 = new JCheckBox("Blue"). } } class ColorsPanel extends JPanel { public ColorsPanel() { JCheckBox cb1 = new JCheckBox("Red"). } } class FlavorsPanel extends JPanel { public FlavorsPanel() { MCA-III Page 213 .JAVA add(b3). JCheckBox cb2 = new JCheckBox("Green"). add(cb3). add(cb1). add(b4).

addItem("Vanilla").addItem("Chocolate"). import java. import javax. jcb.addItem("Strawberry").JAVA JComboBox jcb = new JComboBox(). /* <applet code="JTableDemo" width=400 height=200> </applet> */ public class JTableDemo extends JApplet { public void init() { // Get content pane MCA-III Page 214 .*. jcb. jcb. } } 8.awt.*.swing. add(jcb).

"5555" }. { "Ed". "5159" }. MCA-III Page 215 . "5689". "Fax" }. // Set layout manager contentPane. "9222" }. { "Viviane". "1237". { "Jennifer". "9023".JAVA Container contentPane = getContentPane(). "4244" }. "Phone". "1313" }. "9030". { "Ken". "7566". // Initialize data final Object[][] data = { { "Gail". "2176" }. "5887" }. "7345". { "John". "6741". "4567". { "Ellen". "5332" }. "5656". { "Claire". "5672". { "Matt". { "Anne". "1212" }. "5634". "1134". "3144" }. "8675" }. // Initialize column headings final String[] colHeads = { "Name". "3333" }. { "Melanie". { "Erwin".setLayout(new BorderLayout()).

VERTICAL_SCROLLBAR_AS_NEEDED. // Create the table JTable table = new JTable(data.CENTER). h). /* <applet code="JTextFieldDemo" width=300 height=50> </applet> */ MCA-III Page 216 . JScrollPane jsp = new JScrollPane(table. // Add tree to a scroll pane int v = ScrollPaneConstants. // Add scroll pane to the content pane contentPane.*. } } 9. colHeads). v. import javax.add(jsp. "1415" } }.JAVA { "Helen". import java. "6751".*.HORIZONTAL_SCROLLBAR_AS_NEEDED.awt. BorderLayout.swing. int h = ScrollPaneConstants.

import java.*. // Add text field to content pane jtf = new JTextField(15).JAVA public class JTextFieldDemo extends JApplet { JTextField jtf.add(jtf). /* <applet code="JTreeEvents" width=400 height=200> </applet> MCA-III Page 217 .tree. public void init() { // Get content pane Container contentPane = getContentPane(). contentPane.awt. import java.*. } } 10. import javax.swing.event.awt.*. contentPane. import javax.*.setLayout(new FlowLayout()).swing.

JAVA
*/

public class JTreeEvents extends JApplet { JTree tree; JTextField jtf;

public void init() {

// Get content pane Container contentPane = getContentPane();

// Set layout manager contentPane.setLayout(new BorderLayout());

// Create top node of tree DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");

// Create subtree of "A" DefaultMutableTreeNode a = new DefaultMutableTreeNode("A"); top.add(a); MCA-III Page 218

JAVA
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1"); a.add(a1); DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2"); a.add(a2);

// Create subtree of "B" DefaultMutableTreeNode b = new DefaultMutableTreeNode("B"); top.add(b); DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1"); b.add(b1); DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2"); b.add(b2); DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3"); b.add(b3);

// Create tree tree = new JTree(top);

MCA-III

Page 219

JAVA
// Add tree to a scroll pane int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(tree, v, h);

// Add scroll pane to the content pane contentPane.add(jsp, BorderLayout.CENTER);

// Add text field to applet jtf = new JTextField("", 20); contentPane.add(jtf, BorderLayout.SOUTH);

// Anonymous inner class to handle mouse clicks tree.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { doMouseClicked(me); } }); }

void doMouseClicked(MouseEvent me) { MCA-III Page 220

JAVA
TreePath tp = tree.getPathForLocation(me.getX(), me.getY()); if(tp != null) jtf.setText(tp.toString()); else jtf.setText(""); } }

11. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; /* <applet code="JTreeEvents" width=400 height=200> </applet> */

public class JTreeEvents1 extends JApplet { JTree tree; JTextField jtf;

MCA-III

Page 221

// Set layout manager contentPane. a.JAVA public void init() { // Get content pane Container contentPane = getContentPane().setLayout(new BorderLayout()). DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1"). // Create subtree of "A" DefaultMutableTreeNode a = new DefaultMutableTreeNode("A"). // Create top node of tree DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options"). MCA-III Page 222 .add(a1). top.add(a).add(a2). DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2"). a.

// Create tree tree = new JTree(top). b. JScrollPane jsp = new JScrollPane(tree. h).add(b3). b.add(b1). DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2"). DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3"). v.add(b2). MCA-III Page 223 . int h = ScrollPaneConstants.add(b). DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1"). top.VERTICAL_SCROLLBAR_AS_NEEDED.HORIZONTAL_SCROLLBAR_AS_NEEDED. // Add tree to a scroll pane int v = ScrollPaneConstants. b.JAVA // Create subtree of "B" DefaultMutableTreeNode b = new DefaultMutableTreeNode("B").

getY()).add(jtf. } }). 20).toString()). contentPane. BorderLayout. } MCA-III Page 224 . BorderLayout.add(jsp.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { doMouseClicked(me).SOUTH). else jtf. me.setText(tp.JAVA // Add scroll pane to the content pane contentPane.CENTER).getPathForLocation(me. if(tp != null) jtf. } void doMouseClicked(MouseEvent me) { TreePath tp = tree. // Add text field to applet jtf = new JTextField("". // Anonymous inner class to handle mouse clicks tree.setText("").getX().

net. OutputStream out = s. //Demonstrate Sockets. } br. InputStream in = s. class a { public static void main(String args[]) throws Exception { Socket s = new Socket("localhost". import java. 777).*.JAVA } NETWORKING PROGRAMS 1.close().readLine()) != null) { System.out. BufferedReader br=new BufferedReader(new InputStreamReader(in)).*. MCA-III Page 225 . while ((str=br.getInputStream().getOutputStream().print("fro ser"+str). String str.io. import java.

for (int i=0. class InetAddressTest { public static void main(String args[]) throws UnknownHostException { InetAddress Address = InetAddress.close().out.nba. Address = InetAddress. import java.println(Address).getAllByName("www.getByName("starwave.com").println(SW[i]). System. i<SW.length.println(Address). // Demonstrate InetAddress.net.JAVA s. import java. System. } } 3.com"). class patrickURL { MCA-III Page 226 . InetAddress SW[] = InetAddress.net. } } 2.out. // Demonstrate URL.*.out.getLocalHost().*. i++) System.

println("Protocol: " + hp. class ser { public static void main(String args[]) throws Exception { ServerSocket ss = new ServerSocket(777).JAVA public static void main(String args[]) throws MalformedURLException { URL hp = new URL("http://www. System.getProtocol()).out. System.getHost()).starwave.out.print("connection established"). MCA-III Page 227 .io.getFile()). System.net.getPort()).println("Port: " + hp. System.com/people/naughton/"). System.out. } } 4.out.out. //Demonstrate Sockets. import java.toExternalForm()). System. Socket s=ss.println("File: " + hp. import java.accept().println("Ext:" + hp.println("Host: " + hp.*.*.out.

// Demonstrate URLConnection.println(str). ps.net.println("bye"). import java.io.openConnection().*. class UCDemo { public static void main(String args[]) throws Exception { int c.util. PrintStream ps=new PrintStream(out). MCA-III Page 228 . ps.close(). URL hp = new URL("http://www.getOutputStream().JAVA OutputStream out = s. import java.starwave. import java. String str = "hello client" .Date. } } 5. ps. s.*.com/people/naughton/").close(). URLConnection hpCon = hp.

getContentLength().out.getDate())).println("No Content Available"). MCA-III Page 229 . //Demonstrate Sockets.out.println("Expires: " + hpCon. System.println("Content-Length: " + len). } input.out. InputStream input = hpCon.getInputStream().out. System.println("=== Content ==="). } else { System.out.println("Last-Modified: " + new Date(hpCon.close(). int len = hpCon.getContentType()). if (len > 0) { System.out.print((char) c).getLastModified())). } } } 6. int i = len.println("Date: " + new Date(hpCon.getExpiration()).JAVA System.println("Content-Type: " + hpCon. System.out.read()) != -1) && (--i > 0)) { System. System.out. while (((c = input.

net". // Demonstrate Datagrams. InputStream in = s.print((char) c). } } 7. MCA-III Page 230 .io.out.net.net.getOutputStream(). import java.*.close().length == 0 ? "starwave-dom" : args[0]) + "\n".write(buf). out. class Whois { public static void main(String args[]) throws Exception { int c. 43).JAVA import java. byte buf[] = str.*. OutputStream out = s.read()) != -1) { System.getBytes().getInputStream(). import java. while ((c = in. } s. String str = (args.*. Socket s = new Socket("internic.

while (true) { int c = System.JAVA class WriteServer { public static int serverPort = 666."). public static byte buffer[] = new byte[buffer_size]. public static void TheServer() throws Exception { int pos=0.pos. public static int buffer_size = 1024. public static int clientPort = 999.getLocalHost(). InetAddress. case '\r': break. switch (c) { case -1: System. case '\n': ds.in. break.send(new DatagramPacket(buffer. MCA-III Page 231 . public static DatagramSocket ds.out. return.clientPort)). pos=0.read().println("Server Quits.

getLength())).length). ds. } } public static void main(String args[]) throws Exception { if(args.JAVA default: buffer[pos++] = (byte) c. System. MCA-III Page 232 . TheClient(). buffer. } else { ds = new DatagramSocket(clientPort). p. TheServer().length == 1) { ds = new DatagramSocket(serverPort).receive(p).out. } } } public static void TheClient() throws Exception { while(true) { DatagramPacket p = new DatagramPacket(buffer. 0.println(new String(p.getData().

JAVA } } } MCA-III Page 233 .

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->