Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Java Lab Manual

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Lab Manual

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

MATRUSRI ENGINEERING COLLEGE

(Affiliated to Osmania University & Recognized by AICTE)


Saidabad, Hyderabad

JAVA LAB MANUAL

1
MATRUSRI ENGINEERING COLLEGE
(Affiliated to Osmania University, Hyderabad)
Saidabad, Hyderabad-501510

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Subject : JAVA LAB Acad. Year :

Class : BE II/IV Sem - II Section :

INDEX
Date Pages
S.No. Name of theProgram
Experiment Submission From To
01 Write a Program to implement the
concept of class with constructor
overloading.
02 Write a Program to implement the
concept of method overriding.
03 Write a Program to illustrate the usage of
abstract class and Dynamic method
Dispatching.
04 Write a Program to implement multiple
inheritance using interfaces
05 Develop applications demonstrating
various Access specifiers in packages.
06 Write a Program to implement
predefined Exceptions.
07 Develop an application demonstrating
stack operations with User defined
exceptions.
08 Write a Program to create threads using
Thread class
09 Write a Program to create threads
Runnable Interface
10 Write a Program to Implement Producer-
Consumer Problem.
11 Write a Program to illustrate usage of all
String handling methods
12 Write a Program to demonstrate
StringTokenizer
13 Write a Program to demonstrate
LinkedList and ArrayList

2
Date Pages
S.No. Name of theProgram
Experiment Submission From To
14 Write a Program using Hash Set and
Iterator classes
15 Write a Program using Vector and
Enumeration Classes
16 Write a Program to demonstrates
collection algorithms
17 Write a Program demonstarting the use
of Comparator
18 Write a program to copy contents of one
file to another using byte streams
19 Write a program to compare two files
using character streams.
20 Develop an application demonstrating
Serialization
21 Write a Program to implement Simple
moving banner using Applet life cycle
methods.
22 Develop an application using Checkbox
and Label controls with Applets.
23 Develop an application demonstrating
Choice Lists and Text Area with Applets.
24 Develop an Application using Lists and
Text Field controls with Applet
25 Develop an application using Menu
controls with Frames
26 Write a Program to implement all Mouse
handling events with Applets
27 Write a Program to implement Key
events with Applets

3
1. Write a Program to implement the concept of class with constructor overloading.
class Abc
{
int a,b;
Abc() //non-parameterized constructor
{
a=b=1;
}
Abc(int x) //parameterized constructor
{
a=b=x;
}

Abc(int x,int y) // parameterized constructor


{
a=x;
b=y;
}
int add()
{
return (a+b);
}
}
class ConstructorOverload
{
public static void main(String[] args)
{
Abc x=new Abc(3,5), y=new Abc(), z=new Abc(7);
System.out.println(x.add());
System.out.println(y.add());
System.out.println(z.add());
}
}

Output:

4
2. Write a Program to implement the concept of method overriding.

class Abc
{
int a;
Abc(int x)
{
a=x;
}
void display()
{
System.out.println("a="+a);
}
}
class XYZ extends Abc

{
int b;
XYZ(int y,int z)
{
super(z);
b=y;
}
void display()
{
super.display();
System.out.println("b="+b);

}
}

