You are on page 1of 70

EX 1 : RATIONAL NUMBER CLASS IN JAVA

AIM:

To develop Rational number class in java. Use JavaDoc comments for documentation.
Your implementation should use efficient representation for a rational number, i.e.
(500/1000) should be represented as (1/2).

PROGRAM:

import java.util.Scanner;
public class Rationala
{
private int num; // the numerator
private int den; // the denominator
/**
* constructor
* @param numerator
* @param denominator
*/
public Rationala(int numerator, int denominator)
{
int g = GCD(numerator, denominator);
num = numerator / g;
den = denominator / g;
if (den < 0) { den = -den; num = -num; }
}

/**
*@return String value of Rational number
*/
public String toString()
{
if (den == 1) return num + "";
else return num + "/" + den;
}
/**
* * @param m - Numerator
* @param n - Denominator
* @return - GCD of two numbers
*/
private static int GCD(int m, int n)
{
if (m < 0) m = -m;
if (n < 0) n = -n;
if (0 == n) return m;
else return GCD(n, m % n);
}
/**
* gets the Numerator and Denominator from the user
* @param args
*/
public static void main(String[] args)
{
Rationala x;
int a = 1, b = 1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Numerator : ");
try
{
a = sc.nextInt();
}
catch(Exception e
{
System.out.println("Numerator should be integer only");
System.exit(0);
}
System.out.println("Enter the Denominator: ");
try
{
b = sc.nextInt();
if(b == 0)
{
System.out.println("denominator should not be zero");
System.exit(0);
}
}
catch(Exception e)
{
System.out.println("denominator should be integer only");
System.exit(0);
}
x = new Rationala(a,b);
System.out.println("The Rational Form of given Fractional Number is :" +x);
}
}

OUTPUT:

C:\Java\jdk1.5.0_06\bin>javac Rationala.java
C:\Java\jdk1.5.0_06\bin>java Rationala
Enter the Numerator :
40
Enter the Denominator:
400
The Rational Form of given Fractional Number is :1/10

C:\Java\jdk1.5.0_06\bin>javadoc Rationala.java
Loading source file Rationala.java...
Constructing Javadoc information...
Standard Doclet version 1.5.0_06
Building tree for all the packages and classes...
Generating Rationala.html...
Generating package-frame.html...
Generating package-summary.html...
Generating package-tree.html...
Generating constant-values.html...
Building index for all the packages and classes...
Generating overview-tree.html...
Generating index-all.html...
Generating deprecated-list.html...
Building index for all classes...
Generating allclasses-frame.html...
Generating allclasses-noframe.html...
Generating index.html...
Generating help-doc.html...
Generating stylesheet.css...

C:\Java\jdk1.5.0_06\bin>
EX 2 : THE JAVA.UTIL PACKAGE-DATE CLASS
AIM:

To develop Date class in java similar to the one available in java.util package. Use
java Doc comments.

PROGRAM:

import java.util.Date;

class MyDate extends Date


{
private static final long serialVersionUID = 1L;
int day = super.getDay();
int date = super.getDate();
int year = super.getYear();
int month = super.getMonth();
int hours = super.getHours();
int minutes = super.getMinutes();
int seconds = super.getSeconds();
long time = super.getTime();
int timezoneOffset = super.getTimezoneOffset();
public int getDay() {return day;}
public int getDate() {return date;}
public int getYear() {return year+1900;}
public int getMonth() {return month+1;}
public int getHours() {return hours;}
public int getMinutes() {return minutes;}
public int getSeconds() {return seconds;}
public int getTimezoneOffset() {return timezoneOffset;}
public long getTime() {return time;}
public void setDay(int day) {this.day = day;}
public void setDate(int date) {this.date = date;}
public void setTime(Long time) {this.time = time;}
public void setYear(int year) {this.year = year;}
public void setHours(int hours) {this.hours = hours;}
public void setMonth(int month) {this.month = month;}
public void setMinutes(int minutes) {this.minutes = minutes;}
public void setSeconds(int seconds) {this.seconds = seconds;}
public void setTimezoneOffset(int timezoneOffset){this.timezoneOffset =
timezoneOffset;}
public MyDate()
{
super();
}
public MyDate(String date)
{
super(date);
}
public MyDate(long date)
{
super(date);
}
public MyDate(int year,int month,int day)
{
super(year,month,day);
Date da = new Date();
}
public MyDate(int year,int month,int day,int hrs,int mins)
{
super(year,month,day,hrs,mins);
Date da = new Date();
}
public MyDate(int year,int month,int day,int hrs,int mins,int secs)
{
super(year,month,day,hrs,mins,secs);
Date da = new Date();
}
public long getMillisOf(DateImpl dat)
{
return getMillisOf(dat);//method of java.util.Date Class
}
public Date getCalenderDate()
{
return getCalenderDate();
}
public String toString()
{
String date = this.getDate()+"/"+this.getMonth()+"/"+this.getYear();
String time = this.getHours()+":"+this.getMinutes()+":"+this.getSeconds();
return date+" "+time;
}
}
public class DateImpl
{
public static void main(String args[])
{
MyDate date1 = new MyDate();
System.out.println("Date : "+date1.getDate());
System.out.println("Month : "+date1.getMonth());
System.out.println("Year : "+date1.getYear());
System.out.println("Hour : "+date1.getHours());
System.out.println("Minutes : "+date1.getMinutes());
System.out.println("Secs : "+date1.getSeconds());
System.out.println(date1);
}
}

OUTPUT:

C:\Java\jdk1.5.0_06\bin>javac DateImpl.java
C:\Java\jdk1.5.0_06\bin>java DateImpl
Date : 17
Month : 6
Year : 2010
Hour : 9
Minutes : 40
Secs : 16
17/6/2010 9:40:16
EX 3 : THE JAVA.UTIL PACKAGE

(i) ARRAYLIST CLASS


AIM:

In this Program an object of ArrayList type is created.Then, a few elements are


added to it. Subsequently, a few existing elements are removed from it.The add() and
remove() methods are used for this purpose.

PROGRAM:

import java.util.*;
class ArrayListExample
{
public static void main(String args[])
{
ArrayList arrList=new ArrayList();
System.out.println("Initial size ArrayList is:"+arrList.size());

arrList.add("A");
arrList.add("C");
arrList.add("E");
arrList.add("G");
arrList.add("I");
System.out.println(" size after additions:"+arrList.size());

System.out.println("Contents of arrayList object:"+arrList);


arrList.add(1, "B");
arrList.add(3, "D");
System.out.println("Contents of arrayList object:"+arrList);
arrList.remove("B");
arrList.remove(3);

System.out.println("Contents of arrayList object:"+arrList);


}
}

OUTPUT:
C:\Java\jdk1.5.0_06\bin>javac ArrayListExample.java
C:\Java\jdk1.5.0_06\bin>java ArrayListExample
Initial size ArrayList is:0
size after additions:5
Contents of arrayList object:[A, C, E, G, I]
Contents of arrayList object:[A, B, C, D, E, G, I]
Contents of arrayList object:[A, C, D, G, I]

(ii) LINKEDLIST CLASS

AIM:

In this Program an object of LinkedList type is created.Then, a few elements are


added to it. Subsequently, a few existing elements are removed from it.The add() and
remove() methods are used for this purpose.

PROGRAM:

import java.util.*;
class LinkedListExample
{
public static void main(String args[])
{
//create a Linked List
LinkedList linkList=new LinkedList();
System.out.println("Initial size LinkedList is:"+linkList);

//add elements to a linked list

linkList.add("c");
linkList.add("E");
linkList.add("G");
linkList.add("I");
linkList.add("A");
linkList.add(1,"B");
System.out.println("Contents of LinkList object:"+linkList);
linkList.remove("E");
linkList.remove(4);
System.out.println("Contents of LinkList object:"+linkList);
linkList.removeFirst();
linkList.removeLast();
System.out.println("Contents of LinkList object:"+linkList);
}
}
OUTPUT:
C:\Java\jdk1.5.0_06\bin>javac LinkedListExample.java
C:\Java\jdk1.5.0_06\bin>java LinkedListExample
Contents of LinkedList object: []
Contents of arrayList object: [A, B, C, E, G, I]
Contents of arrayList object: [A,B, C, G]
Contents of arrayList object: []

(iii) STACK CLASS


AIM:

In this Program an empty stack object is first created. Then, many objects are
pushed into it. Finally, the objects are popped out of stack in the LIFO order.

PROGRAM:

import java.util.Stack;
import java.util.EmptyStacKException;
class StackMethods
{
static void displaypush(Stack stk,int a)
{
stk.push(new Integer(a));
System.out.println("Stack:"+stk);
}
static void displaypop(Stack stk)
{
stk.pop();
System.out.println("Stack:"+stk);
}
public static void main(String[] args)
{
Stack stk=new Stack();
displaypush (stk,38);
displaypush (stk,49);
displaypush (stk,56);
displaypop (stk);
displaypop (stk);
displaypop (stk);
try
{
displaypop(stk);
}
catch(EmptyStacKException e)
{

System.out.println("Stack is Empty");
}
}
}

OUTPUT:
Stack : [38]
Stack : [38,47]
Stack : [38,47,56]
Stack : [38,47]
Stack : [38]
Stack : [] Stack is empty
EX : 4 LISP-LIKE LIST IN JAVA
AIM:
To implement Lisp-like list in java. Write basic operations such as ‘car’, ‘cdr’,
and ‘cons’. If L is a List[3,0,2,5], L.car() returns 3,while L.cdr() returns[0,2,5].

PROGRAM:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class LispImpl
{
Scanner sc = new Scanner(System.in);
List consList = new ArrayList();
public void cons()
{
System.out.println("Enter the Cons Element");
System.out.println("Format --->[addr,value1,value2,...]");
String cons = sc.next().trim();
if(cons.indexOf("[") == 0 && cons.indexOf("]") == cons.length()-1)
{
cons = cons.substring(1,cons.length()-1);
String[] consElements = cons.split(",");
if(consElements.length>2)
{
try
{
Integer.parseInt(consElements[0]);
List list = new LinkedList();
for(int i = 0 ;i < consElements.length;i++)
{
list.add(consElements[i]);
}
consList.add(consList.size(),list);
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Error : Content of Address Part of Register should be Numeric" );
}
}
else
System.out.println("Error : No Contents of Decrement part Register Found");
}
else
{
System.out.println("Conses format is not correct");
}
}
public void car()
{
System.out.println("Enter index of the Conses Element");
try
{
int consIndex = sc.nextInt();
List cons = (List)consList.get(consIndex);
System.out.println("Car of given ConsIndex : "+cons.get(0));

}
catch(IndexOutOfBoundsException e)
{
System.out.println("No Conses found");
}
catch(Exception e)
{
System.out.println("Error : Conses index should be Numeric" );
}
}
public void cdr()
{
System.out.println("Enter index of the Conses Element");
try
{
int consIndex = sc.nextInt();
List cons = (List)consList.get(consIndex);
System.out.print("Cdr of given ConsIndex : [");
String cdr = "";
for(int i = 0;i<cons.size();i++)
cdr = cdr+","+cons.get(i);
System.out.println(cdr.substring(1,cdr.length())+"]");

}
catch(IndexOutOfBoundsException e)
{
System.out.println("No Conses found");
}
catch(Exception e)
{
System.out.println("Error : Conses index should be Numeric" );
}
}
public void defaultMsg()
{
System.out.println("****************************");
System.out.println("Enter 1 to do cons operation");
System.out.println("Enter 2 to do car operation");
System.out.println("Enter 3 to do cdr operation");
System.out.println("Enter 4 to exit");
System.out.println("****************************");
}
public static void main(String args[])
{
LispImpl lisp = new LispImpl();
int i = 0;
lisp.defaultMsg();
while(true)
{
Scanner sc = new Scanner(System.in);
try
{
i = sc.nextInt();
}
catch(Exception e)
{
System.out.println("Numeric values are allowed here");
}
switch(i)
{
case 1:
lisp.cons();
lisp.defaultMsg();
break;
case 2:
lisp.car();
lisp.defaultMsg();
break;
case 3:
lisp.cdr();
lisp.defaultMsg();
break;
case 4:
System.exit(0);
break;
default:
System.out.println("Enter numbers between 0 and 4");
}
}
}
}

OUTPUT:

C:\Java\jdk1.5.0_06\bin>javac LispImpl.java
C:\Java\jdk1.5.0_06\bin>java LispImpl
****************************
Enter 1 to do cons operation
Enter 2 to do car operation
Enter 3 to do cdr operation
Enter 4 to exit

EX 5 : IMPLEMENTATION OF INTERFACE
AIM:

To develop the program by using multiple use of an interface

PROGRAM:

import java.io.*;
interface Shape2d
{
double getArea();
}
class shape
{
void display(String s)
{
System.out.println("Name of the shape is"+s);
}
}
class Circle extends shape implements Shape2d
{
int radius;
Circle(int radius)
{
this.radius=radius;
}
public double getArea()
{
return Math.PI*radius*radius;
}
}
class Square extends shape implements Shape2d
{
int side;
Square(int side)
{
this.side=side;
}
public double getArea()
{
return side*side;
}
}
class CircleSquareDemo
{
public static void main(String[] args) throws IOException
{
Circle c=new Circle(10);
c.display("Circle");
System.out.println("Area of the Circle is:"+c.getArea());
Square s=new Square(10);
s.display("Square");
System.out.println("Area of the Square is:"+c.getArea());
}
}

OUTPUT:

Name of the Shape is : Circle


Area of the Circle is : 314.1592653
Name of the Shape is : Square
Area of the Square is : 100

(ii) INTERFACE INHERITANCE

AIM:
Program to illustrate interface inheritance concept
PROGRAM:
import java.io.*;
interface IntFace1
{
int j=20;
int j1();
}
interface IntFace2
{
double k1();
}
interface IntFace3 extends IntFace1,IntFace2
{
boolean l1();
}
class Sample implements IntFace3
{
public int j1()
{
return 100;
}
public double k1()
{
return 20.9;
}
public boolean l1()
{
return true;
}
}
public class IntfaceDemo2
{
public static void main(String[] args)
{
Sample s=new Sample();
System.out.println(s.j);
System.out.println(s.j1());
System.out.println(s.k1());
System.out.println(s.l1());
}
}
OUTPUT:

20
100
20.9 true
EX : 7 POLYMORPHISM

AIM:

To develop a class hierarchy in java. Write a test program to demonstrate polymorphism

PROGRAM:

interface Vehicle
{
int numberOfWheels();
String vehicleType();

}
class Car implements Vehicle
{
public int numberOfWheels()
{
return 4;
}
public String vehicleType()
{
return "Car";
}
}
class AutoRicksaw implements Vehicle
{
public int numberOfWheels()
{
return 3;
}
public String vehicleType()
{
return "Auto Ricksaw";
}
}
public class PolyVehicle
{
public static void main(String[] args)
{
Vehicle ve;
ve = new Car();//Now vehicle is Car
System.out.println("Vehicle Type : "+ve.vehicleType());
System.out.println("Number of wheels : "+ve.numberOfWheels());
ve = new AutoRicksaw();//Now vehicle is Auto
System.out.println("Vehicle Type : "+ve.vehicleType());
System.out.println("Number of wheels : "+ve.numberOfWheels());
}
}

OUTPUT:
C:\Java\jdk1.5.0_06\bin>javac PolyVehicle.java
C:\Java\jdk1.5.0_06\bin>java PolyVehicle
Vehicle Type : Car
Number of wheels : 4
Vehicle Type : Auto Ricksaw
Number of wheels : 3
Ex : 8 EVENT-DRIVEN PROGRAMMING
(i) COLOR PALETTE
AIM:

To develop a color palette program using java events

PROGRAM:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=cp.class width=1000 height=1000></applet>*/
public class cp extends Applet implements ActionListener
{
Button bt[]=new Button[256];
int r[]=new int[256];
int g[]=new int[256];
int b[]=new int[256];
CheckboxGroup cg;
Checkbox c1,c2;
TextArea t;
Panel p,p1,p2;
public void init()
{
int c=0;
setLayout(new BorderLayout());
p1=new Panel();
cg=new CheckboxGroup();
c1=new Checkbox("Background",cg,false);
p1.add(c1,BorderLayout.NORTH);
c2=new Checkbox("Foreground",cg,false);
p1.add(c2,BorderLayout.SOUTH);
t=new TextArea();
p1.add(t,BorderLayout.CENTER);
p=new Panel();
p.setLayout(new GridLayout(16,16));

for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
for(int k=0;k<4;k++)
{
r[c]=(i*32);
g[c]=(j*32);
b[c]=(k*64);
bt[c]=new Button("C"+String.valueOf(c));
bt[c].setBackground(new Color(r[c],g[c],b[c]));
bt[c].addActionListener(this);
p.add(bt[c]);
c++;
}
}
}
p1.add(p,BorderLayout.CENTER);
add(p1);
}
public void actionPerformed(ActionEvent ae)
{
String s=new String(ae.getActionCommand());
int x=Integer.parseInt(s.substring(1,s.length()));

if(c1.getState()==true)
t.setBackground(new Color(r[x],g[x],b[x]));
else if(c2.getState()==true)
t.setForeground(new Color(r[x],g[x],b[x]));
}
}

