java lab manual
TRANSCRIPT
Dept. of MCA/Sir MVIT/ Bangalore 1
JAVA PROGRAMMING LABORATORY [10MCA37]
JAVA PROGRAMMING LABORATORY SUBJECT CODE: 10MCA37 I.A MARKS: 50 HRS/WEEK: 3 EXAM MARKS: 50 TOTAL HRS: 42 EXAM HRS: 3
1. a. Write a JAVA Program to demonstrate Constructor Overloading and Method
overloading.
b. Write a JAVA Program to implement Inner class and demonstrate its Access
Protections.
2. a. Write a JAVA Program to demonstrate Inheritance.
b. Write a JAVA Program to demonstrate Exception Handling (Using Nested
try catch and finally).
3. Write a JAVA program which has
i. A Class called Account that creates account with 500Rs minimum
balance, a deposit() method to deposit amount, a withdraw() method
to withdraw amount and also throws LessBalanceException if an
account holder tries to withdraw money which makes the balance
become less than 500Rs.
ii. A Class called LessBalanceException which returns the statement that
says withdraw amount (___Rs) is not valid.
iii. A Class which creates 2 accounts, both account deposit money and
one account tries to withdraw more money which generates a
LessBalanceException take appropriate action for the same.
4. Write a JAVA program using Synchronized Threads, which demonstrates
Producer Consumer concept.
5. Write a JAVA program which has
i. A Interface class for Stack Operations
ii. A Class that implements the Stack Interface and creates a fixed length
Stack.
iii. A Class that implements the Stack Interface and creates a Dynamic
length Stack.
iv. A Class that uses both the above Stacks through Interface reference and does the Stack operations that demonstrates the runtime binding.
6. Write a JAVA program which has
i. 2 classes which initializes a String in its constructor
ii. A Generic class with 2 type Parameters
iii. Create a Generic Class reference for the above 2 Class and try to print the message inside the constructor (Use to string method).
7. Write JAVA programs which demonstrates utilities of LinkedList Class
8. Write a JAVA Program which uses FileInputStream / FileOutPutStream
Classes.
Dept. of MCA/Sir MVIT/ Bangalore 2
JAVA PROGRAMMING LABORATORY [10MCA37]
9. Write a JAVA Program which writes a object to a file (use transient variable
also).
10. Write a JAVA program which uses Datagram Socket for Client Server
Communication.
11. Write JAVA Applet programs which handles MouseEvent
12. Write JAVA Applet programs which handles KeyBoardEvent
13. Write a JAVA program which implements RMI.
14. Write a Swing Application which uses
i. JTabbed Pane ii. Each Tab should use JPanel, which includes any one component given
below in each Panel
iii. ComboBox / List / Tree / Radiobutton
Note: All the above Components should listen to any one of their respective
events and print appropriate message.
Dept. of MCA/Sir MVIT/ Bangalore 3
JAVA PROGRAMMING LABORATORY [10MCA37]
1. a. WRITE A JAVA PROGRAM TO DEMONSTRATE CONSTRUCTOR OVERLOADING AND METHOD OVERLOADING.
SOURCE CODE:
class Add
{
int a,b;
Add()
{
System.out.println("Default Constructor Initialized ....");
a=10;b=20;
}
Add(int x,int y)
{
System.out.println("\nParameterized Constructor Initialized ....");
a=x;b=y;
}
void addition()
{
int sum;
sum=a+b;
System.out.println("A = "+a);
System.out.println("B = "+b);
System.out.println("Sum = "+sum);
}
void addition(Add ob)
{
int sum;
sum=ob.a+ob.b;
System.out.println("A = "+ob.a);
System.out.println("B = "+ob.b);
System.out.println("Sum = "+sum);
}
}
class Addition
{
public static void main(String arg[])
{
System.out.println("CONSTRUCTOR AND METHOD OVERLOADING\n");
Add ob=new Add();
ob.addition();
Add ob1=new Add(100,300);
ob1.addition(ob1);
}
}
Dept. of MCA/Sir MVIT/ Bangalore 4
JAVA PROGRAMMING LABORATORY [10MCA37]
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 5
JAVA PROGRAMMING LABORATORY [10MCA37]
1. b. WRITE A JAVA PROGRAM TO IMPLEMENT INNER CLASS AND DEMONSTRATE ITS ACCESS PROTECTIONS.
SOURCE CODE:
class Outer
{
private int x=100;
int y=200;
void test()
{
Inner ob=new Inner();
ob.display();
}
class Inner
{
int z=300;
void display()
{
System.out.println("Outer class private data x = "+x);
System.out.println("Outer class default data y = "+y);
System.out.println("Inner class data z = "+z);
z=x+y+z;
System.out.println("Sum = "+z);
}
}
}
class InnerDemo
{
public static void main(String arg[])
{
System.out.println("INNER CLASS ACCESS PROTECTION\n");
Outer ob=new Outer();
ob.test();
}
}
OURPUT
Dept. of MCA/Sir MVIT/ Bangalore 6
JAVA PROGRAMMING LABORATORY [10MCA37]
2. a. WRITE A JAVA PROGRAM TO DEMONSTRATE INHERITANCE.
SOURCE CODE:
class A
{
int a;
void showA()
{
System.out.println("A = "+a);
}
}
class B extends A
{
int b;
void showB()
{
System.out.println("B = "+b);
}
void sum()
{
int z;
z=a+b;
showA();
showB();
System.out.println("Sum = "+z);
}
}
class InheritDemo
{
public static void main(String arg[])
{
System.out.println("DEMONSTRATION OF INHERITANCE\n");
B ob=new B();
ob.a=10;
ob.b=20;
ob.sum();
}
}
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 7
JAVA PROGRAMMING LABORATORY [10MCA37]
2. b. WRITE A JAVA PROGRAM TO DEMONSTRATE EXCEPTION HANDLING (USING NESTED TRY CATCH AND FINALLY).
SOURCE CODE:
class NestTry
{
public static void main(String args[])
{
try
{
int a=args.length;
int b=42/a;
System.out.println("a = "+a);
try{
if(a==1) a=a/(a-a); // division bt zero
if(a==2){
int c[]={1}; c[32]=89;
}
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: "+e);
}
}catch(ArithmeticException e)
{
System.out.println("Divide by 0: "+e);
}
finally
{
System.out.println("Finally block executed:");
}}}
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 8
JAVA PROGRAMMING LABORATORY [10MCA37]
3. WRITE A JAVA PROGRAM WHICH HAS i. A CLASS CALLED ACCOUNT THAT CREATES ACCOUNT WITH
500RS MINIMUM BALANCE, A DEPOSIT() METHOD TO DEPOSIT AMOUNT, A WITHDRAW() METHOD TO WITHDRAW AMOUNT AND ALSO THROWS LESSBALANCEEXCEPTION IF AN ACCOUNT HOLDER TRIES TO WITHDRAW MONEY WHICH MAKES THE BALANCE BECOME LESS THAN 500RS.
ii. A CLASS CALLED LESSBALANCEEXCEPTION WHICH RETURNS THE STATEMENT THAT SAYS WITHDRAW AMOUNT (___RS) IS NOT VALID.
iii. A CLASS WHICH CREATES 2 ACCOUNTS, BOTH ACCOUNT DEPOSIT MONEY AND ONE ACCOUNT TRIES TO WITHDRAW MORE MONEY WHICH GENERATES A LESSBALANCEEXCEPTION TAKE APPROPRIATE ACTION FOR THE SAME.
SOURCE CODE:
import java.io.*;
class LessBalanceException extends Exception
{
LessBalanceException(double amt)
{
System.out.println("withdrawing "+amt+" is invalid ");
}
}
class Account
{
static int count=124;
int an;
double bal;
String name;
Account(double bal,String n)
{
System.out.println("\nNew Account Opened ...");
this.bal=bal; count++;
an=count;
name=n;
System.out.println("Ur Customer ID is :"+an);
}
void deposit(double amt)
{
System.out.println("\nAvailable Balance : "+bal);
bal=bal+amt;
System.out.println("Rs."+amt+"/- Credited ");
System.out.println("Balance : "+bal);
}
void withdraw(double amt)throws LessBalanceException
{
System.out.println("\nAvailable Balance : "+bal);
bal=bal-amt;
Dept. of MCA/Sir MVIT/ Bangalore 9
JAVA PROGRAMMING LABORATORY [10MCA37]
if(bal<500)
{
bal=bal+amt;
throw new LessBalanceException(amt);
}
System.out.println("Rs."+amt+"/- Debited");
System.out.println("Balance :\n"+bal);
}
void Balance()
{
System.out.println("Customer Information");
System.out.println("Customer ID : "+an);
System.out.println("Name :"+name);
System.out.println("Bal : "+bal);
}
}
class AccountDemo1
{
static int i=0;
public static void main(String arg[])throws IOException
{
Account ob[]=new Account[10];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
double amt;
String name;
int ch;
int an;
boolean b=true,f=false;
int k;
while(b)
{
System.out.println("BANKING OPERATION");
System.out.println("1: Opening New Account");
System.out.println("2: Deposit");
System.out.println("3: Withdraw");
System.out.println("4: Balance");
System.out.println("5: Exit");
System.out.println("Enter ur choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1: System.out.println("Opening New Account");
System.out.print("Enter ur Name: ");
name=br.readLine();
System.out.println("Enter initial amount(>Rs. 500/-)");
amt=Double.parseDouble(br.readLine());
ob[i]=new Account(amt,name);i++;
break;
case 2: System.out.println("Enter account number");
an=Integer.parseInt(br.readLine());
Dept. of MCA/Sir MVIT/ Bangalore 10
JAVA PROGRAMMING LABORATORY [10MCA37]
for(k=0;k<2;k++)
if(an==ob[k].an)
{
f=true; break;
}
if(f)
{
System.out.println("Enter amount for deposit: ");
amt=Double.parseDouble(br.readLine());
ob[k].deposit(amt);
}
else
System.out.println("Invalid Account No");
break;
case 3: System.out.println("Enter account number");
an=Integer.parseInt(br.readLine());
for(k=0;k<2;k++)
if(an==ob[k].an)
{
f=true; break;
}
if(f)
{
System.out.println("Enter amount for deposit: ");
amt=Double.parseDouble(br.readLine());
try
{
ob[k].withdraw(amt);
}catch(LessBalanceException e){}
}
else
System.out.println("Invalid Account No");
break;
case 4: System.out.println("Enter account number");
an=Integer.parseInt(br.readLine());
for(k=0;k<2;k++)
if(an==ob[k].an)
{
f=true; break;
}
if(f)
{
ob[k].Balance();
}
else
System.out.println("Invalid Account No");
break;
case 5: b=false;
System.exit(1);
default :System.out.println("invalid choice");
}
}
Dept. of MCA/Sir MVIT/ Bangalore 11
JAVA PROGRAMMING LABORATORY [10MCA37]
}}
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 12
JAVA PROGRAMMING LABORATORY [10MCA37]
Dept. of MCA/Sir MVIT/ Bangalore 13
JAVA PROGRAMMING LABORATORY [10MCA37]
Dept. of MCA/Sir MVIT/ Bangalore 14
JAVA PROGRAMMING LABORATORY [10MCA37]
4. WRITE A JAVA PROGRAM USING SYNCHRONIZED THREADS, WHICH DEMONSTRATES PRODUCER CONSUMER CONCEPT.
SOURCE CODE:
public class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
public class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("Producer #" + this.number
+ " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}
public class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer #" + this.number
+ " got: " + value);
}
Dept. of MCA/Sir MVIT/ Bangalore 15
JAVA PROGRAMMING LABORATORY [10MCA37]
}
}
public class CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) { }
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) { }
}
contents = value;
available = true;
notifyAll();
}
}
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 16
JAVA PROGRAMMING LABORATORY [10MCA37]
5. WRITE A JAVA PROGRAM WHICH HAS i. A INTERFACE CLASS FOR STACK OPERATIONS ii. A CLASS THAT IMPLEMENTS THE STACK INTERFACE AND
CREATES A FIXED LENGTH STACK. iii. A CLASS THAT IMPLEMENTS THE STACK INTERFACE AND
CREATES A DYNAMIC LENGTH STACK. iv. A CLASS THAT USES BOTH THE ABOVE STACKS THROUGH
INTERFACE REFERENCE AND DOES THE STACK OPERATIONS THAT DEMONSTRATES THE RUNTIME BINDING.
SOURCE CODE:
// Define an integer stack interface.
interface IntStack {
void push(int item); // store an item
int pop(); // retrieve an item
}
// An implementation of IntStack that uses fixed storage.
class FixedStack implements IntStack {
private int stck[];
private int tos;
// allocate and initialize stack
FixedStack(int size) {
stck = new int[size];
tos = -1;
}
// Push an item onto the stack
public void push(int item) {
if(tos==stck.length-1) // use length member
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
public int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
} else
return stck[tos--];
}}
// Implement a "growable" stack.
class DynStack implements IntStack {
private int stck[];
private int tos;
// allocate and initialize stack
DynStack(int size) {
Dept. of MCA/Sir MVIT/ Bangalore 17
JAVA PROGRAMMING LABORATORY [10MCA37]
stck = new int[size];
tos = -1;
}
// Push an item onto the stack
public void push(int item) {
// if stack is full, allocate a larger stack
if(tos==stck.length-1) {
int temp[] = new int[stck.length * 2]; // double size
for(int i=0; i<stck.length; i++) temp[i] = stck[i];
stck = temp;
stck[++tos] = item;
} else
stck[++tos] = item;
}
// Pop an item from the stack
public int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
} else
return stck[tos--];
}}
/* Create an interface variable and access stacks through it. */
class IFTest3 {
public static void main(String args[]) {
IntStack mystack; // create an interface reference variable
DynStack ds = new DynStack(5);
FixedStack fs = new FixedStack(8);
mystack = ds; // load dynamic stack
// push some numbers onto the stack
for(int i=0; i<12; i++) mystack.push(i);
mystack = fs; // load fixed stack
for(int i=0; i<8; i++) mystack.push(i);
mystack = ds;
System.out.println("Values in dynamic stack:");
for(int i=0; i<12; i++)
System.out.println(mystack.pop());
mystack = fs;
System.out.println("Values in fixed stack:");
for(int i=0; i<8; i++)
System.out.println(mystack.pop());
}}
Dept. of MCA/Sir MVIT/ Bangalore 18
JAVA PROGRAMMING LABORATORY [10MCA37]
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 19
JAVA PROGRAMMING LABORATORY [10MCA37]
6. WRITE A JAVA PROGRAM WHICH HAS
i. TWO CLASSES WHICH INITIALIZES A STRING IN ITS CONSTRUCTOR
ii. A GENERIC CLASS WITH 2 TYPE PARAMETERS
iii. CREATE A GENERIC CLASS REFERENCE FOR THE ABOVE 2 CLASS AND TRY TO PRINT THE MESSAGE INSIDE THE CONSTRUCTOR (USE TO STRING METHOD).
SOURCE CODE:
import java.io.*;
import java.lang.String;
class first
{
String s1;
first(String s)
{
s1=s;
}
void disp()
{
System.out.println(s1);
}
}
class second
{
String s2;
second(String s)
{
s2=s;
}
void disp()
{
System.out.println(s2);
}
}
class tg<T,V>
{
T ob1;
V ob2;
tg(T o1,V o2)
{
ob1=o1;
ob2=o2;
}
public String toString()
Dept. of MCA/Sir MVIT/ Bangalore 20
JAVA PROGRAMMING LABORATORY [10MCA37]
{
System.out.println("type of T is " +ob1.getClass().getName());
System.out.println("type of V is " +ob2.getClass().getName());
return("object referece is used to call toString()");
}
T getob1()
{
return ob1;
}
V getob2()
{
return ob2;
}
}
class lab6
{
public static void main(String args[])
{
System.out.println("Initializing Strings in class Constructors:");
System.out.println("------------------------------");
first f = new first("class1");
second s = new second("class2");
f.disp();
s.disp();
System.out.println("------------------------------");
System.out.println("Two Type parameters using generic class");
System.out.println("------------------------------");
tg<Integer,String> conobj=new tg<Integer,String>(99,"String-
generics");
System.out.println(conobj);
int v=conobj.getob1();
System.out.println("Value is : " +v);
String str=conobj.getob2();
System.out.println("String is : " +str);
System.out.println("--------------------------------------");
System.out.println("By using above two classes");
tg<first,second> obfs = new tg<first,second>(f,s);
System.out.println(obfs);
System.out.println("--------------------------------------");
}
}
Dept. of MCA/Sir MVIT/ Bangalore 21
JAVA PROGRAMMING LABORATORY [10MCA37]
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 22
JAVA PROGRAMMING LABORATORY [10MCA37]
7. WRITE JAVA PROGRAMS WHICH DEMONSTRATES UTILITIES OF
LINKEDLIST CLASS
SOURCE CODE:
/* Demonstrate LinkedList.*/
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
// create a linked list
LinkedList <String>ll = new LinkedList<String>();
// add elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// remove elements from the linked list
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: "+ ll);
// remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: " + ll);
// get and set a value
Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 23
JAVA PROGRAMMING LABORATORY [10MCA37]
8. WRITE A JAVA PROGRAM WHICH USES FILEINPUTSTREAM /
FILEOUTPUTSTREAM CLASSES.
import java.io.*;
public class FileInStreamDemo
{
public static void main(String[] args)
{
// create file object
File file = new File("DevFile.txt");
int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
while ((ch = fin.read()) != -1)
strContent.append((char) ch);
fin.close();
} catch (FileNotFoundException e) {
System.out.println("File " + file.getAbsolutePath() + " could not be found on
filesystem");
} catch (IOException ioe) {
System.out.println("Exception while reading the file" + ioe);
}
System.out.println("File contents :");
System.out.println(strContent);
}
}
OUTPUT
OR
import java.io.*;
public class FileOutStreamDemo
{
public static void main(String[] args)
{
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try {
// Create a new file output stream
// connected to "DevFile.txt"
Dept. of MCA/Sir MVIT/ Bangalore 24
JAVA PROGRAMMING LABORATORY [10MCA37]
out = new FileOutputStream("DevFile.txt");
// Connect print stream to the output stream
p = new PrintStream(out);
p.println("The text shown here will write to a file after run");
System.out.println("The Text is written to DevFile.txt");
p.close();
} catch (Exception e) {
System.err.println("Error writing to file");
}
}
}
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 25
JAVA PROGRAMMING LABORATORY [10MCA37]
9. WRITE A JAVA PROGRAM WHICH WRITES A OBJECT TO A FILE (USE
TRANSIENT VARIABLE ALSO).
import java.util.Vector;
import java.io.*;
public class SerializationTest
{
static long start,end;
OutputStream out = null;
OutputStream outBuffer = null;
ObjectOutputStream objectOut = null;
public Person getObject(){
Person p = new Person("SID","austin");
Vector<String> v = new Vector<String>();
for(int i=0;i<7000;i++){
v.addElement("StringObject:" +i);
}
p.setData(v);
return p;
}
public static void main(String[] args){
SerializationTest st = new SerializationTest();
start = System.currentTimeMillis();
st.writeObject();
end = System.currentTimeMillis();
System.out.println("Time taken for writing :"+ (end-start) + "milli
seconds");
}
public void writeObject(){
try{
out = new FileOutputStream("e:\\test.txt");
outBuffer = new BufferedOutputStream(out);
objectOut = new ObjectOutputStream(outBuffer);
objectOut.writeObject(getObject());
}catch(Exception e){e.printStackTrace();}
finally{
if(objectOut != null)
try{ objectOut.close();}catch(IOException e){e.printStackTrace();}
}
}
}
class Person implements java.io.Serializable
{
private String name;
private transient Vector data;
private String address;
public Person(String name,String address){
this.name = name;
this.address = address;
Dept. of MCA/Sir MVIT/ Bangalore 26
JAVA PROGRAMMING LABORATORY [10MCA37]
}
public String getAddress(){
return address;
}
public Vector getData(){
return data;
}
public String getName(){
return name;
}
public void setData(Vector data){
this.data = data;
}
}
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 27
JAVA PROGRAMMING LABORATORY [10MCA37]
10. WRITE A JAVA PROGRAM WHICH USES DATAGRAM SOCKET FOR CLIENT
SERVER COMMUNICATION.
SOURCE CODE:
import java.net.*;
class WriteServer {
public static int serverPort = 998;
public static int clientPort = 999;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];
public static void TheServer() throws Exception {
int pos=0;
while (true) {
int c = System.in.read();
switch (c) {
case -1:
System.out.println("Server Quits.");
return;
case '\r':
break;
case '\n':
ds.send(new DatagramPacket(buffer,pos,
InetAddress.getLocalHost(),clientPort));
pos=0;
break;
default:
buffer[pos++] = (byte) c;
}
}
}
public static void TheClient() throws Exception {
while(true) {
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
ds.receive(p);
System.out.println(new String(p.getData(), 0, p.getLength()));
}
}
public static void main(String args[]) throws Exception {
if(args.length == 1) {
ds = new DatagramSocket(serverPort);
TheServer();
} else {
ds = new DatagramSocket(clientPort);
TheClient();
}
}
}
Dept. of MCA/Sir MVIT/ Bangalore 28
JAVA PROGRAMMING LABORATORY [10MCA37]
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 29
JAVA PROGRAMMING LABORATORY [10MCA37]
11. WRITE JAVA APPLET PROGRAMS WHICH HANDLES MOUSE EVENT
SOURCE CODE:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
Dept. of MCA/Sir MVIT/ Bangalore 30
JAVA PROGRAMMING LABORATORY [10MCA37]
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) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 31
JAVA PROGRAMMING LABORATORY [10MCA37]
12. WRITE JAVA APPLET PROGRAMS WHICH HANDLES KEYBOARDEVENT
SOURCE CODE:
// Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet>
*/
public class SimpleKey extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 32
JAVA PROGRAMMING LABORATORY [10MCA37]
13. WRITE A JAVA PROGRAM WHICH IMPLEMENTS RMI.
SOURCE CODE:
AddServerIntf.java
import java.rmi.*;
public interface AddServerInf extends Remote
{ double add(double d1,double d2)throws RemoteException; }
AddServerImpl.java
import java.rmi.*;
import java.net.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf
{
public AddServerImpl()throws RemoteException{}
public double add(double d1,double d2)throws RemoteException
{ return d1+d2; }
}
AddClient.java
import java.rmi.*;
public class AddClient
{
public static void main(String arg[])
{
try
{ String addServerURL="rmi://"+arg[0]+"/AddServer";
AddServerIntf addServerIntf=(AddServerIntf)Naming.lookup(addServerURL);
System.out.println("The first number is : "+arg[1]);
double d1=Double.valueOf(arg[1]).doubleValue();
System.out.println("The Second number is : "+arg[2]);
double d2=Double.valueOf(arg[2]).doubleValue();
System.out.println("The sum is: "+addServerIntf.add(d1,d2));
}catch(Exception e){}
}
}
AddServer.java
import java.net.*;
import java.rmi.*;
public class AddServer
{
public static void main(String arg[])
{
try
{
AddServerImpl addServerImpl=new AddServerImpl();
Naming.rebind("AddServer",addServerImpl);
}catch(Exception e){}
}
}
Dept. of MCA/Sir MVIT/ Bangalore 33
JAVA PROGRAMMING LABORATORY [10MCA37]
OUTPUT
Dept. of MCA/Sir MVIT/ Bangalore 34
JAVA PROGRAMMING LABORATORY [10MCA37]
14. WRITE A SWING APPLICATION WHICH USES i. JTABBED PANE ii. EACH TAB SHOULD USE JPANEL, WHICH INCLUDES ANY ONE
COMPONENT GIVEN BELOW IN EACH PANEL iii. COMBOBOX / LIST / TREE / RADIOBUTTON
SOURCE CODE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
/*
<applet code="Lab14" width=600 height=600>
</applet>
*/
public class Lab14 extends JApplet
{
public void init()
{
try
{
SwingUtilities.invokeAndWait
(
new Runnable()
{
public void run()
{
makeGUI();
}
}
);
}
catch(Exception e)
{
System.out.println(e);
}
}
private void makeGUI()
{
JTabbedPane jtp=new JTabbedPane();
jtp.addTab("Cities",new CitiesPanel());
jtp.addTab("Color",new ColorPanel());
jtp.addTab("Flavors",new FlaverPanel());
jtp.addTab("Gender",new GenderPanel());
jtp.addTab("USN",new USNPanel());
jtp.addTab("Course",new CoursePanel());
add(jtp);
}
}
class CitiesPanel extends JPanel implements ActionListener
{
Dept. of MCA/Sir MVIT/ Bangalore 35
JAVA PROGRAMMING LABORATORY [10MCA37]
JLabel clab;
public CitiesPanel()
{
JButton b1=new JButton("NewYork");
b1.setActionCommand("NewYork");
b1.addActionListener(this);
add(b1);
JButton b2=new JButton("Landon");
b2.setActionCommand("Landon");
b2.addActionListener(this);
add(b2);
JButton b3=new JButton("HongKong");
b3.setActionCommand("HongKong");
b3.addActionListener(this);
add(b3);
JButton b4=new JButton("Tokyo");
b4.setActionCommand("Tokyo");
b4.addActionListener(this);
add(b4);
clab=new JLabel("Click a Button");
add(clab);
}
public void actionPerformed(ActionEvent ae)
{
clab.setText("You Clicked : "+ae.getActionCommand());
}
}
class ColorPanel extends JPanel implements ItemListener
{
JLabel colab;
JCheckBox cb;
public ColorPanel()
{
cb=new JCheckBox("red");
cb.addItemListener(this);
add(cb);
cb=new JCheckBox("green");
cb.addItemListener(this);
add(cb);
cb=new JCheckBox("Blue");
cb.addItemListener(this);
add(cb);
colab=new JLabel("Select A Color");
add(colab);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb=(JCheckBox)ie.getItem();
if(cb.isSelected())
colab.setText(cb.getText() + " is Selected ");
else
colab.setText(cb.getText() + " is Cleared ");
}
Dept. of MCA/Sir MVIT/ Bangalore 36
JAVA PROGRAMMING LABORATORY [10MCA37]
}
class FlaverPanel extends JPanel implements ActionListener
{
String clist[]={"vanila","Choclate","Strawberry"};
JLabel flab;
JComboBox jcb;
public FlaverPanel()
{
jcb=new JComboBox(clist);
jcb.addActionListener(this);
add(jcb);
flab=new JLabel("Select from Combo");
add(flab);
}
public void actionPerformed(ActionEvent ae)
{
flab.setText("You Selected : "+jcb.getSelectedItem());
}
}
class GenderPanel extends JPanel implements ActionListener
{
JLabel glab;
public GenderPanel()
{
JRadioButton rb1=new JRadioButton("M");
rb1.addActionListener(this);
add(rb1);
JRadioButton rb2=new JRadioButton("F");
rb2.addActionListener(this);
add(rb2);
ButtonGroup bg1=new ButtonGroup();
bg1.add(rb1);
bg1.add(rb2);
glab=new JLabel("Select One");
add(glab);
}
public void actionPerformed(ActionEvent ae)
{
glab.setText("You Clicked : "+ae.getActionCommand());
}
}
class USNPanel extends JPanel implements ListSelectionListener
{
JLabel ulab;
JList jlst;
String
Usn[]={"1BY10MCA01","1BY10MCA02","1BY10MCA03","1BY10MCA04","1BY10MCA0
5","1BY10MCA06","1BY10MCA07","1BY10MCA08","1BY10MCA09","1BY10MCA10"};
public USNPanel()
{
jlst=new JList(Usn);
jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane jscrlp=new JScrollPane(jlst);
Dept. of MCA/Sir MVIT/ Bangalore 37
JAVA PROGRAMMING LABORATORY [10MCA37]
jscrlp.setPreferredSize(new Dimension(100,80));
jlst.addListSelectionListener(this);
add(jscrlp);
ulab=new JLabel("Select One");
add(ulab);
}
public void valueChanged(ListSelectionEvent le)
{
int idx=jlst.getSelectedIndex();
if(idx!=-1)
ulab.setText("Current Selection "+Usn[idx]);
else
ulab=new JLabel("Select One");
}
}
class CoursePanel extends JPanel implements TreeSelectionListener
{
JLabel tlab;
public CoursePanel()
{
DefaultMutableTreeNode top =new
DefaultMutableTreeNode("Course");
DefaultMutableTreeNode a =new DefaultMutableTreeNode("UG");
DefaultMutableTreeNode a1 =new DefaultMutableTreeNode("BA");
DefaultMutableTreeNode a2 =new DefaultMutableTreeNode("BSc");
DefaultMutableTreeNode a3 =new DefaultMutableTreeNode("BCA");
DefaultMutableTreeNode b =new DefaultMutableTreeNode("PG");
DefaultMutableTreeNode b1 =new DefaultMutableTreeNode("MA");
DefaultMutableTreeNode b2 =new DefaultMutableTreeNode("MSc");
DefaultMutableTreeNode b3 =new DefaultMutableTreeNode("MCA");
top.add(a);
a.add(a1);
a.add(a2);
a.add(a3);
top.add(b);
b.add(b1);
b.add(b2);
b.add(b3);
JTree jt=new JTree(top);
JScrollPane jsp=new JScrollPane(jt);
jsp.setPreferredSize(new Dimension(150,200));
jt.addTreeSelectionListener(this);
add(jsp);
tlab=new JLabel("Select One");
add(tlab);
}
public void valueChanged(TreeSelectionEvent tse)
{
tlab.setText("Current Selection "+tse.getPath());
}
}
Dept. of MCA/Sir MVIT/ Bangalore 38
JAVA PROGRAMMING LABORATORY [10MCA37]
OUTPUT