class Methodoverride
{
public static void main(String args[])
{
XYZ p=new XYZ(5,9);
p.display();
}

Output:

5
3. Write a Program to illustrate the usage of abstract class and Dynamic method Dispatching.

abstract class polygon


{
double a,b;
polygon()
{
}

polygon(double x,double y)
{
a=x;
b=y;
}
abstract double area();
}
class Triangle extends polygon
{
Triangle(double x,double y)
{
super(x,y);
}
double area()
{
System.out.println("area of right angled triangle ");
return 0.5*a*b;
}
}
class Rectangle extends polygon
{
Rectangle(double x,double y)
{
super(x,y);
}

double area()
{
System.out.println("area of rectangle is");
return (a*b);
}
}
class Abstract_class
{
public static void main(String args[])
{
polygon p;
Triangle t=new Triangle(1.5,2.7);
p=t;
System.out.println(p.area());
p=new Rectangle(2.5,1.3);
System.out.println(p.area());
} }

6
Output:

7
4. Write a Program to implement multiple inheritance using interfaces

class MyClass
{
int a=2,b=5;
}
//defining interface One
interface One
{
void display();
}
//defining interface Two
interface Two
{
int add();
}
//Inheriting MyClass,One,Two
class MultipleInherit extends MyClass implements One,Two
{
public void display()
{
System.out.println("a="+a+"\tb="+b);
}
public int add()
{
return (a+b);
}
public static void main(String[] args)
{
MultipleInherit x=new MultipleInherit();
x.display();
System.out.println("a+b="+x.add());
}
}

Output:

8
5. Develop applications demonstrating various Access specifiers in packages.

//This is file Protection.java


package p1;
public class Protection
{
int n = 1;
private int pri = 2;
protected int pro = 3;
public int pub = 4;
public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("pri = " + pri);
System.out.println("pro = " + pro);
System.out.println("pub = " + pub);
}
}
//This is file Derived.java
package p1;
class Derived extends Protection
{
Derived()
{
System.out.println("derived constructor");
System.out.println("n = " + n);
// class only
// System.out.println(pri = " + pri);
System.out.println("pro = " + pro);
System.out.println("pub = " + pub);
}
}
//This is file SamePackage.java
package p1;
class SamePackage
{
SamePackage()
{
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
// class only
// System.out.println("pri = " + p.pri);
System.out.println("pro = " + p.pro);
System.out.println("pub = " + p.pub);
}
}
//This is file Protection2.java
package p2;
class Protection2 extends p1.Protection
{

9
Protection2()
{
System.out.println("derived other package constructor");
// class or package only
// System.out.println("n = " + n);
// class only
// System.out.println("pri = " + pri);
System.out.println("pro = " + pro);
System.out.println("pub = " + pub);
}
}
//This is file OtherPackage.java
package p2;
class OtherPackage
{
OtherPackage()
{
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// class or package only
// System.out.println("n = " + p.n);
// class only
// System.out.println("pri = " + p.pri);
// class, subclass or package only
// System.out.println("pro = " + p.pro);
System.out.println("pub = " + p.pub);
}
}
/This is file Demo1.java
// Demo package p1.
package p1;
// Instantiate the various classes in p1.
public class Demo1
{
public static void main(String args[])
{
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}
//This is file Demo2.java
// Demo package p2.
package p2;
// Instantiate the various classes in p2.
public class Demo2
{
public static void main(String args[])
{
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
} }

10
Output:

11
12
6. Write a Program to implement predefined Exceptions.

class ExceptionsDemo
{
int p=9;
public static void main(String[] args)
{
int d[ ]={10,20,30,40};
try
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a/b;
System.out.println(c);
System.out.println("NO EXCEPTION");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Trying to access array out of its range");
}
catch (ArithmeticException e)
{
System.out.println("Value of b must not be zero");
}
catch (NumberFormatException e)
{
System.out.println("Invalid conversion of string exception raised");
}
try
{
for(int i=0;i<5;i++)
System.out.print(d[i]+"\n");
System.out.println("NO EXCEPTION");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Trying to access array out of its range");
}
try
{
int x[ ]=new int[-3];
}
catch (NegativeArraySizeException e)
{
System.out.println("Negative array Size Exception Raised");
}

try
{
ExceptionsDemo f=null;
//A NullPointerException is thrown if an attempt
//is made to use a null object

13
System.out.println(f.p);
}
catch(NullPointerException e)
{
System.out.println("null pointer exception");
}
}
}

Output:

14
7. Develop an application demonstrating stack operations with User defined exceptions.

class StackOverflowException extends Exception