OUTPUT

C:\Java\jdk1.5.0_06\bin>javac cp.java
C:\Java\jdk1.5.0_06\bin>appletviewer cp.html

C:\Java\jdk1.5.0_06\bin>
(ii) SCIENTIFIC CALCULACTOR

AIM:

To develop a scientific calculactor using event handling function

PROGRAM:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Math.*;

/*<applet code="Calc.class" width=500 height=500>


</applet>*/

public class Calc extends Applet implements ActionListener


{
int flag=0;
Button add,sub,mul,div,sin,cos,tan,eq,bname,clear,log,mod;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,bdot;
TextField tEdit;
double x1,x2,res;
String s="";
Panel p1,p2;

public void init()


{
tEdit=new TextField(15);
this.add(tEdit);
b1=new Button("1");
this.add(b1);
b1.addActionListener(this);

b2=new Button("2");
this.add(b2);
b2.addActionListener(this);

b2=new Button("3");
this.add(b3);
b3.addActionListener(this);

b4=new Button("4");
this.add(b4);
b4.addActionListener(this);
b5=new Button("5");
this.add(b5);
b5.addActionListener(this);

b6=new Button("6");
this.add(b6);
b6.addActionListener(this);

b7=new Button("7");
this.add(b7);
b7.addActionListener(this);

b8=new Button("8");
this.add(b8);
b8.addActionListener(this);

b9=new Button("9");
this.add(b9);
b9.addActionListener(this);

b0=new Button("0");
this.add(b0);
b0.addActionListener(this);

bdot=new Button(".");
this.add(bdot);
bdot.addActionListener(this);

add=new Button("+");
this.add(add);
add.addActionListener(this);

sub=new Button("-");
this.add(sub);
sub.addActionListener(this);

mul=new Button("*");
this.add(mul);
mul.addActionListener(this);

div=new Button("/");
this.add(div);
div.addActionListener(this);

eq=new Button("=");
this.add(eq);
eq.addActionListener(this);

mod=new Button("mod");
this.add(mod);
mod.addActionListener(this);

log=new Button("log");
this.add(log);
log.addActionListener(this);

sin=new Button("sin");
this.add(sin);
sin.addActionListener(this);

cos=new Button("cos");
this.add(cos);
cos.addActionListener(this);

tan=new Button("tan");
this.add(tan);
tan.addActionListener(this);

clear=new Button("clear");
this.add(clear);
clear.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
s=s+"1";
tEdit.setText(s);
}
else if(ae.getSource()==b2)
{
s=s+"2";
tEdit.setText(s);
}
else if(ae.getSource()==b3)
{
s=s+"3";
tEdit.setText(s);
}
else if(ae.getSource()==b4)
{
s=s+"4";
tEdit.setText(s);
}
else if(ae.getSource()==b5)
{
s=s+"5";
tEdit.setText(s);
}

else if(ae.getSource()==b6)
{
s=s+"6";
tEdit.setText(s);
}
else if(ae.getSource()==b7)
{
s=s+"7";
tEdit.setText(s);
}

else if(ae.getSource()==b8)
{
s=s+"8";
tEdit.setText(s);
}
else if(ae.getSource()==b9)
{
s=s+"9";
tEdit.setText(s);
}

else if(ae.getSource()==b0)
{
if(s=="")
s="0";
else
s=s+"0";
tEdit.setText(s);
}

else if(ae.getSource()==bdot)
{
int fg=0;
for(int k=0;k<s.length();k++)
{
if(s.charAt(k)=='.')
{
fg=1;
break;
}
}
if(fg==0)
s=s+".";
tEdit.setText(s);
}
else if(ae.getSource()==add)
{
if(flag!=1)
x1=Integer.parseInt(tEdit.getText());
s="";
bname=add;
tEdit.setText("");
}
else if(ae.getSource()==sub)
{
if(flag!=1)
x1=Integer.parseInt(tEdit.getText());
s="";
bname=sub;
tEdit.setText("");
}
else if(ae.getSource()==mul)
{
if(flag!=1)
x1=Integer.parseInt(tEdit.getText());
s="";
bname=mul;
tEdit.setText("");
}
else if(ae.getSource()==div)
{
if(flag!=1)
x1=Integer.parseInt(tEdit.getText());
s="";
bname=div;
tEdit.setText("");
}
else if(ae.getSource()==mod)
{
if(flag!=1)
x1=Integer.parseInt(tEdit.getText());
s="";
bname=mod;
tEdit.setText("");
}
else if(ae.getSource()==sin)
{
if(flag!=1)
x1=Integer.parseInt(tEdit.getText());
res=Math.sin(x1);
s=""+res;
tEdit.setText(s);
x1=res;
flag=1;
}

else if(ae.getSource()==cos)
{
if(flag!=1)
x1=Integer.parseInt(tEdit.getText());
res=Math.cos(x1);
s=""+res;
tEdit.setText(s);
x1=res;
flag=1;
}
else if(ae.getSource()==tan)
{
if(flag!=1)
x1=Integer.parseInt(tEdit.getText());
res=Math.tan(x1);
s=""+res;
tEdit.setText(s);
x1=res;
flag=1;
}
else if(ae.getSource()==eq)
{
flag=2;
s="";
x2=Integer.parseInt(tEdit.getText());
if(bname==add)
res=x1+x2;
if(bname==sub)
res=x1-x2;
if(bname==mul)
res=x1*x2;
if(bname==div)
{
if(x2==0)
System.out.println("Divide by zero Error");
else
res=x1/x2;
}
if(bname==mod)
{
if(x2==0)
System.out.println("Divide by zero Error");
else
res=x1 % x2;
}
s=""+res;
tEdit.setText(s);
x1=res;
flag=1;
}
else if(ae.getSource()==clear)
{
s="";
tEdit.setText("");
}
}

EX : 9 JCHECKBOXCONTROL-SWING

AIM:

Program to illustrate Checkbox control by using swing

PROGRAM:

//SWING
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CheckboxDemo extends JApplet implements ItemListener
{
JTextField jtf;
ImageIcon normalIcon,rolloverIcon,selectedIcon;
JCheckBox cb1,cb2;
Container c;
public void init()
{
c=getContentPane();
c.setLayout(new FlowLayout());
normalIcon =new ImageIcon("web.gif");
rolloverIcon =new ImageIcon("mmc.gif");
selectedIcon =new ImageIcon("help.gif");
cb1=new JCheckBox("java",normalIcon);
cb1.setRolloverIcon(rolloverIcon);
cb1.setSelectedIcon(selectedIcon);
cb1.addItemListener(this);
c.add(cb1);

cb2=new JCheckBox("swing",normalIcon);
cb2.setRolloverIcon(rolloverIcon);
cb2.setSelectedIcon(selectedIcon);
cb2.addItemListener(this);
c.add(cb2);
jtf=new JTextField(15);
c.add(jtf);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb=(JCheckBox)ie.getItem();
String message=cb.getText();
jtf.setText(message);
}
}

OUTPUT

C:\Java\jdk1.5.0_06\bin>javac CheckboxDemo.java