{
StackOverflowException()
{
System.out.println("stackOverflowException has been raised");
}
}
class StackUnderflowException extends Exception
{
StackUnderflowException()
{
System.out.println("StackUnderflowException has been raised");
}
}
class Mystack
{
int top= -1,x,size=5;
int st[ ]=new int[size];
void push(int y)
{
try
{
if(top= =size-1)
throw(new StackOverflowException());
st[++top]=y;
}

//Empty catch block, since every try must have a catch


catch(Exception e)
{
}
}
int pop()
{
try
{
if(top= =-1)
throw(new StackUnderflowException());
x=st[top--];
}
catch(Exception e)
{
}
return x;
}
void peep()
{
try
{
if(top= =-1)

15
throw (new StackUnderflowException());
System.out.println("The elements of stack are:");
for(int i=top;i>=0;i - -)
System.out.println(st[i]+"\t");
}
catch(Exception e)
{
}
}
}
class StackExceptions
{
public static void main(String[] args)
{
Mystack s=new Mystack();
s.push(10);
s.push(20);
s.push(30);
s.push(40);
s.push(50);
s.push(60);
s.peep();
int x=s.pop();
System.out.println(x+"is deleted from stack");
s.peep();
x=s.pop();
System.out.println(x+"is deleted from stack");
x=s.pop();
System.out.println(x+"is deleted from stack");
x=s.pop();
System.out.println(x+"is deleted from stack");
x=s.pop();
System.out.println(x+"is deleted from stack");
x=s.pop();
s.peep();
}
}

16
Output:

17
8. Write a Program to create threads using Thread class

class NewThread extends Thread