C:\Java\jdk1.5.0_06\bin>appletviewer CheckboxDemo.html

C:\Java\jdk1.5.0_06\bin>
C:\Java\jdk1.5.0_06\bin>
SQL TABLE:

SQL>desc student1;

NAME NULL? TYPE

SNAME
VARCHAR(10)
RANK NUMBER(10)

SQL>insert into student values(‘&sname’,&rank);


Enter the value for sname : sherin
Enter value for rank : 1

1 row created.

SQL> select* from student;

SNAME RANK
SHERIN 1
BEEVI 3
SOWMIA 5

OUTPUT:
SHERIN 1
BEEVI 3
SOWMIA 5

MULTI-THREADED ECHO SERVER

AIM:

To develop multi-threaded echo server and a corresponding GUI client in java

PROGRAM:

ECHO CLIENT

import java.io.*;
import java.net.*;
public class echoclient
{
Public static void main(String args[])throws IOException
{
InetAddress obj=InetAddress.getLocalHost();
Socket s=new Socket(obj,500);
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());
System.out.println(“Type your message to server and type quit to
execute”);

While(true)
{
String t=new DataInputStream(Syatem.in).readLine();
If(t.equals(“Quit”))
{
p.close();
System.exit(0);
}
else
{
p.println(t);
t=dis.readLine();
System.out.println(t);
}
}
}
}

ECHO SERVER

import java.io.*;
import java.net.*;
public class echoserver
{
Public static void main(String args[])throws IOException
{
ServerSocket ss=new ServerSocket(500);
Socket s=ss.accept();
System.out.println(“Server is ready”);
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());

While(true)
{
String t=dis.readLine();
If(t==null)
{
Break;
}
System.out.println(t);
p.println(t);
}
}
}
OUTPUT:

ECHOSERVER

Server is ready
Hello
Hai

ECHOCLIENT

Hello
Hello
hai
hai
VEHICLE INTERFACE