{
String name;
NewThread(String s)
{
// Create a new thread
super(s);
name=s;
System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the new thread.
public void run()
{
try
{
for(int i = 5; i > 0; i - -)
{
System.out.println(name+":" + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThreadDemo
{
public static void main(String args[])
{
new NewThread("ONE"); // create a new thread
try {
for(int i = 5; i > 0; i - -)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

18
Output:

19
9. Write a Program to create threads Runnable Interface

class NewThread implements Runnable


{
Thread t;
NewThread()
{
// Create a new thread
t = new Thread(this, "ONE");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the new thread.
public void run()
{
try {
for(int i = 5; i > 0; i - -) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ImplementRunnableDemo
{
public static void main(String args[ ])
{
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i - -) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

20
Output:

21
10. Write a Program to Implement Producer-Consumer Problem.

class Q
{
int n;
boolean valueSet = false;
synchronized int get( )
{
if(!valueSet)
try {
wait( );
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify( );
return n;
}
synchronized void put(int n)
{
if(valueSet)
try {
wait( );
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q = q;
new Thread(this, "Producer").start();
}
public void run( )
{
int i = 0;
while(true)
{
q.put(i++);
}

22
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q = q;
new Thread(this, "Consumer").start();
}
public void run( )
{
while(true)
{
q.get( );
}
}
}
class Producer_ConsumerDemo
{
public static void main(String args[ ])
{
Q q = new Q( );
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
Output:

23
11. Write a Program to illustrate usage of all String handling methods

class StringsDemo
{
public static void main(String args[])
{
String s1="Hello welcome to java",s2=new String(s1),s3="he",s4="java";
char c[ ]=new char[3];
System.out.println(s1.charAt(4));
s1.getChars(2,5,c,0);
System.out.println(c);
System.out.println(s1.getBytes( ));
if(s1.equals(s2))
System.out.println("EQUAL STRINGS");
else
System.out.println("UNEQUAL STRINGS");
if(s1.startsWith(s3))
System.out.println(s1+"STARTS WITH "+s3);
else
System.out.println(s1+"DOES NOT START WITH "+s3);
if(s1.endsWith(s4))
System.out.println(s1+"ENDS WITH "+s4);
else
System.out.println(s1+"DOES NOT END WITH "+s4);
int x=s1.compareTo(s3);
if(x==0)
System.out.println(s1+" and "+s3+" are equal");
else if(x>0)
System.out.println(s1+" IS GREATER THAN "+s3);
else
System.out.println(s1+"IS LESS THAN "+s3);
System.out.println("index of first occurrence a is : "+s1.indexOf('a'));
System.out.println("index of last occurrence a is : "+s1.lastIndexOf('a'));
System.out.println("index of first occurrence ll is : "+s1.indexOf("ll"));
System.out.println("index of last occurrence ll is : "+s1.lastIndexOf("ll"));
s3=s1.substring(3);
System.out.println(s3);
s3=s1.substring(2,5);
System.out.println(s3);
System.out.println(s1.concat(s2));
System.out.println(s1.replace('e','a'));
}
}

24
Output:

25
12. Write a Program to demonstrate StringTokenizer

import java.util.*;
class StringTokenizerDemo
{
public static void main(String[ ] args)
{
StringTokenizer s1=new StringTokenizer("Hello,Welcome to java");
StringTokenizer s2=new StringTokenizer("Hello,Welcome to java","o");
StringTokenizer s3=new StringTokenizer("Hello,Welcome to java","o",true);
System.out.println("The no.of tokens in s1 are:"+s1.countTokens( ));
while(s1.hasMoreTokens( ))
{
System.out.println(s1.nextToken( ));
}
System.out.println("The no.of tokens in s2 are:"+s2.countTokens( ));
while(s2.hasMoreTokens( ))
{
System.out.println(s2.nextToken( ));
}
System.out.println("The no.of tokens in s3 are:"+s3.countTokens( ));
while(s3.hasMoreTokens( ))
{
System.out.println(s3.nextToken( ));
}
}
}

Output:

26
13. Write a Program to demonstrate LinkedList and ArrayList

import java.util.*;
class ArrayLinkedDemo
{
public static void main(String args[ ])
{
// create an array list
ArrayList A = new ArrayList( );
LinkedList L = new LinkedList( );
System.out.println("Initial size of A: "+A.size( ));
// add elements to the array list
A.add("Object");
A.add("Oriented");
A.add("Programming");
// display the array list
System.out.println("Contents of A: " +A);
A.add(0,"Welcome to");
A.add(4,"JAVA");
A.add(4,"Using");
// display the array list
System.out.println("Contents of al: "+A);
System.out.println("Size of al after additions: "+A.size( ));
// Remove elements from the array list
A.remove("Using");
System.out.println("Contents of al: "+A);
A.remove(4);
System.out.println("Contents of al: "+A);
System.out.println("Size of al after deletions: "+A.size( ));
//List operations
System.out.println("Initial size of L: "+L.size( ));
// add elements to the array list
L.add("Object");
L.add("Oriented");
L.add("Programming");
// display the array list
System.out.println("Contents of al: "+L);
L.addFirst("Welcome to");
L.addLast("JAVA");
L.add(4,"Using");
// display the array list
System.out.println("Contents of al: "+L);
System.out.println("Size of al after additions: "+L.size( ));
// Remove elements from the array list
L.removeFirst( );
System.out.println("Contents of al: "+L);
L.removeLast( );
System.out.println("Contents of al: "+L);
System.out.println("Size of al after deletions: "+L.size( ));
L.remove(3);
System.out.println("Contents of al: "+L);
System.out.println("Size of al after deletions: "+L.size( ));

27
}
}

Output:

28
14. Write a Program using Hash Set and Iterator classes

import java.util.*;
class HashSet_Iterator
{
public static void main(String args[])
{
// create a hash set
HashSet hs = new HashSet( );
// add elements to the hash set
hs.add(new Integer(10));
hs.add(new Integer(20));
hs.add(new Integer(30));
hs.add(new Integer(40));
hs.add(new Integer(70));
System.out.println("HASH SET: "+hs);
//Iterator to access the Hashset
Iterator it=hs.iterator( );
System.out.println("HASH SET: ");
while(it.hasNext( ))
{
System.out.println(it.next( ));
}
}
}

Output:

29
15. Write a Program using Vector and Enumeration Classes

import java.util.*;
class VectorEnum
{
public static void main(String[] args)
{
Vector v=new Vector( );
v.add("Object");
v.add("Oriented");
v.add("Programming");
v.add(0,"Welcome to");
System.out.println("Vector:"+v);
System.out.println("First Element:"+v.firstElement( ));
System.out.println("First Element:"+v.lastElement( ));
System.out.println("First Element:"+v.elementAt(1));
v.setElementAt("Hello",0);
System.out.println("Vector:"+v);
v.removeElementAt(2);
System.out.println("Vector:"+v);
v.removeElement("Object");
System.out.println("Vector:"+v);
System.out.println("Vector Size after deletion:"+v.size( ));
v.insertElementAt("JAVA",1);
System.out.println("Vector:"+v);
System.out.println("Elements of Vector:");
//Using Enumerator
Enumeration e=v.elements( );
while(e.hasMoreElements( ))
{
System.out.println(e.nextElement( ));
}
}
}
Output:

30
16. Write a Program to demonstrates collection algorithms

import java.util.*;
class CollectionAlgs
{
public static void main(String args[])
{
LinkedList<Integer> ll=new LinkedList<Integer>();
ll.add(-8); ll.add(20);ll.add(-20);ll.add(8);
//crate reverse order comparator
Comparator<Integer> r=Collections.reverseOrder();
System.out.print("List : ");
for(int i : ll)
System.out.print(i+ "");
System.out.println();
//Sort list by using comparator
Collections.sort(ll,r);
System.out.print("List sorted in reverse: ");
for(int i : ll)
System.out.print(i+ "");
System.out.println();
//shuffle list
Collections.shuffle(ll);
System.out.print("List after shuffle ");
for(int i: ll)
System.out.print(i+"");
System.out.println();
System.out.println("Minimum: "+Collections.min(ll));
System.out.println("Max: "+Collections.max(ll));
}
}

Output:

31
17. Write a Program demonstarting the use of Comparator

import java.util.*;
class MyComp implements Comparator<String>
{
public int compare(String a,String b)
{
String aStr,bStr;
aStr=a; bStr=b;
System.out.println("in compare "+aStr+""+bStr);
return bStr.compareTo(aStr);
}
}
class ComparatorDemo
{
public static void main(String args[])
{
TreeSet<String> ts=new TreeSet<String>(new MyComp());
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("i");
for(String ele: ts)
System.out.print(ele + "");
System.out.println();
}
}

Output:

32
18. Write a program to copy contents of one file to another using byte streams

import java.io.*;
class FileCopy
{
public static void main(String[] args)throws IOException
{
FileInputStream fin;
FileOutputStream fout;
int i;
//Open source file
try
{
fin=new FileInputStream("/home/lab4sys-8/Files/file1.txt");
}
catch(FileNotFoundException e)
{
System.out.println("source file can't be opened");
return;
}
//Open Destination file
try
{
fout=new FileOutputStream("/home/lab4sys-8/file2.txt");
}
catch(FileNotFoundException e)
{
System.out.println("Destination file can't be created");
return;
}
//Copy from source file to destination file
try
{
do
{
i=fin.read( );
if(i!=-1)
fout.write(i);
}while(i!=-1);
}
catch(IOException e)
{
System.out.println("File reading error");
}
fin.close( );
fout.close( );
}
}

Note: Open both the files “file1.txt” and “file2.txt” and see the contents.

33
19. Write a program to compare two files using character streams.

import java.io.*;
class FileCompare
{
public static void main(String[] args) throws IOException
{
int f=1;
FileReader f1,f2;
char ch1,ch2;
try
{
f1=new FileReader("/home/lab4sys-8/Files/file1.txt");
f2=new FileReader("/home/lab4sys-8/file2.txt");
ch1=(char)f1.read();
ch2=(char)f2.read();
while((ch1!=(char)-1) || (ch2!=(char)-1))
{
if(ch1!=ch2)
{
f=0;
break;
}
ch1=(char)f1.read( );
ch2=(char)f2.read( );
}
}
catch(FileNotFoundException e)
{
System.out.println("one of the Files can't be opened for comparison");
System.exit(0);
}
if(f==1)
System.out.println("FILES ARE EQUAL");
else
System.out.println("FILES ARE NOT EQUAL");
}
}

Output:

34
20. Develop an application demonstrating Serialization

import java.io.*;
public class SerializationDemo
{
public static void main(String args[ ])
{
// Object serialization
try
{
MyClass object1 = new MyClass("Hello", -7, 2.7e10);
System.out.println("object1: " + object1);
FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush( );
oos.close( );
}
catch(Exception e)
{
System.out.println("Exception during serialization: " + e);
System.exit(0);
}
// Object deserialization
try
{
MyClass object2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
object2 = (MyClass)ois.readObject( );
ois.close( );
System.out.println("object2: " + object2);
}
catch(Exception e)
{
System.out.println("Exception during deserialization: " + e);
System.exit(0);
}
}
}
class MyClass implements Serializable
{
String s;
int i;
double d;
public MyClass(String s, int i, double d)
{
this.s = s;
this.i = i;
this.d = d;
}
public String toString()

35
{
return "s=" + s + "; i=" + i + "; d=" + d;
}
}

Output:

36
21. Write a Program to implement Simple moving banner using Applet life cycle methods.

/* A simple banner applet.


This applet creates a thread that scrolls
the message contained in msg right to left
across the applet's window.
*/
import java.awt.*;
import java.applet.*;
/*
<applet code="BannerApplet" width=400 height=200>
</applet>
*/
public class BannerApplet extends Applet implements Runnable
{
String msg = " Welcome to MVSR ";
Thread t = null;
boolean stopFlag;
// Set colors and initialize thread.
public void init( )
{
setBackground(Color.pink);
setFont(new Font("SansSerif", Font.BOLD, 28));
}
// Start thread
public void start( )
{
t = new Thread(this);
stopFlag = false;
t.start( );
}
// Entry point for the thread that runs the banner.
public void run( )
{
char ch;
// Display banner
for( ; ; )
{
try {
repaint( );
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1, msg.length( ));
msg += ch;
if(stopFlag)
break;
} catch(InterruptedException e) { }
}
}
// Pause the banner.
public void stop( )
{

37
stopFlag = true;
t = null;
}
// Display the banner.
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawString(msg, 100, 100);
}
}

Output:

38
22. Develop an application using Checkbox and Label controls with Applets.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CheckboxDemo" width=400 height=200>
</applet>
*/
public class CheckboxDemo extends Applet implements ItemListener
{
String msg = "";
Checkbox c1,c2,c3,c4,c5,c6;
public void init()
{
setBackground(Color.pink);
Label l1 = new Label("Programming Skills",Label.CENTER);
c1 = new Checkbox("C", null, true);
c2 = new Checkbox("c++");
c3 = new Checkbox("JAVA");
c4 = new Checkbox("Oracle");
Label l2 = new Label("Operating systems:",Label.RIGHT);
c5 = new Checkbox("Windows NT", null, true);
c6 = new Checkbox("Linux");
add(l1);
add(c1);
add(c2);
add(c3);
add(c4);
add(l2);
add(c5);
add(c6);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
c5.addItemListener(this);
c6.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g)
{
msg = "Softwares familier with: ";
g.drawString(msg, 6,120 );
msg="";
if(c1.getState( ))
msg+="C,";
if(c2.getState( ))

39
msg+="C++,";
if(c3.getState( ))
msg+="JAVA,";
if(c4.getState( ))
msg+="Oracle,";
if(c5.getState())
msg+="Windows NT,";
if(c6.getState( ))
msg+="Linux";
g.drawString(msg, 5, 150);
}
}

Output:

40
23. Develop an application demonstrating Choice Lists and Text Area with Applets.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ChoiceTextarea" width=300 height=180> </applet>
*/
public class ChoiceTextarea extends Applet implements ItemListener
{
Choice ch1,ch2;
TextArea t1;
String msg = "";
public void init()
{
ch1 = new Choice( );
ch2 = new Choice( );
t1=new TextArea(5,20);
add(t1);
// add items to First choice list
ch1.add("B.Sc."); //by default first item will be shown in the list
ch1.add("B.E.");
ch1.add("MBA");
ch1.add("MCA");
ch1.add("MTech");
// add items to Second choice list
ch2.add("JNTU");
ch2.add("OU");
ch2.add("KU");
ch2.add("AU");
ch2.add("HCU");
ch2.add("None");
ch2.select("None");//item will be shown in choice list
// add choice lists to window
add(ch1);
add(ch2);
ch2.requestFocus();
// register to receive item events
ch1.addItemListener(this);
ch2.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
// Display current selections.
public void paint(Graphics g)
{
String x=ch1.getSelectedItem( );
t1.setText("Pursuing "+x+" at "+ch2.getSelectedItem());
}
}

41
Output:

42
24. Develop an Application using Lists and Text Field controls with Applet

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="ListDemo" width=300 height=180> </applet> */
public class ListDemo extends Applet implements ActionListener,ItemListener
{
List os, browser;
TextField t1,t2;
String msg = "";
public void init()
{
os = new List(4, true);
browser = new List(4, false);
t1=new TextField(30);
t2=new TextField(30);
// add items to os list
os.add("Windows 98/XP");
os.add("Windows NT/2000");
os.add("Solaris");
os.add("MacOS");
// add items to browser list
browser.add("Netscape 3.x");
browser.add("Netscape 4.x");
browser.add("Netscape 5.x");
browser.add("Netscape 6.x");
browser.add("Internet Explorer 4.0");
browser.add("Internet Explorer 5.0");
browser.add("Internet Explorer 6.0");
browser.add("Lynx 2.4");
browser.select(1);
// add lists to window
add(os);
add(browser);
//add textfields to window
add(t1);
add(t2);
// register to receive action events
os.addActionListener(this);
browser.addActionListener(this);
os.addItemListener(this);
browser.addItemListener(this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}

43
// Display current selections.
public void paint(Graphics g)
{
int idx[ ];
msg = "Current OS: ";
idx = os.getSelectedIndexes( );
for(int i=0; i<idx.length; i++)
msg += os.getItem(idx[i]) + ",";
//Display the selections in text field
t1.setText(msg);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
//Display the selections in text field
t2.setText(msg);
}
}

Output:

44
25. Develop an application using Menu controls with Frames

import java.awt.*;
import java.awt.event.*;
class MenusDemo extends Frame implements ActionListener
{
Menu m1,m2,m3;
MenuBar mb=new MenuBar( );
MenuItem m4,m5,m6,m7,m8,m9,m10;
int ch=0;
char cl;
MenusDemo( )
{
setSize(400,400);
setVisible(true);
setLayout(new FlowLayout());
m1=new Menu("colors");
m2=new Menu("draw");
m3=new Menu("shape");
m4=new MenuItem("pink");
m5=new MenuItem("cyan");
m6=new MenuItem("yellow");
m7=new MenuItem("exit");
m8=new MenuItem("Line");
m9=new MenuItem("Rectangle");
m10=new MenuItem("circle");
m1.add(m4);
m1.add(m5);
m1.add(m6);
m1.add(m7);
m3.add(m8);
m3.add(m9);
m3.add(m10);
m2.add(m3);
setMenuBar(mb);
mb.add(m2);
mb.add(m1);
m4.addActionListener(this);
m5.addActionListener(this);
m6.addActionListener(this);
m7.addActionListener(this);
m8.addActionListener(this);
m9.addActionListener(this);
m10.addActionListener(this);
addWindowListener(new MyWindowAdapter(this));
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==m4)
cl='P';
if(ae.getSource()==m5)
cl='B';

45
if(ae.getSource()==m6)
cl='Y';
if(ae.getSource()==m7)
System.exit(0);
if(ae.getSource()==m8)
ch=1;
if(ae.getSource()==m9)
ch=2;
if(ae.getSource()==m10)
ch=3;
repaint();
}
public void paint(Graphics g)
{
switch(cl)
{
case 'P':setBackground(Color.pink);
break;
case 'C':setBackground(Color.cyan);
break;
case 'Y':setBackground(Color.yellow);
break;
}
switch(ch)
{
case 1: g.setColor(Color.red);
g.drawLine(70,70,150,180);
break;
case 2: g.setColor(Color.green);
g.fillRect(80,80,70,40);
break;
case 3: g.setColor(Color.blue);
g.fillOval(80,80,70,70);
break;
}
}
public static void main(String[ ] args)
{
MenusDemo f=new MenusDemo( );
}
}
class MyWindowAdapter extends WindowAdapter
{
MenusDemo f;
public MyWindowAdapter(MenusDemo f)
{
this.f=f;
}
public void windowClosing(WindowEvent w)
{
f.setVisible(false);
} }

46
Output:

47
26. Write a Program to implement all Mouse handling events with Applets

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

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

Output:

49
27. Write a Program to implement Key events with Applets

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEvents" width=300 height=100>
</applet>
*/
public class KeyEvents extends Applet implements KeyListener
{
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init()
{
setBackground(Color.pink);
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
int key = ke.getKeyCode();
switch(key)
{
case KeyEvent.VK_F1:
msg += "<F1>";
break;
case KeyEvent.VK_F2:
msg += "<F2>";
break;
case KeyEvent.VK_F3:
msg += "<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>";
break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
case KeyEvent.VK_HOME:
msg += "<HOME>";
break;
case KeyEvent.VK_SHIFT:
msg += "<SHIFT>";
break;
}

50
repaint();
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}

Output:

51

You might also like