interface Vehicle
{
int numberOfWheels();
String vehicleType();
}
class Car implements Vehicle
{
public int numberOfWheels()
{
return 4;
}
public String vehicleType()
{
return "Car";
}
}
class AutoRicksaw implements Vehicle
{
public int numberOfWheels()
{
return 3;
}
public String vehicleType()
{
return "Auto Ricksaw";
}
}
public class Poly
{
public static void main(String[] args)
{
Vehicle ve;
ve=new Car();
System.out.println("Vehicle Type:"+ve.vehicleType());
System.out.println("Number of Wheels:"+ve.numberOfWheels());
ve=new AutoRicksaw();
System.out.println("Vehicle Type:"+ve.vehicleType());
System.out.println("Number of Wheels:"+ve.numberOfWheels());
}
}
OUTPUT:

C:\PROGRA~1\Java\JDK15~1.0\bin>javac Poly.java
C:\PROGRA~1\Java\JDK15~1.0\bin>java Poly
Vehicle Type:Car
Number of Wheels:4
Vehicle Type:Auto Ricksaw
Number of Wheels:3

COLOR PALETTE

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class cp extends Applet implements ActionListener
{
Button bt[]=new Button[256];
int r[]=new int[256];
int g[]=new int[256];
int b[]=new int[256];
CheckboxGroup cg;
Checkbox c1,c2;
TextArea t;
Panel p,p1,p2;
public void init()
{
int c=0;
setLayout(new BorderLayout());
p1=new Panel();
cg=new CheckboxGroup();
c1=new Checkbox("Background",cg,false);
p1.add(c1,BorderLayout.NORTH);
c1=new Checkbox("Foreground",cg,false);
p1.add(c1,BorderLayout.SOUTH);
t=new TextArea();
p1.add(t,BorderLayout.CENTER);

p=new Panel();
p.setLayout(new GridLayout(16,16));

for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
for(int k=0;k<4;k++)
{
r[c]=(i*32);
g[c]=(j*32);
b[c]=(k*64);
bt[c]=new Button("C"+String.valueOf(c));
bt[c].setBackground(new Color(r[c],g[c],b[c]));
bt[c].addActionListener(this);
p.add(bt[c]);
c++;
}
}
}
p1.add(p,BorderLayout.CENTER);
add(p1);
}
public void actionPerformed(ActionEvent ae)
{
String s=new String(ae.getActionCommand());
int x=Integer.parseInt(s.substring(1,s.length()));

if(c1.getState()==true)
t.setBackground(new Color(r[x],g[x],b[x]));
else if(c2.getState()==true)
t.setForeground(new Color(r[x],g[x],b[x]));

}
}

import java.util.*;
import java.io.*;
// To implement LISP-like List in Java to perform functions like car, cdr, cons.
class Lisp
{
Vector v = new Vector(4,1);
int i;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader inData = new BufferedReader(isr);
String str;
//Create a LISP-Like List using VECTOR
public void create()
{
int n;
System.out.print("\n Enter the Size of the list:");
//Get Input from the user...Use I/p stream reader for it...
try
{
str = inData.readLine();
n = Integer.parseInt(str);
for(i=0;i<N;I++)
{
int temp;
System.out.print("\n Enter the element " + (i+1) + " of the list:");
str = inData.readLine();
temp=Integer.parseInt(str);
v.addElement(new Integer(temp));
}
}
catch (IOException e)
{
System.out.println("Error!");
System.exit(1);
}
}
//Display the content of LISP-List
public void display()
{
int n=v.size();
System.out.print("[ ");
for(i=0;i<N;I++)
{
System.out.print(v.elementAt(i) + " ");
}
System.out.println("]");
}
/*
The car of a list is, quite simply, the first item in the list.
For Ex: car of L.car() of a list [3 0 2 5] returns 3.
Gives the CAR of LISP-List
*/
public void car()
{
System.out.println("\n CAR of the List: " + v.elementAt(0));
}
/*
The cdr of a list is the rest of the list, that is, the cdr function returns the part of the list
that follows the first item.
For ex: cdr of a list [3 0 2 5] returns [0 2 5]
*/
public void cdr()
{
int n=v.size();
System.out.print("\n The CDR of the List is:");
System.out.print("[ ");
for(i=1;i<N;I++)
{
System.out.print(v.elementAt(i) + " ");
}
System.out.println("]");
}
/*
The cons function constructs lists. It is useful to add element to the front of the list; it is
the inverse of car and cdr. For example, cons can be used to make a five element list from
the four element list.
For ex: adding 7 to [3 0 2 5], cons(7) gives [7 3 0 2 5]
*/
public void cons(int x)
{
v.insertElementAt(x,0);
System.out.print("\n The List after using CONS and adding an element:");
display();
}
// Returns the length of the LISP-List
public int length()
{
return v.size();
}
}
class Lisp_List
{
public static void main(String[] args)
{
Lisp a = new Lisp();
a.create();
System.out.print("\n The contents of the List are:");
a.display();
a.car();
a.cdr();
a.cons(5);
System.out.println("\n\n The length of the list is " + a.length());
}
}
output

Enter the Size of the list:4


Enter the element 1 of the list:3
Enter the element 2 of the list:0
Enter the element 3 of the list:2
Enter the element 4 of the list:5
The contents of the List are:[ 3 0 2 5 ]
CAR of the List: 3
The CDR of the List is:[ 0 2 5 ]
The List after using CONS and adding an element:[ 5 3 0 2 5 ]
The length of the list is 5

MULTITHREAD PROGRAM FOR FIBONACCI


import java.util.*;
import java.io.*;

class Fibonacci extends Thread


{
private PipedWriter out = new PipedWriter();
public PipedWriter getPipedWriter()
{
return out;
}
public void run()
{
Thread t = Thread.currentThread();
t.setName("Fibonacci");
System.out.println(t.getName() + " thread started");
int fibo1=0,fibo2=1,fibo=0;
while(true)
{
try
{
fibo = fibo1 + fibo2;
if(fibo>100000)
{
out.close();
break;
}
out.write(fibo);
sleep(1000);
}
catch(Exception e)
{
System.out.println("Fibonacci:"+e);
}
fibo1=fibo2;
fibo2=fibo;
}
System.out.println(t.getName() + " thread exiting");

}
}
class Prime extends Thread
{
private PipedWriter out1 = new PipedWriter();
public PipedWriter getPipedWriter()
{
return out1;
}
public void run()
{
Thread t= Thread.currentThread();
t.setName("Prime");
System.out.println(t.getName() + " thread Started...");
int prime=1;
while(true)
{
try
{
if(prime>100000)
{
out1.close();
break;
}
if(isPrime(prime))
out1.write(prime);
prime++;
sleep(0);
}
catch(Exception e)
{
System.out.println(t.getName() + " thread exiting.");
System.exit(0);
}
}
}
public boolean isPrime(int n)
{
int m=(int)Math.round(Math.sqrt(n));
if(n==1 || n==2)
return true;
for(int i=2;i<=m;i++)
if(n%i==0)
return false;
return true;
}
}
public class PipedIo
{
public static void main(String[] args) throws Exception
{
Thread t=Thread.currentThread();
t.setName("Main");
System.out.println(t.getName() + " thread Started...");
Fibonacci fibonacci = new Fibonacci();
Prime prime = new Prime();
PipedReader fpr = new PipedReader(fibonacci.getPipedWriter());
PipedReader ppr = new PipedReader(prime.getPipedWriter());
fibonacci.start();
prime.start();
int fib=fpr.read(), prm=ppr.read();
System.out.println("The numbers common to PRIME and FIBONACCI:");
while((fib!=-1) && (prm!=-1))
{
while(prm<=fib)
{
if(fib==prm)
System.out.println(prm);
prm=ppr.read();
}
fib=fpr.read();
}
System.out.println(t.getName() + " thread exiting");
}
}
// Five programs and one database, main program is Library.java

FIRST PROGRAM

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JPanel.*;
import javax.swing.event.*;
import java.util.*;
import java.sql.*;

public class Library extends JFrame implements


ActionListener {

JTextField bId, bName, bAuth, bpub;


JTextField Isbn, qt;
JList blst;

JButton Member;
JButton NewMem;
JButton Books;
JButton NewBook;
JButton Exit;

JMenu fMenu;
JMenu hMenu;
JMenuItem hMen, abt;
JMenuItem eMen;
JMenuBar menuBar;
JButton BooksEntry;
String memName, Address, Desig;
int memId;
String bookName, Author, publisher;
int ISBN, qty;
Container cont;
JPanel memp, butmainp, bookp, butbookp;

Library() {

cont = getContentPane();
menuBar = new JMenuBar();

fMenu = new JMenu("File");


hMen = new JMenuItem("Help", KeyEvent.VK_F1);
hMen.addActionListener(this);
fMenu.add(hMen);

hMenu = new JMenu("Library");


abt = new JMenuItem("About");
eMen = new JMenuItem("Exit", KeyEvent.VK_E);
abt.addActionListener(this);
eMen.addActionListener(this);
hMenu.add(abt);
hMenu.addSeparator();
hMenu.add(eMen);
menuBar.add(fMenu);
menuBar.add(hMenu);
setJMenuBar(menuBar);
butmainp = new JPanel();
butmainp.setLayout(new GridLayout(4, 4, 30, 30));

NewMem = new JButton("New Member");


NewMem.addActionListener(this);
butmainp.add(NewMem);

NewBook = new JButton("New Book Entry");


NewBook.addActionListener(this);
butmainp.add(NewBook);

Member = new JButton("Member Details");


Member.addActionListener(this);
butmainp.add(Member);

Books = new JButton("Book Details");


Books.addActionListener(this);
butmainp.add(Books);

cont.add("Center", butmainp);

}
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if (s.equals("Exit")) {
System.exit(0);
} else if (s.equalsIgnoreCase("Help")) {
JOptionPane.showMessageDialog(null, "This is a
application for OPAC.\nFor more
information:\n\tContact cse Innovators", "Help...!",
JOptionPane.PLAIN_MESSAGE);
} else if (s.equalsIgnoreCase("About")) {
JOptionPane.showMessageDialog(null, "By
Whitman Kumaresh - NPSB CSE Innovators.\nUnder
the guidence of BHUVANESHWARI Mam.",
"About", JOptionPane.PLAIN_MESSAGE);
}
if (s.equals("New Member")) {
NewMem nm1 = new NewMem();
nm1.setTitle("New Member");
nm1.setSize(370, 240);
nm1.setVisible(true);
}
if (s.equals("Member Details")) {
Member m1 = new Member();
m1.setTitle("Member Details");
m1.setSize(330, 280);
m1.setVisible(true);
}
if (s.equals("New Book Entry")) {
NewBook nb1 = new NewBook();
nb1.setTitle("New Book Entry");
nb1.setSize(370, 240);
nb1.setVisible(true);
}
if (s.equals("Book Details")) {
Book b1 = new Book();
b1.setTitle("Book Details");
b1.setSize(800, 420);
b1.setVisible(true);
}
}

public static void main(String args[]) {


Library main = new Library();
main.setTitle("Library");
main.setSize(640, 480);
main.setResizable(false);
main.setVisible(true);
main.setDefaultCloseOperation(JFrame.EXIT_ON_C
LOSE);
}
}
OPAC PROGRAM

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JPanel.*;
import javax.swing.event.*;
import java.util.*;
import java.sql.*;

class Book extends JFrame {

JButton clos;
JList mem;
JLabel desp;
JPanel membp;
Container cont;
Connection con;
ResultSet rs;
String n1, n2, n3, n4, n5, n6, n7;
Book() {
cont = getContentPane();
membp = new JPanel();
membp.setLayout(new
FlowLayout(FlowLayout.LEFT));
this.setDefaultCloseOperation(DISPOSE_ON_C
LOSE);
desp.setToolTipText("Books available in
library.\nShort description on every book.");
disp();
cont.add(membp);
}

public void disp() {


try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"
);
con =
DriverManager.getConnection("jdbc:odbc:Lib",
"", "");
String table = "Book";
Statement st = con.createStatement();
rs = st.executeQuery("SELECT * FROM " +
table);
while (rs.next()) {
n1 = rs.getString("bName");
n2 = rs.getString("bNo");
n3 = rs.getString("bAuthor");
n4 = rs.getString("bPub");
n5 = rs.getString("bYear");
desp = new JLabel("Name: " + n1 + " Book No:
" + n2 + " Author: " + n3 + " Publisher: " + n4 +
" Year: " + n5);
membp.add(desp);
}
} catch (Exception q) {
JOptionPane.showMessageDialog(null, "
Error..", "Member Notification",
JOptionPane.PLAIN_MESSAGE);
}
}
}
OPAC PROGRAM

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JPanel.*;
import javax.swing.event.*;
import java.util.*;
import java.sql.*;

class Member extends JFrame implements


ActionListener {

JButton b1, b2;


JList mem;
JLabel desp, l1, l2;
JLabel mb1, mb2, mb3, mb4, mb5, mb6, mb7;
JPanel membp;
Container cont;
Connection con;
ResultSet rs;
JTextField t1, m1, m2, m3, m4, m5, m6, m7;
String n1, n2, n3, n4, n5, n6, n7, m;

Member() {
cont = getContentPane();
membp = new JPanel();
membp.setLayout(new
FlowLayout(FlowLayout.LEFT));
this.setDefaultCloseOperation(DISPOSE_ON_C
LOSE);

l1 = new JLabel("Enter Member ID:");


t1 = new JTextField(10);

b1 = new JButton("View");
b1.addActionListener(this);
b2 = new JButton("Save");
b2.addActionListener(this);

m1 = new JTextField(20);
m2 = new JTextField(20);
m3 = new JTextField(20);
m4 = new JTextField(20);
m5 = new JTextField(20);
m6 = new JTextField(20);
m7 = new JTextField(20);

mb1 = new JLabel("Name: ");


mb2 = new JLabel("Address: ");
mb3 = new JLabel("Designation: ");
mb4 = new JLabel("Member ID: ");
mb5 = new JLabel("Book 1: ");
mb6 = new JLabel("Book 2: ");
mb7 = new JLabel("Book 3: ");
membp.add(l1);
membp.add(t1);
membp.add(b1);

membp.add(mb1);
membp.add(m1);
membp.add(mb2);
membp.add(m2);
membp.add(mb3);
membp.add(m3);
membp.add(mb4);
membp.add(m4);
membp.add(mb5);
membp.add(m5);
membp.add(mb6);
membp.add(m6);
membp.add(mb7);
membp.add(m7);

membp.add(b2);
cont.add(membp);
}

public void disp() {


try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"
);
con =
DriverManager.getConnection("jdbc:odbc:Lib",
"", "");
String table = "Member";
PreparedStatement st =
con.prepareStatement("SELECT i.* FROM
Member i WHERE i.mId=?");
m = t1.getText().toString();
st.setString(1, m);
rs = st.executeQuery();
while (rs.next()) {
m1.setText(rs.getString("mName"));
m2.setText(rs.getString("mAdd"));
m3.setText(rs.getString("mDesig"));
m4.setText(rs.getString("mId"));
m5.setText(rs.getString("bBord1"));
m6.setText(rs.getString("bBord2"));
m7.setText(rs.getString("bBord3"));
}
} catch (Exception q) {
JOptionPane.showMessageDialog(null, "Server
busy.\nTry after some time. ", "Member
Notification",
JOptionPane.PLAIN_MESSAGE);
}
}

public void update() {


try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"
);
con =
DriverManager.getConnection("jdbc:odbc:Lib");
String table = "Member";
PreparedStatement ps =
con.prepareStatement("UPDATE " + table + "
SET bBord1=?,bBord2=?,bBord3=? WHERE
mId=?");
ps.setString(1, m5.getText());
ps.setString(2, m6.getText());
ps.setString(3, m7.getText());
m = t1.getText().toString();
ps.setString(4, m);
ps.executeUpdate();
ps.close();
JOptionPane.showMessageDialog(null,
m1.getText() + " details has been updated.",
"Member Notification",
JOptionPane.PLAIN_MESSAGE);
} catch (Exception q) {
JOptionPane.showMessageDialog(null,
m1.getText() + ", sorry for
inconvenience.\nServer busy.\nTry after some
time. ", "Member Notification",
JOptionPane.PLAIN_MESSAGE);
}
}

public void actionPerformed(ActionEvent e) {


String a = e.getActionCommand();
if (a.equals("View")) {
disp();
}
if (a.equals("Save")) {
update();
}
}
}

OPAC PROGRAM

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JPanel.*;
import javax.swing.event.*;
import java.util.*;
import java.sql.*;

class NewBook extends JFrame implements


ActionListener {

JTextField bName, bNo, bAuth, bPub, bYr;


JButton addBook;
JPanel memp;
Container cont;
Connection con;
ResultSet rs;
Statement st;

NewBook() {
cont = getContentPane();
memp = new JPanel();
this.setDefaultCloseOperation(DISPOSE_ON_C
LOSE);
memp.setLayout(new
FlowLayout(FlowLayout.RIGHT));
JLabel nm1 = new JLabel("Name:",
JLabel.RIGHT);
bName = new JTextField(25);
JLabel nm2 = new JLabel("Book No:",
JLabel.RIGHT);
bNo = new JTextField(25);
JLabel nm3 = new JLabel("Author:",
JLabel.RIGHT);
bAuth = new JTextField(25);
JLabel nm4 = new JLabel("Publisher:",
JLabel.RIGHT);
bPub = new JTextField(10);
JLabel nm5 = new JLabel("Year:",
JLabel.RIGHT);
bYr = new JTextField(10);

bName.setToolTipText("Enter book name");


bNo.setToolTipText("Enter book no");
bAuth.setToolTipText("Enter author name");
bPub.setToolTipText("Enter publisher name");
bYr.setToolTipText("Enter year of the book
being published");

addBook = new JButton("Add Book");


addBook.addActionListener(this);
memp.add(nm1);
memp.add(bName);
memp.add(nm2);
memp.add(bNo);
memp.add(nm3);
memp.add(bAuth);
memp.add(nm4);
memp.add(bPub);
memp.add(nm5);
memp.add(bYr);
memp.add(addBook);
cont.add(memp);
}

public void actionPerformed(ActionEvent e) {


String a = e.getActionCommand();
if (a.equals("Add Book")) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"
);
con =
DriverManager.getConnection("jdbc:odbc:Lib");
String table = "Book";
PreparedStatement ps =
con.prepareStatement("insert into " + table + "
values(?,?,?,?,?)");
ps.setString(1, bName.getText());
ps.setString(2, bNo.getText());
ps.setString(3, bAuth.getText());
ps.setString(4, bPub.getText());
ps.setString(5, bYr.getText());
ps.executeUpdate();
ps.close();
JOptionPane.showMessageDialog(null,
bName.getText() + " has been added to Book
list", "Member Notification",
JOptionPane.PLAIN_MESSAGE);
} catch (Exception q) {
}

} else {
JOptionPane.showMessageDialog(null,
bName.getText() + "is not added to book list,
sorry for inconvenience.\nServer busy.\nTry
after some time. ", "Member Notification",
JOptionPane.PLAIN_MESSAGE);
}
}
}

OPAC PROGRAM

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JPanel.*;
import javax.swing.event.*;
import java.util.*;
import java.sql.*;

class NewMem extends JFrame implements


ActionListener {

JTextField mName, mAdd, mDesig, mId;


JButton addMem;
JPanel memp;
Container cont;
Connection con;
ResultSet rs;
Statement st;

NewMem() {
cont = getContentPane();
memp = new JPanel();
this.setDefaultCloseOperation(DISPOSE_ON_C
LOSE);
memp.setLayout(new
FlowLayout(FlowLayout.RIGHT));
JLabel nm1 = new JLabel("Name:",
JLabel.RIGHT);
mName = new JTextField(25);
JLabel nm2 = new JLabel("Address:",
JLabel.RIGHT);
mAdd = new JTextField(25);
JLabel nm3 = new JLabel("Designation:",
JLabel.RIGHT);
mDesig = new JTextField(20);
JLabel nm4 = new JLabel("Member ID:",
JLabel.RIGHT);
mId = new JTextField(10);

mName.setToolTipText("Enter your name. ");


mAdd.setToolTipText("Enter your address.");
mDesig.setToolTipText("Enter your
Designation.");
mId.setToolTipText("Enter your Mem ID.\nTo
be provided while borrowing books.");

addMem = new JButton("Add Member");


addMem.addActionListener(this);
memp.add(nm1);
memp.add(mName);
memp.add(nm2);
memp.add(mAdd);
memp.add(nm3);
memp.add(mDesig);
memp.add(nm4);
memp.add(mId);
memp.add(addMem);
cont.add(memp);
}

public void actionPerformed(ActionEvent e) {


String a = e.getActionCommand();
if (a.equals("Add Member")) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"
);
con =
DriverManager.getConnection("jdbc:odbc:Lib");
String table = "Member";
PreparedStatement ps =
con.prepareStatement("insert into " + table + "
values(?,?,?,?,?,?,?)");
ps.setString(1, mName.getText());
ps.setString(2, mAdd.getText());
ps.setString(3, mDesig.getText());
ps.setString(4, mId.getText());
ps.setString(5, "-");
ps.setString(6, "-");
ps.setString(7, "-");
ps.executeUpdate();
ps.close();
JOptionPane.showMessageDialog(null,
mName.getText() + " has been added as a
member", "Member Notification",
JOptionPane.PLAIN_MESSAGE);

} catch (Exception q) {
JOptionPane.showMessageDialog(null,
mName.getText() + ", sorry for
inconvenience.\nServer busy.\nTry after some
time. ", "Member Notification",
JOptionPane.PLAIN_MESSAGE);
}

} else {
JOptionPane.showMessageDialog(null,
mName.getText() + ", sorry for
inconvenience.\nServer busy.\nTry after some
time. ", "Member Notification",
JOptionPane.PLAIN_MESSAGE);
}
}
}
// SimpleEditor.java

//An example showing several DefaultEditorKit features. This class is designed


//to be easily extended for additional functionality.
//

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Hashtable;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.JTextComponent;

public class SimpleEditor extends JFrame {

private Action openAction = new OpenAction();

private Action saveAction = new SaveAction();

private JTextComponent textComp;

private Hashtable actionHash = new Hashtable();


public static void main(String[] args) {
SimpleEditor editor = new SimpleEditor();
editor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editor.setVisible(true);
}

// Create an editor.
public SimpleEditor() {
super("Swing Editor");
textComp = createTextComponent();
makeActionsPretty();

Container content = getContentPane();


content.add(textComp, BorderLayout.CENTER);
content.add(createToolBar(), BorderLayout.NORTH);
setJMenuBar(createMenuBar());
setSize(320, 240);
}

// Create the JTextComponent subclass.


protected JTextComponent createTextComponent() {
JTextArea ta = new JTextArea();
ta.setLineWrap(true);
return ta;
}

// Add icons and friendly names to actions we care about.


protected void makeActionsPretty() {
Action a;
a = textComp.getActionMap().get(DefaultEditorKit.cutAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
a.putValue(Action.NAME, "Cut");

a = textComp.getActionMap().get(DefaultEditorKit.copyAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif"));
a.putValue(Action.NAME, "Copy");

a = textComp.getActionMap().get(DefaultEditorKit.pasteAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif"));
a.putValue(Action.NAME, "Paste");

a = textComp.getActionMap().get(DefaultEditorKit.selectAllAction);
a.putValue(Action.NAME, "Select All");
}
// Create a simple JToolBar with some buttons.
protected JToolBar createToolBar() {
JToolBar bar = new JToolBar();

// Add simple actions for opening & saving.


bar.add(getOpenAction()).setText("");
bar.add(getSaveAction()).setText("");
bar.addSeparator();

// Add cut/copy/paste buttons.


bar.add(textComp.getActionMap().get(DefaultEditorKit.cutAction))
.setText("");
bar.add(textComp.getActionMap().get(DefaultEditorKit.copyAction))
.setText("");
bar.add(textComp.getActionMap().get(DefaultEditorKit.pasteAction))
.setText("");
return bar;
}

// Create a JMenuBar with file & edit menus.


protected JMenuBar createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
menubar.add(file);
menubar.add(edit);

file.add(getOpenAction());
file.add(getSaveAction());
file.add(new ExitAction());
edit.add(textComp.getActionMap().get(DefaultEditorKit.cutAction));
edit.add(textComp.getActionMap().get(DefaultEditorKit.copyAction));
edit.add(textComp.getActionMap().get(DefaultEditorKit.pasteAction));
edit.add(textComp.getActionMap().get(DefaultEditorKit.selectAllAction));
return menubar;
}

// Subclass can override to use a different open action.


protected Action getOpenAction() {
return openAction;
}

// Subclass can override to use a different save action.


protected Action getSaveAction() {
return saveAction;
}
protected JTextComponent getTextComponent() {
return textComp;
}

// ********** ACTION INNER CLASSES ********** //

// A very simple exit action


public class ExitAction extends AbstractAction {
public ExitAction() {
super("Exit");
}

public void actionPerformed(ActionEvent ev) {


System.exit(0);
}
}

// An action that opens an existing file


class OpenAction extends AbstractAction {
public OpenAction() {
super("Open", new ImageIcon("icons/open.gif"));
}

// Query user for a filename and attempt to open and read the file into
// the
// text component.
public void actionPerformed(ActionEvent ev) {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(SimpleEditor.this) !=
JFileChooser.APPROVE_OPTION)
return;
File file = chooser.getSelectedFile();
if (file == null)
return;

FileReader reader = null;


try {
reader = new FileReader(file);
textComp.read(reader, null);
} catch (IOException ex) {
JOptionPane.showMessageDialog(SimpleEditor.this,
"File Not Found", "ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException x) {
}
}
}
}
}

// An action that saves the document to a file


class SaveAction extends AbstractAction {
public SaveAction() {
super("Save", new ImageIcon("icons/save.gif"));
}

// Query user for a filename and attempt to open and write the text
// component's content to the file.
public void actionPerformed(ActionEvent ev) {
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(SimpleEditor.this) !=
JFileChooser.APPROVE_OPTION)
return;
File file = chooser.getSelectedFile();
if (file == null)
return;

FileWriter writer = null;


try {
writer = new FileWriter(file);
textComp.write(writer);
} catch (IOException ex) {
JOptionPane.showMessageDialog(SimpleEditor.this,
"File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException x) {
}
}
}
}
}
}

You might also like