OOPS LAB (2)
OOPS LAB (2)
YEAR/SEM : II\III
REGULATION : 2021
vision
global market .
Mission:
Information Technology.
Transfer.
Ex.
No. Name of the Experiment
1. Solve problems by using sequential search, binary search, and quadratic sorting algorithms
(selection, insertion)
i. selection sort
ii. Insertion Sort
iii. Solve problems by using sequential search
iv. Solve problems by using binary search
2. Develop stack and queue data structures using classes and objects.
3. Develop a java application with an Employee class with Emp_name, Emp_id, Address, Mail_id,
Mobile _no as members. Inherit the classes, Programmer, Assistant Professor, Associate Professor
Professor from employee class. Add Basic Pay (BP) as the member of all the inherited classes wit of
BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club funds. Generate pa for
the employees with their gross and net salary.
4. Write a Java Program to create an abstract class named Shape that contains two integers and an e
method named print Area(). Provide three classes named Rectangle, Triangle and Circle such that
one of the classes extends the class Shape. Each one of the classes contains only the method print
that prints the area of the given shape.
7. Write a java program that implements a multi-threaded application that has three threads. First three
generates a random integer every 1 second and if the value is even, the second thread computes the
square of the number and prints. If the value is odd, the third thread will print the value of the cube
number.
8. Write a program to perform file operations.
9.
Develop applications to demonstrate the features of generics classes.
10. Develop applications using Java FX controls, layouts and menus.
11. Develop a mini project for any application using Java concepts.
Ex. No : 1(a)
Solve problems by using sequential search, binary search,
Date : and quadratic sorting algorithms using selection sort
AIM:
To Solve problems by using sequential search, binary search, and quadratic sorting
algorithms
using selection sort
. Procedure:
To selection sort a list of items, we first find the smallest item in the entire list, and put it at
the beginning.
Then we find the smallest item in everything after the first item, and put it second.
Thus we can say selection sort is not advisable for larger lists of data.
ALGORITHMS:
Step 4: EXIT
PROGRAM:
import java.util.Scanner;
public class SelectionSortExample2
{
public static void main(String args[])
{
int size, i, j, temp;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);
System.out.print("Enter Array Size : ");
size = scan.nextInt();
System.out.print("Enter Array Elements : ");
for(i=0; i<size; i++)
{
arr[i] = scan.nextInt();
}
System.out.print("Sorting Array using Selection Sort Technique..\n");
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.print("Now the Array after Sorting is :\n");
for(i=0; i<size; i++)
{
System.out.print(arr[i]+ " ");
}
}
}
Output:
Enter Array Size : 10
Enter Array Elements : 15 32 5 30 42 20 50 70 60 10
Sorting Array using Selection Sort Technique..
Now the Array after Sorting is :
5 10 15 20 30 32 42 50 60 70
RESULT
Thus the java program to Solve problems by using sequential search, binary search, and
quadratic
sorting algorithms (selection, insertion) was implemented and executed successfully
Ex. No :1(b)
InsertionSort
Date :
AIM:
To Solve problems by using sequential search, binary search, and quadratic sorting
algorithms using insertion sort
ALGORITHM:
The insertion sort algorithm is as follows.
Step 1: Repeat Steps 2 to 5 for K = 1 to N-1
Step 2: set temp = A[K]
Step 3: set J = K – 1
Step 4:Repeat while temp <=A[J]
set A[J + 1] = A[J]
set J = J – 1
[end of inner loop]
Step 5:set A[J + 1] = temp
[end of loop]
Step 6: exit
As you know, insertion sort starts from the second element assuming that the first element is already
sorted. The above steps are repeated for all the elements in the list from the second element onwards
and put in their desired positions.
PROGRAM:
import java.util.Scanner;
public class InsertionSortExample {
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
}
public static void main(String a[]){ int[] arr1
= {9,14,3,2,43,11,58,22};
System.out.println("Before Insertion
Sort"); for(int i:arr1){
System.out.print(i+" ");
}
System.out.println()
;
insertionSort(arr1);//sorting array using insertion sort
System.out.println("After Insertion Sort");
for(int i:arr1){
System.out.print(i+" ");
}
}
}
OUTPUT:
Before Insertion Sort
9 14 3 2 43 11 58 22
After Insertion Sort
2 3 9 11 14 22 43 58
RESULT:
Thus the java program to Solve problems by using sequential search, binary search, and
quadratic sorting algorithms (selection, insertion) was implemented and executed successfully
Ex. No : 1(c) Solve problems by using sequential search
Date :
AIM:
To Solve problems by using sequential search, binary search, and quadratic sorting algorithms
Procedure
PROGRAM:
class GFG {
// Driver Code
public static void main(String args[])
{
// Given arr[]
int arr[] = { 2, 3, 4, 10, 40 };
// Element to search
int x = 10;
// Function Call
int result = search(arr, x);
if (result == -1)
System.out.print("Element is not present in array");
else
System.out.print("Element is present"
+ " at index "
+ result);
}
}
OUTPUT:
Element is present at index 3
RESULT:
Thus the java program to Solve problems by using sequential search, binary search, and quadratic
sorting algorithms (selection, insertion) was implemented and executed successfully.
Ex. No : 1(d) Solve problems by using binary search
Date :
AIM:
To Solve problems by using sequential search, binary search, and quadratic sorting algorithms
Procedure
1. Calculate the mid element of the collection.
2. Compare the key items with the mid element.
3. If key = middle element, then we return the mid index position for the key found.
4. Else If key > mid element, then the key lies in the right half of the collection. Thus repeat
steps
1 to 3 on the lower (right) half of the collection.
5. Else key < mid element, then the key is in the upper half of the collection. Hence you need
to repeat the binary search in the upper half.
PROGRAM:
class BinarySearchExample{
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}
OUTPUT:
Element is found at index: 2
RESULT
Thus the java program to Solve problems by using sequential search, binary search, and quadratic
sorting
algorithms (selection, insertion) was implemented and executed successfully.
Ex. No : 2(a) Stack using Class and objects
Date :
AIM:
To Develop stack of data structures using classes and objects.
ALGORITHM:
1. Create theinterfacestackoperationwithmethoddeclarationsforpushandpop.
2. Create the class astack which implements the interface and provides implementation
forthemethods
pushandpop.Alsodefinethemethodfordisplayingthevalues storedinthestack.Handlethe
stackoverflowandstackunderflowcondition .
3. Create the class teststack .Get the choice from the user for the operation to be performed
.andalsohandletheexceptionthatoccurwhileperformingthestackoperation.
4. Create the objectandinvokethemethodforpush,pop,displaybasedontheinput fromtheuser.
Once we import the Stack class, we can create a Stack object as shown below:
Stack mystack = new Stack();
We can also create a generic type of Stack class object as follows:
Stack<data_type> myStack = new Stack<data_type>;
Here data_type can be any valid data type in Java.
We can remove the element from the stack using the “pop” operation. The element pointed by the
Top at present is popped off the stack.
PROGRAM:
import java.util.*;
public class StackDemo {
stack: []push(42)
stack: [42]push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]pop -> 42
stack: []
pop -> empty stack
RESULT:
To Develop stack of data structures using classes and objects was created and the output
verified successfully.
Ex. No : 2(b) Queue using Class and object
Date :
AIM:
To Develop queue of data structures using classes and objects
ALGORITHM:
1. Create theinterfacequeueoperationwithmethoddeclarationsforenqueueanddequeue.
2. Create the class a queue which implements the interface and provides implementation
forthemethods
enqueueanddequeue.Alsodefinethemethodfordisplayingthevalues storedinthe
queue.Handlethe queueoverflowandqueueunderflowcondition .
3. Create the class testqueue .Get the choice from the user for the operation to be
performed
.andalsohandletheexceptionthatoccurwhileperformingthequeueoperation.
4. Create the
objectandinvokethemethodforenqueue,dequeue,displaybasedontheinput fromtheuser.
str_queue.add(“one”);
str_queue.add(“two”);
str_queue.add(“three”);
import java.util.*;
public class Queue{
int SIZE =5;
int items[]=new int[SIZE];
int front, rear;
Queue(){
front =-1;
rear =-1;
}
boolean isFull(){
if(front ==0&& rear == SIZE -1){
return true;
}
return false;
}
boolean isEmpty(){
if(front ==-1)
return true;
else
return false;
}
void enQueue(int element){
if(isFull()){
System.out.println("\nThe queue is full");
}
else{
if(front ==-1){
front =0;
}
rear++;
items[rear]= element;
System.out.println("\nThe element "+ element +" is inserted");
}
}
int deQueue(){
int element;
if(isEmpty()){
System.out.println("\nThe queue is empty");
return(-1);
}
else{
element = items[front];
if(front >= rear){
front =-1;
rear =-1;
}
else{
front++;
}
System.out.println("\nThe element "+element +" is deleted");
return(element);
}
}
void display(){
int i;
if(isEmpty()){
System.out.println("The queue is empty ");
}
else{
System.out.println("\nThe elements of the queue are: ");
for(i = front; i <= rear; i++)
System.out.print(items[i]+"
");
}
}
public static void main(String[] args)
{ Queue input_queue =new Queue();
for(int i =1; i <6; i ++){
input_queue.enQueue(i *100);
}
System.out.println("The queue is defined as: "+ input_queue);
input_queue.enQueue(6);
input_queue.display();
input_queue.deQueue();
input_queue.display();
}
}
OUTPUT:
The element 100 is inserted
The element 200 is
inserted
RESULT:
To Develop queue of data structures using classes and objects was created and the output
verified successfully.
Ex. No : 3 Develop a java application with an Employee class with
Date : Emp_name, Emp_id, Address, Mail_id, Mobile_no as members.
Inherit the classes, Programmer, Assistant Professor, Associate
Professor and Professor from employee class. Add Basic Pay
(BP) as the member of all the inherited classes with 97% of BP
as DA,
10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff
club funds. Generate pay slips for the employees with their
gross and
net salary
PROCEDURE
1. Create theclassemployeewithname,Empid,address,mailid,mobilenoasmembers.
2. Inherittheclassesprogrammer,asstprofessor,associateprofessorandprofessorfromemplo
yeeclass.
3. AddBasicPay(BP)as thememberofalltheinheritedclasses.
4. CalculateDAas 97%ofBP,HRAas 10%ofBP,PF as 12%ofBP,Staffclubfundas 0.1%ofBP.
5. Calculategrosssalaryand netsalary.
6. Generatepayslip forallcategoriesofemployees.
7.Createtheobjectsfortheinheritedclassesand invoke thenecessarymethodstodisplaythePayslip.
PROGRAM:
import java.util.Scanner;
class Employee{
String Emp_name;
int Emp_id;
String Address;
String Mail_id;
int Mobile_no;
void display(){
System.out.println(Emp_name)
;
//
Syetem.out.println(Address);
System.out.println(Emp_id);
System.out.println(Mail_id);
System.out.println(Mobile_no)
;
}
}
class Programmer extends Employee{
int BP;
}
}
class Assistant_Professor extends Employee{
int BP;
void display(){
System.out.println(BP)
;
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP)
;
System.out.println("PF"+0.12*BP);
System.out.println("SATFF CLUD
FUND"+0.001*BP);
}
}
class Associate_Professor extends Employee{
int BP;
void display(){
System.out.println(BP)
;
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP)
;
System.out.println("PF"+0.12*BP);
System.out.println("SATFF CLUD FUND"+0.001*BP);
}
}
class Professor extends Employee{
int BP;
void display(){
System.out.println(BP)
;
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP)
;
System.out.println("PF"+0.12*BP)
;
System.out.println("SATFF CLUD FUND"+0.001*BP);
}
}
class Main{
public static void main(String args[])
{ System.out.println("\n
1.Programmer\n2.Assistant_Professor\n3.Associate_Professor\
n4.Professor"); Scanner input=new Scanner(System.in);
System.out.println("Enter an integer: ");
int ch=input.nextInt();
switch (ch) {
case 1:
Employee e1=new Employee();
Programmer p1=new Programmer();
e1.Emp_name="ABC";
e1.Address="y-city";
e1.Mail_id="[email protected]";
e1.Emp_id=567;
e1.Mobile_no=2345678;
p1.BP=15000;
p1.display();
e1.display();
break;
case 2:
Employee e2=new Employee();
Assistant_Professor p2=new Assistant_Professor();
e2.Emp_name="DEF";
e2.Address="A-city";
e2.Mail_id="[email protected]"
; e2.Emp_id=123;
e2.Mobile_no=987321;
p2.BP=30000;
p2.display();
e2.display();
break;
case 3:
Employee e3=new Employee();
Associate_Professor p3=new Associate_Professor();
e3.Emp_name="GHF";
e3.Address="B-city";
e3.Mail_id="[email protected]"
; e3.Emp_id=456;
e3.Mobile_no=98710;
p3.BP=30000;
p3.display();
e3.display();
break;
case 4:
Employee e4=new
Employee(); Professor p4=new
Professor();
e4.Emp_name="KANNAN";
e4.Address="TRICHY";
e4.Mail_id="[email protected]"
; e4.Emp_id=789;
e4.Mobile_no=9810;
p4.BP=30000;
p4.display();
e4.display();
break;
case 5:
//exit(1);
default:
System.out.println("enter correct choice");
}
}
}
OUTPUT:
1. Programmer
2.Assistant_Professor
3.Associate_Professor
4.Professor
Enter an integer:
1
15000
DA14550.0
HRA1500.0
PF1800.0SATFF CLUD FUND15.0
ABC
567
[email protected]
2345678
RESULT:
Thus the development of a java application with an Employee class has been
implemented
and the output verified successfully.
Ex. No : 4 Write a Java Program to create an abstract class named Shape that contains
Date : two integers and an empty method named printArea(). Provide three classes
named Rectangle, Triangle and Circle such that each one of the classes
extends the class Shape. Each one of the classes contains only the method
printArea( ) that prints the area of the given shape.
AIM:
To Write a Java Program to create an abstract class named Shape that contains two
integers and an empty method named printArea().
PROCEDURE
1. Createanabstractclassnamedshapethat
containstwointegersandanemptymethod namedprintarea().
2. Providethree classesnamedrectangle,triangleandcirclesuchthateachoneofthe
classesextends theclassShape.
3.Eachofthe
inheritedclassfromshapeclassshouldprovidethe
implementationforthemethodprintarea().
4.Getthe inputandcalculate thearea ofrectangle,circleandtriangle.
5. Intheshapeclass,createthe objectsfor thethree
inheritedclassesandinvokethemethodsanddisplaytheareavaluesofthedifferentshapes.
PROGRAM:
import java.util.Scanner;
int a = 10, b = 2;
{ Rectangle(int a, int b) {
super(a, b);
}
void Printarea() {
System.out.println("area of rectangle is " + (a * b));
}
{ Triangle(int a, int b) {
super(a, b);
}
void Printarea(){
System.out.println("area of triangle is " + (0.5 * a * b));
}
{ Circle(int a, int b) {
super(a, b);
}
void Printarea() {
System.out.println("area of circle is " + (3.14 * a * a));
}
class Z {
{ Shape shape=null;
String input;
int width, height;
while (true) {
System.out.println("height: ");
height =scanner.nextInt();
System.out.println("width: ");
width = scanner.nextInt();
if("circle".equalsIgnoreCase(input)){
shape=new Circle(width, height);
}
else if("rectangle".equalsIgnoreCase(input)){
shape=new Rectangle(width, height);
}
else{ // == triangle
shape=new Triangle(width, height);
}
shape.Printarea();
OUTPUT:
which shape? circle/rectangle/triangle (write any other thing for
quitting): Circle
height:
5
width: 5
area of circle is 78.5
RESULT:
Thus the java program for to create an abstract class named Shape that contains two
integers and an empty method named printArea().has been implemented and the output
verified successfully.
Ex. No : 5 Solve the above problem using an interface.
Date :
AIM:
To Solve the above problem using an interface.
.
PROCEDURE
1. Createanabstractclassnamedshapethat
containstwointegersandanemptymethod namedprintarea().
2. Providethree classesnamedrectangle,triangleandcirclesuchthateachoneofthe
classesextends theclassShape.
3.Eachofthe
inheritedclassfromshapeclassshouldprovidethe
implementationforthemethodprintarea().
4.Getthe inputandcalculate thearea ofrectangle,circleandtriangle.
5. Intheshapeclass,createthe objectsfor thethree
inheritedclassesandinvokethemethodsanddisplaytheareavaluesofthedifferentshapes.
PROGRAM
import java.util.Scanner;
interface Shape
{
void input();
void area();
}
class Circle implements Shape
{
int r =0;
double pi =3.14, ar =0;
@Override
public void input()
{
r =5;
}
@Override
public void area()
{
ar = pi * r * r;
System.out.println("Area of
circle:"+ar);
}
}
class Rectangle extends Circle
{
int l =0, b =0;
double ar;
public void input()
{
super.input();
l =6;
b =4;
}
public void area()
{
super.area();
ar = l * b;
System.out.println("Area of rectangle:"+ar);
}
}
public class Demo
{
public static void main (String[] args)
{
Rectangle obj =new Rectangle();
obj.input();
obj.area();
}
}
OUTPUT:
Area of circle:78.5
Area of rectangle:24.0
RESULT:
Thus the RSA algorithm has been implemented using HTML & CSS and the output
has been verified successfully.
Ex. No : 6(a)
Implement Pre defined exception handling
Date :
AIM:
To Implement exception handling and creation of user defined exceptions.
PROCEDURE
1. CreateaclasswhichextendsExceptionclass.
2. Create
aconstructorwhichreceivesthestringasargument.3.GettheAm
o untasinputfromtheuser.
4. Iftheamountisnegative,the exceptionwillbegenerated.
5. Usingthe
exceptionhandlingmechanism,thethrownexceptionishandledbythecatchconstruc
t.
6. Aftertheexception ishandled, thestring“invalid amount“willbedisplayed.
7. Iftheamountis greaterthan0,themessage“AmountDeposited“willbedisplayed
PROGRAM:
import java.util.Scanner;
publicclassExceptionExample{
publicstaticvoid main(String args[]){
Scanner sc
=newScanner(System.in);
System.out.println("Enter first number: ");
int a = sc.nextInt();
System.out.println("Enter second number: ");
int b = sc.nextInt();
int c = a/b;
System.out.println("The result is: "+c);
}
}
ExceptionExample.main(ExceptionExample.java:10)
}
}
catch(AgeDoesnotMatchException e){
e.printStackTrace();
}
this.name = name;
this.age = age;
}
publicvoid display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
publicstaticvoid main(String args[]){ Scanner
sc=newScanner(System.in);
System.out.println("Enter the name of the Student:
"); String name = sc.next();
System.out.println("Enter the age of the Student should be 17 to
24 (including 17 and 24): ");
int age = sc.nextInt();
Student obj =newStudent(name, age);
obj.display();
}
}
OUTPUT:
Enter the name of the Student:
Krishna
Enter the age of the Student should be 17 to 24 (including 17 and 24):
14
AgeDoesnotMatchException: Age is not between 17 and 24
Name of the Student:
Krishna' Age of the Student:
14
at Student.<init>(Student.java:18)
at Student.main(Student.java:39)
RESULT:
Thus the Implementation of exception handling and creation of user defined exceptions
has been created and the output has been verified successfully.
Ex. No : 7 Write a java program that implements a multi-threaded application that has three threads. First thread
Date : generates a random integer every 1 second and if the value is even, the second thread computes the square of
the
number and prints. If the value is odd, the third thread will print the value of the cube of the number.
AIM:
To Write a java program that implements a multi-threaded application that has three threads
PROCEDURE
1. Createaclassevenwhichimplementsfirstthreadthatcomputes.thesquareofthenumber.
2. run()methodimplementsthecodetobeexecutedwhenthreadgetsexecuted.
3. Createaclassoddwhichimplementssecondthreadthatcomputesthecube ofthe number.
4. Createathirdthreadthatgeneratesrandom number.Iftherandomnumberiseven,itdisplaysthe
square of the number.If the random number generated is odd , it displays the cube of
thegivennumber .
5. TheMultithreading isperformed
andthetaskswitchedbetweenmultiplethreads.6.Thesleep()methodmakesthethreadtos
u spendforthespecifiedtime.
PROGRAM:
import java.util.*;
class even implements Runnable
{
public int x; public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN and Square of " + x + " is: " + x * x);
}
}
class odd implements Runnable
{
public int x; public odd(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x * x * x);
}
}
class A extends Thread
{
public void run()
{
int num = 0;
Random r = new Random(); try
{
for (int i = 0; i < 5; i++)
{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num); if (num % 2 == 0)
{
Thread t1 = new Thread(new even(num)); t1.start();
}
else
{
Thread t2 = new Thread(new odd(num)); t2.start();
} Thread.sleep(1000);
System.out.println("
");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
class multithreadprog
{
Output:
Main Thread and Generated Number is 87
New Thread 87 is ODD and Cube of 87 is: 658503
Main Thread and Generated Number is 49
New Thread 49 is ODD and Cube of 49 is: 117649
Main Thread and Generated Number is 9
New Thread 9 is ODD and Cube of 9 is: 729
Main Thread and Generated Number is 28
New Thread 28 is EVEN and Square of 28 is: 784
Main Thread and Generated Number is 12
New Thread 12 is EVEN and Square of 12 is: 144
RESULT:
Thus that implementation of a multi-threaded application that has three threads
has been implemented and the output has been verified successfully.
Ex. No : 8 Write a program to perform file operations.
Date :
AIM:
To Write a program to perform file operations.
.
PROCEDURE
PROGRAM:
RESULT:
Thus a program to perform file operations has been implemented and
the output has been verified successfully.
Ex. No : 9 Develop applications to demonstrate the features of generics classes.
Date :
AIM:
To Develop applications to demonstrate the features of generics classes.
PROCEDURE
2. Getthesetofthevalues belongingtospecificdatatype.
3. Createtheobjectsoftheclasstohold integer,characteranddoublevalues.
4. Createthemethodtocompare the valuesandfindthemaximum valuestored inthearray.
5. Invoke
themethodwithinteger,characterordoublevalues.Theoutputwillbedisplayed
basedonthedatatypepassedtothemethod.
PROGRAM
classMyClass<TextendsComparable<T>>
{ T[]vals;
MyClass(T[]o)
{
vals= o;
}
publicT min()
{ Tv=vals[
0];
for(inti=1;i<vals.length;i++)if(vals[i].compareTo(v)<0)
v=vals[i];returnv;
}
publicTmax()
{ Tv=vals[0]; for(inti=1;i<vals.length;i+
+)if(vals[i].compareTo(v) >0) v=vals[i];returnv;
}
}
classgendemo
{
publicstatic voidmain(Stringargs[])
{ inti;
Integerinums[]={10,2,5,4,6,1};Characterchs[]={'v','p','s','a','n','h'
}; Doubled[]={20.2,45.4,71.6,88.3,54.6,10.4};
MyClass<Integer> iob = new
MyClass<Integer>(inums);MyClass<Character>cob=newMyClass<Character>(chs);MyClass<Dou
bl e>dob = new MyClass<Double>(d);System.out.println("Max value in inums: " + iob.max());
System.out.println("Min value in inums: " + iob.min());
System.out.println("Max value in chs: " + cob.max());
System.out.println("Min value in chs: " + cob.min());
System.out.println("Max value in chs: " +
dob.max());
System.out.println("Minvalueinchs:"+dob.min());
}
}
Output:
Max value in inums: 10
Min value in inums: 1
Max value in chs: v
Min value in chs: a
Max value in chs: 88.3
Min value in chs: 10.4
RESULT:
Thus To Develop applications to demonstrate the features of generics classes has been
demonstrated
and the output is verified successfully.
Ex. No : 10
Develop applications using JavaFX controls, layouts and menus.
Date :
AIM:
To Develop applications using JavaFX controls, layouts and menus.
PROGRAM
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.layout.StackPane;
public class JavaFXExample extends Application{
//application starts here
@Override
publicvoid start(Stage s) throws Exception {
//create button
Button btn = new Button("Sample Button");
//create stackpane
StackPane r=new StackPane();
//add button to stackpane
r.getChildren().add(btn);
//create scene
Scene sc=new Scene(r,500,300);
//set title for the stage
s.setTitle(" JavaFX
Example");
//set scene for the stage
s.setScene(sc);
//display the
result s.show();
}
//main method
public static void main (String[] args)
{
launch(args);
}
}
Output
RESULT:
Thus To Develop applications using JavaFX controls, layouts and menus has
been implemented.
Ex. No : 11(a) Develop a mini project for any application using Java concepts.
Date :
AIM:
CODE
Logon.java
importjava.awt.*;importjava.awt.event.*;import javax.swing.*;importjava.sql.*;
publicclassLogonextendsJFrameimplementsActionListener
{
intfl=1;
JPanelpLog= newJPanel();JLabel lbUser,
lbPass;JTextFieldtxtUser;JPasswordFieldtxtPass;JButton btnOk, btnCancel;Connectioncon;
publicStringuser;publicLogon()
{
super("LibraryManagementSystem.");setSize(275, 300);
addWindowListener(newWindowAdapter()
{ publicvoidwindowClosing(WindowEventwe)
{setVisible(false); dispose();System.exit(0);
}
}
);
pLog.setLayout(null);
lbUser = new JLabel ("Username:");lbUser.setForeground (Color.black);lbUser.setBounds (20, 15,
75, 25);lbPass = new JLabel ("Password:");lbPass.setForeground
(Color.BLACK);lbPass.setBounds
(20, 50, 75, 25);txtUser = new JTextField ();txtUser.setBounds (100, 15, 150, 25);txtPass = new
JPasswordField ();txtPass.setBounds(100,50,150,25)
AddBCat.java
importjava.awt.*;importjava.awt.event.*;import javax.swing.*;importjava.sql.*;
publicclassAddBCatextendsJInternalFrame implementsActionListener
{ JPanelpNew=newJPanel();JLabellbUser;
JTextFieldtxtUser;JButtonbtnOk,btnCancel
; privateStatementst;
public AddBCat(Connectioncon)
{
super("NewBookCategory",false, true, false,true);setSize(280, 175);
lbUser = new JLabel ("Category:");lbUser.setForeground (Color.black);lbUser.setBounds (20,
20,
100, 25);txtUser = new JTextField ();txtUser.setBounds (100, 20, 150, 25);btnOk = new
JButton ("OK");btnOk.setBounds (20, 100, 100, 25);btnOk.addActionListener (this);btnCancel
= new JButton ("Cancel");btnCancel.setBounds(150,100,100,25);btnCancel.addActionListener
(this);pNew.setLayout(null);
pNew.add (lbUser);pNew.add (txtUser);pNew.add (btnOk);pNew.add(btnCancel);
getContentPane().add(pNew);try
{
st=con.createStatement();
}
catch(SQLExceptionsqlex)
{
JOptionPane.showMessageDialog(null,"AProblemOccursWhileLoadingtheForm.");dispose();
}
setVisible(true);
}
publicvoidactionPerformed(ActionEventae)
{
Objectobj=ae.getSource();if(obj==btnOk)
{ if(txtUser.getText().equals("")){txtUser.requestFocus();
JOptionPane.showMessageDialog(this,"CategorynotProvided."
);
}
else
{
try
{ Stringid=txtUser.getText
();
Stringq= "SELECT*FROMBCat";ResultSetrs = st.executeQuery(q);
intfl=0;while(rs.next())
{ StringmemberNo=rs.getString("Cat");if(id.equals(memberN
o))
{
JOptionPane.showMessageDialog(this,"Already existingCategory");txtUser.setText("");
txtUser.requestFocus();fl=1;
break;
}
}
rs.close();if(fl==0){
q="INSERT INTOBCat "+"VALUES('"+txtUser.getText()+"')";
intresult=st.executeUpdate(q);if(result==1) {
JOptionPane.showMessageDialog(this,"NewCategoryCreated.");txtUser.setText(""
); txtUser.requestFocus();
}
else
{ JOptionPane.showMessageDialog(this,"ProblemwhileCreating.");txtUser.setText(
"");
txtUser.requestFocus();
}
}
}
catch(SQLExceptionsqlex)
{
JOptionPane.showMessageDialog(this,"ProblemwhileCreatingexcep.");
}
}
}
if(obj==btnCancel){setVisible (false);dispose();
}
}
}
(120,45,175,25);txtBookAuthor=new JTextField();
AddBook.java
importjava.awt.*;
importjava.awt.event.*;
import javax.swing.*;
importjava.sql.*;
publicclassAddBookextendsJInternalFrameimplementsActionListener,FocusListener
{
JPanelpBook=new JPanel();
JLabellbBookId,lbBookName,lbBookAuthor,lbBookRef,lbBookCategory;JTextFieldtxtBookId,txt
Bo
okName,txtBookAuthor;
JComboBox cboBookCategory;JButton btnOk, btnCancel;JRadioButton
rby,rbn;ButtonGroupbg; String[]cn=newString[100];
Statementst;
long id = 0; inti,j,ref=0;
publicAddBook(Connectioncon
)
{
super("AddNewBook", false,true,true, true);setSize(325, 250);
lbBookId = new JLabel ("Book Id:");
lbBookId.setForeground (Color.black);
lbBookId.setBounds (15, 15, 100, 20);
lbBookName = new JLabel ("Book Name:");
lbBookName.setForeground (Color.black);
lbBookName.setBounds (15, 45, 100, 20);
lbBookAuthor = new JLabel ("Book Author:");
lbBookAuthor.setForeground (Color.black);
lbBookAuthor.setBounds (15, 75, 100, 20);
lbBookRef = new JLabel ("Reference:");
lbBookRef.setForeground (Color.black);
lbBookRef.setBounds (15, 105, 100, 20);
lbBookCategory=newJLabel("BookCategory:")
; lbBookCategory.setForeground (Color.black);
lbBookCategory.setBounds (15, 135, 100, 20);
txtBookId=newJTextField();
txtBookId.setHorizontalAlignment(JTextField.RIGHT);
txtBookId.addFocusListener(this);
txtBookId.setBounds (120, 15, 175, 25);
txtBookName = new JTextField ();
txtBookName.setBounds
txtBookAuthor.setBounds(120,75,175,25);rby=new
JRadioButton("yes");rby.addActionListener(this);rby.setBounds(120,105,60,25);
rbn=new JRadioButton("no");rbn.addActionListener(this);rbn.setBounds(180,105,60,25);bg = new
ButtonGroup();bg.add(rby);
bg.add(rbn);rbn.setSelected(true)
; cboBookCategory = new
JComboBox();cboBookCategory.setBounds(120,135,175,25);btnOk=newJButton("OK");
btnOk.setBounds (50, 175, 100, 25);btnOk.addActionListener (this);btnCancel = new
JButton
("Cancel");btnCancel.setBounds(170,175,100,25);btnCancel.addActionListener(this);
txtBookId.addKeyListener(newKeyAdapter()
{
publicvoidkeyTyped(KeyEventke)
{
charc= ke.getKeyChar();
if(!((Character.isDigit(c))||(c==KeyEvent.VK_BACK_SPACE)))
{
getToolkit().beep ();ke.consume();
}
}
}
);
txtBookAuthor.addKeyListener(newKeyAdapter()
{
publicvoidkeyTyped(KeyEventke)
{
charc= ke.getKeyChar();
if(!((Character.isLetter(c))||(c==KeyEvent.VK_BACK_SPACE)||(c==KeyEvent.VK_SPACE)))
{
getToolkit().beep ();ke.consume();
}
}
}
);
pBook.setLayout (null);pBook.add (lbBookId);pBook.add
(lbBookName);pBook.add (lbBookAuthor);pBook.add
(lbBookRef);pBook.add(lbBookCategory);pBook.add (txtBookId);pBook.add
(txtBookName);pBook.add (txtBookAuthor);pBook.add(rby); pBook.add(rbn);
pBook.add(cboBookCategory);pBook.add(btnOk);
pBook.add(btnCancel);
getContentPane().add(pBook,BorderLayout.CENTER);try
{ i=0;
st=con.createStatement();
ResultSetrs=st.executeQuery("Select*fromBCat");while(rs.next(
))
{
cn[i]=rs.getString(1);i++;
}
for(j=0;j<i;j++)
{
cboBookCategory.addItem(cn[j]);
}
cboBookCategory.addActionListener(this);cboBookCategory.setSelectedItem(cn[0]);rs.close()
;
}
catch(SQLExceptionsqlex)
{
JOptionPane.showMessageDialog(null,"AProblemOccursWhileLoadingForm.");dispose();
}
setVisible(true);
}
publicvoidactionPerformed(ActionEventae)
{
Objectobj=ae.getSource();if(obj==btnOk)
{
if(txtBookId.getText().equals(""))
{
JOptionPane
//INSERTQuerytoAddBookRecordinTable.
/* String q = "INSERT INTO Books " +"VALUES (" + id + ", '" + txtBookName.getText()
+ "','"+txtBookAuthor.getText()+"',"+ref+",'"+cboBookCategory.getSelectedItem()+"',"+0
+",'"+s8+"','"+s8+")";*/
intresult=st.executeUpdate("Insert intoBooksvalues("+id+",'"+txtBookName.getText()
+"','" + txtBookAuthor.getText() +"', " + ref + ", '"
+cboBookCategory.getSelectedItem().toString()+"', "+0+ ",'"+s8+"','"+s8+ "')");
//Running Query.if(result==1) {
//IfQuerySuccessful.
JOptionPane.showMessageDialog(this,"RecordhasbeenSaved.");txtClear();
//ClearingtheTextFields.
}
else
{
//IfQueryFailed.
OptionPane.showMessageDialog(this,"ProblemwhileSavingtheRecord.");
}
} catch(SQLExceptionsqlex){
JOptionPane.showMessageDialog(this,"ProblemwhileSavingtheRecordExcep."
);
}
}
}
if(obj==btnCancel){ /IfCancelButtonPressedUnloadtheFrom.setVisible(false);
dispose();
}
if(obj==rby)
{
ref=1;
}
elseif(obj==rbn)
{
ref=0;
}
}
publicvoid focusGained(FocusEventfe){}publicvoidfocusLost(FocusEventfe){
if(txtBookId.getText().equals("")){
}
else{
id= Integer.parseInt(txtBookId.getText());longbookNo;
booleanfound=false;try{ Stringq="SELECT*FROMBooksWHEREBId="+id+"";Result
Setrs= st.executeQuery(q); rs.next();
bookNo=rs.getLong("BId");if(bookNo==id) {
found=true;txtClear();
JOptionPane.showMessageDialog(this,id+ "isalreadyassigned.");
}
else{
found= false;
}
}
catch(SQLExceptionsqlex)
{
}
}
}
privatevoidtxtClear (){txtBookId.setText ("");txtBookName.setText
("");txtBookAuthor.setText
("");cboBookCategory.setSelectedIndex(0);txtBookId.requestFocus ();
}
}
}
if(obj==rby)
{
ref=1;
}
elseif(obj==rbn)
{
ref=0;
}
}
publicvoid focusGained(FocusEventfe){}publicvoidfocusLost(FocusEventfe){
if(txtBookId.getText().equals("")){
}
else{
id= Integer.parseInt(txtBookId.getText());longbookNo;
booleanfound=false;try{
Stringq="SELECT*FROMBooksWHEREBId="+id+"";ResultSetrs= st.executeQuery(q);
rs.next();
bookNo=rs.getLong("BId");if(bookNo==id) {
found=true;txtClear();
JOptionPane.showMessageDialog(this,id+ "isalreadyassigned.");
}
else{
found= false;
}
}
catch(SQLExceptionsqlex)
{
}
}
}
privatevoidtxtClear (){txtBookId.setText ("");txtBookName.setText
("");txtBookAuthor.setText
("");cboBookCategory.setSelectedIndex(0);txtBookId.requestFocus ();
}
}
ke.consume();
}
}
}
);
btnOk = new JButton ("OK");btnOk.setBounds (20, 123, 100,
25);btnOk.addActionListener (this);btnCancel = new JButton
("Cancel");btnCancel.setBounds(150,123,100,25);btnCancel.addActionListener
(this);pNew.setLayout(null);
pNew.add (lbUser);pNew.add (lbDate);pNew.add (lbBooks);pNew.add (txtUser);pNew.add
(txtDate);pNew.add (txtBooks);pNew.add (btnOk);pNew.add(btnCancel);
getContentPane().add(pNew);try{
st=con.createStatement();
} catch(SQLExceptionsqlex){
JOptionPane.showMessageDialog(null,"AProblemOccursWhileLoadingtheForm.");dispose(
);
}
setVisible(true);
}
publicvoidactionPerformed(ActionEventae)
{Objectobj=ae.getSource(); if(obj==btnOk)
{ if(txtUser.getText().equals("")){txtUser.requestFocus();
JOptionPane.showMessageDialog(this,"UsernamenotProvided.");
}
else {try{
Stringid=txtUser.getText();
Stringq="SELECTCNameFROMMeCat";ResultSetrs= st.executeQuery(q);
intfl=0;while(rs.next())
{
String memberNo=rs.getString("CName");
if(id.equals(memberNo))
{
JOptionPane.showMessageDialog(this,"Already existingCategory");txtUser.setText("");
txtUser.requestFocus();fl=1;
break;
}
} rs.close();intnum=0;try{
rs=st.executeQuery("Select*FromMeCat");while(rs.next()
)
{
num++;
}
num++;rs.close();
}
catch(Exceptione)
{
JOptionPane.showMessageDialog(this,"ProblemwhileCreatingexcep1.");
} if(fl==0){
intresult=st.executeUpdate("InsertintoMeCatValues("+num+",'"+txtUser.getText()
+"'
,"+Integer.parseInt(txtBooks.getText())+","+Integer.parseInt(txtDate.getText())+")"
);//Running Query.if(result==1) {
JOptionPane.showMessageDialog(this,"NewCategoryCreated.");txtUser.setText("");
txtUser.requestFocus();
} else{
JOptionPane.showMessageDialog(this,"ProblemwhileCreating.");txtUser.setText(""
); txtUser.requestFocus();
}
}
} catch(SQLExceptionsqlex){
JOptionPane.showMessageDialog(this,"ProblemwhileCreatingexcep."
);
}
}
}
if(obj==btnCancel){setVisible (false);dispose();
}
}
}
Addmember.java
importjava.awt.*;importjava.awt.event.*;
importjava.util.Calendar;import
javax.swing.*;importjava.sql.*; importjava.util.*;
publicclassAddMemberextendsJInternalFrameimplementsActionListener,FocusListener{JPanelp
Me mber =newJPanel();
JLabellbMemberId,lbMemberName,lbMemberpwd,lbEntryDate,lbCategory;JTextField
txtMemberId, txtMemberName, txtMemberpwd,txtMemberdate;JButtonbtnOk, btnCancel;
JComboBoxcboMemCategory;Statementst;
longid=0;
String[]cn=newString[100];intid1,im,iy,vd,vm,vy,
i; public AddMember(Connectioncon){
super("AddNewMember",false,true, false,true);setSize(355, 250);
lbMemberId = new JLabel ("Member Id:");lbMemberId.setForeground
(Color.black);lbMemberId.setBounds (15, 15, 100, 20);lbMemberName=
newJLabel("MemberName:");lbMemberName.setForeground
(Color.black);lbMemberName.setBounds (15, 45, 100, 20);lbMemberpwd = new JLabel
("Member Pwd:");lbMemberpwd.setForeground (Color.black);lbMemberpwd.setBounds (15, 75,
110,
20);lbEntryDate = new JLabel ("Entry Date:");lbEntryDate.setForeground
(Color.black);lbEntryDate.setBounds (15, 105, 100, 20);lbCategory = new JLabel
("Category:");lbCategory.setForeground(Color.BLACK);lbCategory.setBounds(15,135,100,20);
txtMemberId=newJTextField();
txtMemberId.setHorizontalAlignment(JTextField.RIGHT);txtMemberId.addFocusListener
(this);txtMemberId.setBounds (125, 15, 205, 25);txtMemberName=new JTextField
();txtMemberName.setBounds (125, 45, 205, 25);txtMemberpwd=new JTextField
();txtMemberpwd.setBounds (125, 75, 205, 25);txtMemberdate=new
JTextField();txtMemberdate.setBounds(125,105,205,25);txtMemberdate.setEditable(false);
cboMemCategory=new
JComboBox();cboMemCategory.setBounds(125,135,100,20);GregorianCalendargcal=newGregori
an Calendar();id= gcal.get(Calendar.DATE);im=(int)gcal.get(Calendar.MONTH)
+1;iy=gcal.get(Calendar.YEAR);
Stringidate=id+"/"+im+"/"+iy;txtMemberdate.setText(idate);btnOk = new JButton
("OK");btnOk.setBounds (30, 165, 125, 25);btnOk.addActionListener
(this);btnCancel=newJButton("Cancel");
btnCancel.setBounds (190, 165, 125, 25);btnCancel.addActionListener
(this);txtMemberId.addKeyListener(newKeyAdapter()
{publicvoidkeyTyped(KeyEventke){ charc= ke.getKeyChar(); if(!((Character.isDigit(c))||
(c==KeyEvent.VK_BACK_SPACE))){getToolkit().beep();
ke.consume();
}
}
}
); txtMemberName.addKeyListener(newKeyAdapter()
{publicvoidkeyTyped(KeyEventke){ charc= ke.getKeyChar();
if(!((Character.isLetter(c))||(c==KeyEvent.VK_BACK_SPACE)||(c==KeyEvent.VK_SPACE))){
getToolkit().beep();ke.consume();
}
}
}
);
pMember.setLayout(null);
pMember.add (lbMemberId);pMember.add (lbMemberName);pMember.add
(lbMemberpwd);pMember.add (lbEntryDate);pMember.add (txtMemberId);pMember.add
(txtMemberName);pMember.add
(txtMemberpwd);pMember.add(txtMemberdate);pMember.add (btnOk);pMember.add
(btnCancel);pMember.add (lbCategory);pMember.add(cboMemCategory);
getContentPane().add(pMember,BorderLayout.CENTER);intj;
try {i=0; st=con.createStatement();
ResultSetrs=st.executeQuery("Select*fromMeCat");while(rs.next()
)
{
cn[i]=rs.getString(2);i++;
}
for(j=0;j<i;j++)
{
cboMemCategory.addItem(cn[j]);
}
cboMemCategory.addActionListener(this);cboMemCategory.setSelectedItem(cn[0]);rs.close();
} catch(SQLExceptionsqlex){
JOptionPane.showMessageDialog(null,"AProblemOccursWhileLoadingForm.");dispose(
);
}
setVisible(true);
} publicvoidactionPerformed(ActionEventae)
{Objectobj=ae.getSource(); if(obj==btnOk){
if (txtMemberId.getText().equals (""))
{JOptionPane.showMessageDialog(this,"Member'sIdnotProvided.");txtMemberId.requestFocus
();
}
else if (txtMemberName.getText().equals (""))
{JOptionPane.showMessageDialog(this,"Member'sNamenotProvided.");
txtMemberName.requestFocus();
}
else if (txtMemberpwd.getText().equals ("")) {JOptionPane.showMessageDialog (this, "Member's
Password not Provided.");txtMemberpwd.requestFocus ();
}
else {try{
intmtype=cboMemCategory.getSelectedIndex()+1;
Stringq="INSERTINTOMembers"+"VALUES("+id+",'"+txtMemberpwd.getText()+"', '" +
txtMemberName.getText() + "', '" + txtMemberdate.getText() + "',"+ 0 + "," + 0 + ","
+mtype+")"; intresult=st.executeUpdate(q);if(result==1) {
JOptionPane.showMessageDialog(this,"RecordhasbeenSaved.");txtClear();
}
else{
JOptionPane.showMessageDialog(this,"ProblemwhileSaving theRecord.");
}
}
catch(SQLExceptionsqlex){JOptionPane.showMessageDialog(this,"Error!!");}
}
}
if(obj==btnCancel){setVisible (false);dispose();
}
}
publicvoid focusGained(FocusEventfe){}publicvoidfocusLost(FocusEventfe){
if(txtMemberId.getText().equals("")){
}
else{
id=Integer.parseInt(txtMemberId.getText());longmemberNo;
booleanfound=false;try{
Stringq="SELECT*FROMMembersWHERE id="+id+"";ResultSetrs= st.executeQuery(q);
rs.next();
memberNo=rs.getLong("id");if(memberNo==id)
{ found=true;txtClear();
JOptionPane.showMessageDialog(this,id+ "isalreadyassigned.");
}
else
{
found= false;
}
}
catch(SQLExceptionsqlex){}
}
}
private void txtClear () {txtMemberId.setText ("");txtMemberName.setText
("");txtMemberpwd.setText ("");txtMemberId.requestFocus();
}
}
Dates.java
publicclassDates
{
intm,d,y;
publicDates(intmonth,intday, intyear)
{
m=month;d=day;y=year;
}
publicintgetMonth()
{returnm;}
publicintgetDay()
{ returnd;}
public intgetYear()
{returny;}
publicvoidsetMonth(intmonth)
{m=month;}
publicvoidsetDay(intday)
{d=day; }
publicvoidsetYear(intyear)
{y=year;}
publicStringtoString()
{
Strings=m+"/"+d+"/"+y;returns;
}
publiclongtoLong()
{
longdays=0;
switch(m)
{ case12:days+=3
0;
case11:days+=31;
case10:days+=30;
case9:days+=31;
case8:days+=31;
case7:days+=30;
case6:days+=31;
case5:days+=30;
case4:days+=31;
case3:days+=isLeapYear(y)?29:28;
case2:days+=31;
case1:days+=d-1;
}
if(y!=1900){
intinc=(1900-y)/Math.abs(1900-y);for(inti=y;i!=1900;i+=inc)
days+=(isLeapYear(i)?366:365);
}
returndays;
}
privatebooleanisLeapYear(inty)
{
if((y%100)==0)return(y%400)==0;elsereturn(y%4)==0;
}
publiclonggetDifference(Datesdate)
{returnMath.abs(toLong()-date.toLong());}
DeleteBook.java
importjava.awt.*;importjava.awt.event.*;import
javax.swing.*;importjava.sql.*;importjava.util.*;
publicclassDeleteBookextendsJInternalFrameimplementsActionListener,FocusListener{JPanelpBoo
k
=newJPanel();
JLabellbBookId,lbBookName,lbBookAuthor;JTextField txtBookId, txtBookName,
txtBookAuthor;JButtonbtnDel,
btnCancel; Statement st;ResultSetrs;
private longid=0,bisued;
publicDeleteBook(Connectioncon){
super("DeleteBook",false,true,false,true);setSize(325, 250);
lbBookId = new JLabel ("Book Id:");lbBookId.setForeground (Color.black);lbBookId.setBounds
(15, 15, 100, 20);lbBookName = new JLabel ("Book Name:");lbBookName.setForeground
(Color.black);lbBookName.setBounds (15, 45, 100, 20);lbBookAuthor=
newJLabel("BookAuthor:");lbBookAuthor.setForeground (Color.black);lbBookAuthor.setBounds
(15, 75, 100, 20);txtBookId=newJTextField();
txtBookId.setHorizontalAlignment(JTextField.RIGHT);txtBookId.addFocusListener(this);
txtBookId.setBounds (120, 15, 175, 25);txtBookName = new JTextField
();txtBookName.setEnabled (false);txtBookName.setBounds (120, 45, 175,
25);txtBookAuthor=new JTextField();txtBookAuthor.setEnabled
(false);txtBookAuthor.setBounds(120,75,175,25);btnDel = new JButton ("Delete
Book");btnDel.setBounds (25,175,125,25);btnDel.addActionListener(this); btnCancel = new
JButton ("Cancel");btnCancel.setBounds (165, 175, 125,
25);btnCancel.addActionListener (this);txtBookId.addKeyListener(newKeyAdapter()
{publicvoidkeyTyped(KeyEventke){ charc=ke.getKeyChar(); if(!
((Character.isDigit(c))||(c==KeyEvent.VK_BACK_SPACE))){getToolkit().beep();
ke.consume();
}
}
}
);
publicvoidactionPerformed(ActionEventae){Objectobj=ae.getSource();
if(obj==btnDel){
if (txtBookId.getText().equals ("")) {JOptionPane.showMessageDialog (this, "Book's Id not
Provided.");txtBookId.requestFocus ();
}
elseif(bisued!=0)
{ txtClear();
JOptionPane.showMessageDialog(this,"Bookheldbyamember"
);
}
else
{
}
}
private void txtClear () {txtBookId.setText ("");txtBookName.setText
("");txtBookAuthor.setText("");txtBookId.requestFocus();
}
}
DeleteMember.java
importjava.awt.*;importjava.awt.event.*;import javax.swing.*;importjava.sql.*;
publicclassDeleteMemberextendsJInternalFrameimplementsActionListener,FocusListener{privateJP
anelpMember =newJPanel();
privateJLabellbMemberId,lbMemberName,lbMemberCat;private JTextField
txtMemberId, txtMemberName,txtCat;privateJButtonbtnDel, btnCancel;
privateintdue;
privateStatementst; //StatementforGettingtheRequiredTable.privateResultSetrs; //For Getting the
Records From Table.private longid=0,heldBooks; //ToHoldtheMemberId.
//Constructor ofClass.
publicDeleteMember(Connectioncon)
{
//
super(Title,Resizable,Closable,Maximizable,Iconifiable)super("DeleteMember",false,true,false,true
);
setSize(350,222);
//SettingtheForm'sLabels.
lbMemberId = new JLabel ("Member Id:");lbMemberId.setForeground
(Color.black);lbMemberId.setBounds(15,15,100,20);lbMemberName=
newJLabel("MemberName:");lbMemberName.setForeground
(Color.black);lbMemberName.setBounds (15, 45, 100, 20);lbMemberCat = new
JLabel ("Category");lbMemberCat.setForeground(Color.black);
intreply=JOptionPane.showConfirmDialog(this,"AreyoureallywanttoDelete\
nthe"+txtBookName.get Text () + " Record?","LibrarySystem - Delete
Book",JOptionPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE);
if(reply==JOptionPane.YES_OPTION){try{
Stringq="DELETEFROMBooksWHEREBId="+id+"";txtClear();
JOptionPane.showMessageDialog(this,"BookDeleted.");ResultSetrs=
st.executeQuery(q);
}
catch(SQLExceptionsqlex){}
}
elseif(reply==JOptionPane.NO_OPTION){}
}
}
if(obj==btnCancel){setVisible (false);dispose();
}
}
publicvoid focusGained(FocusEventfe){}publicvoidfocusLost(FocusEventfe){
if(txtBookId.getText().equals("")){
}
else{
id= Integer.parseInt(txtBookId.getText());longbookNo;
booleanfound=false;try{ Stringq="SELECT*FROMBooksWHEREBId="+id+"";Result
Setrs= st.executeQuery(q); rs.next();
bookNo=rs.getLong("BId");bisued=rs.getLong("Mid");
if(bookNo== id){found=true;
txtBookId.setText(""+id);
txtBookName.setText ("" +
rs.getString
("BName"));txtBookAuthor.setText(""+rs.getString("BAuthor"));
}
else{
found= false;
}
}catch(SQLExceptionsqlex){if(found==false){
txtClear();
JOptionPane.showMessageDialog(this,"RecordnotFound.");
}
}
lbMemberCat.setBounds(15,75,110,20);txtMemberId=new JTextField();
txtMemberId.setHorizontalAlignment(JTextField.RIGHT);txtMemberId.addFocusListener(thi
s); txtMemberId .setBounds (125, 15, 200, 25);txtMemberName = new JTextField
();txtMemberName.setEnabled
(false);txtMemberName.setBounds(125,45,200,25);txtCat=new JTextField ();
txtCat.setEnabled(false);txtCat.setBounds (125, 75, 200,
25);btnDel=newJButton("DeleteMember");btnDel.setBounds (30, 145, 125,
25);btnDel.addActionListener (this);btnCancel = new JButton ("Cancel");btnCancel.setBounds
(185,
145, 125, 25);btnCancel.addActionListener(this);
//
RegisteringtheKeyListenertoRestrictusertotypeonlyNumericinNumericBoxes.txtMemberId.addKey
Listener(newKeyAdapter() {
publicvoidkeyTyped(KeyEventke){charc=ke.getKeyChar(); if(!
((Character.isDigit(c))||(c==KeyEvent.VK_BACK_SPACE))){getToolkit().beep();
ke.consume();
}
}
}
);
//AddingAlltheControlsinPanel.pMember.setLayout (null);pMember.add
(lbMemberId);pMember.add
(lbMemberName);pMember.add(lbMemberCat);pMember.add(txtCat);pMember.add
(txtMemberId);pMember.add (txtMemberName);pMember.add (btnDel);pMember.add(btnCancel);
//AddingPaneltoForm.
getContentPane().add(pMember,BorderLayout.CENTER);try
{ st=con.createStatement(); //CreatingStatementObject.
}
catch(SQLExceptionsqlex){
//
IfProblemthenShowtheUseraMessage.JOptionPane.showMessageDialog(null,"AProblemOc
cursWhileLoadingtheForm.");dispose(); //Closing theForm.
}
setVisible(true);
} publicvoidactionPerformed(ActionEventae){Objectobj=ae.getSource();
if(obj==btnDel){ //IfDeleteButtonPressed.if(txtMemberId.getText().equals(""))
{
JOptionPane.showMessageDialog(this,"Member's IdnotProvided.");txtMemberId.requestFocus ();
}
elseif(heldBooks!=0)
{
JOptionPane.showMessageDialog(this,"MemberHoldingBooks..Can'tDelete");txtClear();
}
elseif(due!=0)
{
JOptionPane.showMessageDialog(this,"MemberHoldingBooks..Can'tDelete");txtClear();
}
else
{
intreply=JOptionPane.showConfirmDialog(this,"DoyoureallywanttoDelete\
nthe"+txtMemberName.g etText () + " Record?","LibrarySystem - Delete
Member",JOptionPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE);
//ChecktheUserSelection.
if(reply==JOptionPane.YES_OPTION){ //IfUser'sChoiceYesthen.try{
//DELETEQuerytoDeletetheRecordfromTable.
String q = "DELETE FROM Members WHERE id = " + id + "";txtClear(); //Clearing the
TextFields.JOptionPane.showMessageDialog(this,"RecordhasbeenDeleted.");ResultSetrs
=st.executeQuery(q); //ExecutingtheQuery.
}
catch(SQLExceptionsqlex){System.out.println("problem");}
}
//IfUser'sChoiceNo thenDoNothingReturntoProgram.elseif(reply==JOptionPane.NO_OPTION){ }
}
}
if(obj==btnCancel){ //IfCancelButtonPressed Unload theFrom.setVisible(false);
dispose();
}
}
//OverRiddingtheFocusListenerClassFunction.public void focusGained (FocusEvent fe) {
}publicvoidfocusLost(FocusEventfe){
if(txtMemberId.getText().equals("")){ //IfTextField isEmpty.
}
else{
id = Integer.parseInt (txtMemberId.getText ());//Converting String to
Numeric.longmemberNo,memtype; //UseforComparingtheMember'sId.
booleanfound=false; //ToConfirmtheMember'sIdExistance.try{
//SELECTQuerytoRetrieved theRecord.
String q = "SELECT * FROM Members WHERE id = " + id + "";ResultSetrs =st.executeQuery(q);
//Executingthe Query.rs.next();
//MovingtowardstheRecord.memberNo=rs.getLong("id"); //Storing
the Record.heldBooks=rs.getLong("Bcnt");
due=rs.getInt(6);memtype=rs.getLong("Mcat");
if(memberNo==id) { //IfRecord Found thenDisplayRecords.found= true;
txtMemberId.setText(""+ id);
txtMemberName.setText(""+rs.getString("MName"));
ResultSetrs1=st.executeQuery("Select*FromMeCatwhereMcat="+memtype+"");rs1.next(
); txtCat.setText(""+rs1.getString("CName"));
}
else{
found= false;
}
}
catch(SQLExceptionsqlex){if(found==false){
txtClear(); //Clearing the
TextFields.JOptionPane.showMessageDialog(this,"RecordnotFound.");
}
}
}
}
//FunctionUsetoClearAlltheTextFieldsofForm.privatevoid txtClear (){
txtMemberId.setText ("");txtMemberName.setText
("");txtCat.setText("");txtMemberId.requestFocus();
}
}
IssueBook.java
importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;
importjava.util.Calendar;importjava.sql.*;
importjava.util.*;
publicclassIssueBookextendsJInternalFrameimplementsActionListener,FocusListener{privateJPan
el pBook=newJPanel();
privateJLabellbBookId,lbBookName,lbBookAuthor,lbBookCategory,lbMemberId,lbMemberName
,l bDate1,lbDate2;
privateJTextFieldtxtBookId,txtBookName,txtBookAuthor,txtBookCategory,txtMemberId,txtMemb
er Name,txtDate1,txtDate2;
privateJButtonbtnOk,btnCancel;privateStatementst;
privatelongid=0;privateintmemberId=0;
privateintid1,im,iy,vd,vm,vy;privateStringidate,vdate;
publicIssueBook(Connectioncon){
super("IssueBook",false,true,false,true);setSize(325,
340);
lbBookId = new JLabel ("Book Id:");lbBookId.setForeground (Color.black);lbBookId.setBounds
(15, 15, 100, 20);lbBookName = new JLabel ("Book Name:");lbBookName.setForeground
(Color.black);lbBookName.setBounds (15, 45, 100, 20);lbBookAuthor = new JLabel
("Book Author:");lbBookAuthor.setForeground (Color.black);lbBookAuthor.setBounds (15,
75, 100,
20);lbBookCategory=newJLabel("BookCategory:");lbBookCategory.setForeground
(Color.black);lbBookCategory.setBounds (15, 105, 100, 20);lbMemberId = new JLabel
("Member
Id:");lbMemberId.setForeground (Color.black);lbMemberId.setBounds (15, 135, 100,
20);lbMemberName = new JLabel ("Member Name:");lbMemberName.setForeground
(Color.black);lbMemberName.setBounds (15, 165, 100, 20);lbDate1 = new JLabel
("Issue Date:");lbDate1.setForeground (Color.black);lbDate1.setBounds (15,195,
100,20); lbDate2=newJLabel("ReturnDate:");
lbDate2.setForeground (Color.black);lbDate2.setBounds(15,225,100,20);txtBookId=new
JTextField();
txtBookId.setHorizontalAlignment(JTextField.RIGHT);txtBookId.addFocusListener(this);
txtBookId.setBounds (120, 15, 175,
25);txtBookName=newJTextField();txtBookName.setEnabled (false);txtBookName.setBounds
(120, 45, 175, 25);txtBookAuthor=new JTextField();txtBookAuthor.setEnabled
(false);txtBookAuthor.setBounds (120, 75, 175,
25);txtBookCategory = new JTextField ();txtBookCategory.setEnabled
(false);txtBookCategory.setBounds(120,105,175,25);txtMemberId=new JTextField ();
txtMemberId.setHorizontalAlignment(JTextField.RIGHT);txtMemberId.addFocusListen
er (this);txtMemberId.setBounds (120, 135, 175, 25);txtMemberName=newJTextField
();txtMemberName.setEnabled (false);txtMemberName.setBounds (120,165,175, 25);
txtDate1=new JTextField();txtDate1.setEnabled
(false);txtDate1.setBounds(120,195,175,25);txtDate1.setEditable(false);
txtDate2=new JTextField();txtDate2.setEnabled
(false);txtDate2.setBounds(120,225,175,25);txtDate2.setEditable(false);
btnOk = new JButton ("OK");btnOk.setBounds (50, 260, 100, 25);btnOk.addActionListener
(this);btnCancel = new JButton ("Cancel");btnCancel.setBounds(170,260,
100,25);btnCancel.addActionListener(this);
txtBookId.addKeyListener(newKeyAdapter(){publicvoidkeyTyped(KeyEventke){
charc= ke.getKeyChar(); if(!((Character.isDigit(c))||
(c==KeyEvent.VK_BACK_SPACE))){getToolkit().beep(); ke.consume();
}
}
}
);
txtMemberId.addKeyListener(newKeyAdapter(){publicvoidkeyTyped(KeyEventke)
{ charc= ke.getKeyChar(); if(!((Character.isDigit(c))||
(c==KeyEvent.VK_BACK_SPACE))){getToolkit().beep(); ke.consume();
}
}
}
);
if(obj==txtBookId){
if(txtBookId.getText().equals("")){
}
else{
id=Integer.parseInt(txtBookId.getText());longbookNo; booleanfound=false;try{
Stringq="SELECT*FROMBooksWHEREBId="+id+"";ResultSetrs=
st.executeQuery(q); rs.next();
bookNo=rs.getLong("BId");intmid=rs.getInt("Mid");
intbref=rs.getInt("BRef");if(bref==1)
{ txtClear();
JOptionPane.showMessageDialog(this,"RefBookCan'tBeIssued."
);
}
if(mid!=0)
{ txtClear();
JOptionPane.showMessageDialog(this,"BookAlreadyIssued")
;
}
if(bookNo== id){found=true;
txtBookId.setText(""+id);
txtBookName.setText ("" + rs.getString
("BName"));txtBookAuthor.setText(""+rs.getString("BAuthor"));txtBookCategory.setText(""+rs.g
et String("BCat"));
}
else{
found= false;
}
}
catch (SQLException sqlex) {if (found == false) {txtBookId.requestFocus ();txtBookId.setText
("");txtBookName.setText ("");txtBookAuthor.setText ("");txtBookCategory.setText("");
JOptionPane.showMessageDialog(this,"RecordnotFound.");
}
}
}
} elseif(obj==txtMemberId){
if(txtMemberId.getText().equals(""))
{
} else{
memberId=Integer.parseInt(txtMemberId.getText())
;
intmemberNo,memberDays,memberBooks,memberCat,heldBooks;booleanfind =false;
try{
Stringq="SELECT *FROMMembersWHEREid="+memberId+"";ResultSetrs= st.executeQuery(q);
rs.next();
memberNo =rs.getInt("id");if(memberNo==memberId){find=true;
memberCat=rs.getInt("MCat");heldBooks=rs.getInt("Bcnt");
txtMemberName.setText(""+rs.getString("MName"));rs.close();
ResultSetrs1=st.executeQuery("Select*fromMecatwhereMCat="+memberCat+"");rs1.next();
memberBooks=rs1.getInt("Blmt");memberDays=rs1.getInt("Dlmt");if(heldBooks==memberBook
s)
{
txtClear();
JOptionPane.showMessageDialog(this,"BookLimitReached");dispose(
);
}
GregorianCalendargcal=newGregorianCalendar();id1=
gcal.get(Calendar.DATE);im=(int)gcal.get(Calendar.MONTH)
+1;iy=gcal.get(Calendar.YEAR);vd=i d1+memberDays;
vm=im;vy=iy;
String xx,yy,zz;if(id1<10) {xx="0"+id1;
}
else
{
xx=""+id1;
}
}
else
{
yy= ""+im;
} idate=xx+"/"+yy+"/"+iy;while(vd>31){ if(im==1||
im==3||im==5||im==7||im==8||im==10||im==12)
{
if(vd>31){im=im+1;vd=vd-31;if(im>12){im=im-12;iy=iy+1;
}}}
if(im==4||im==6||im==9||im==11){if(vd>30){
im=im+1;vd=vd-30;if(im>12){im=im-12;iy=iy+1;}
}}
if(im==2){if(vd>28){im=im+1;vd=vd-28;if(im>12){im=im-12;iy=iy+1;
}}}
}
vdate=vd+"/"+im+"/"+iy;txtMemberId.setText(""+memberId);txtDate1.setText(idate);txtDate2.set
Te xt(vdate);
}
else{
find= false;
}
}
catch(SQLExceptionsqlex)
{ if(find==false)
{txtClear();
JOptionPane.showMessageDialog(this,"RecordnotFound.");
}
}
}
}
}
private void txtClear () {txtBookId.setText ("");txtBookName.setText ("");txtBookAuthor.setText
("");txtBookCategory.setText("");txtMemberId.setText ("");txtMemberName.setText
("");txtBookId.requestFocus();
}
}
LibrarySystem.java
importjava.awt.*;import java.awt.event.*;import
javax.swing.*;importjava.sql.*;importjava.util.*;importjava.text.*;importjava.io.
*;
publicclassLibrarySystemextendsJFrameimplements ActionListener
{
privateJDesktopPanedesktop= newJDesktopPane();JMenuBarbar;
JMenumnuFile,mnuEdit;
JMenuItemnewBook,newMember,printBook,printIssueBook;JMenuIte
m issueBook,returnBook,delBook,findBook;
privateJToolBartoolBar;
privateJButtonbtnNewBook,btnIssue,btnReturn,btnPrintIssue,btnDelBook,btnFindBook;privateJPa
ne l statusBar =newJPanel();
Connection con;Statement st;StringuserName;
publicLibrarySystem(inttype,intuser,Connectionconn)
{ super("LibraryManagementSystem.");
setIconImage(getToolkit().getImage("Images/Warehouse.png")
);
setSize (700, 550);setLocation((Toolkit.getDefaultToolkit().getScreenSize().width-
getWidth())/2,
(Toolkit.getDefaultToolkit().getScreenSize().height-
getHeight())/2);addWindowListener(newWindowAdapter()
{ publicvoidwindowClosing(WindowEventwe){
//quitApp();
}
}
);
bar=newJMenuBar();setJMenuBar(bar);
mnuFile = new JMenu ("File");mnuFile.setMnemonic ((int)'E');mnuEdit = new JMenu
("Edit");mnuEdit.setMnemonic((int)'E');
newBook=newJMenuItem("AddNewBook");
newBook.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,Event.CTRL_MASK));newB
oo k.setMnemonic((int)'N');
newBook.addActionListener(this);
newMember = new JMenuItem ("Add New
Member");newMember.setAccelerator
(KeyStroke.getKeyStroke(KeyEvent.VK_M,Event.CTRL_MASK));
newMember.setMnemonic ((int)'M');newMember.addActionListener
(this);issueBook=newJMenuItem("IssueBook");
issueBook.setAccelerator (KeyStroke.getKeyStroke(KeyEvent.VK_I,
Event.CTRL_MASK));issueBook.setMnemonic((int)'I');
issueBook.addActionListener(this);returnBook=newJMenuItem("ReturnBook"
); returnBook.setAccelerator (KeyStroke.getKeyStroke(KeyEvent.VK_R,
Event.CTRL_MASK));returnBook.setMnemonic((int)'R');
returnBook.addActionListener
(this);delBook=newJMenuItem("DeleteBook"); delBook.setAccelerator
(KeyStroke.getKeyStroke(KeyEvent.VK_D,
Event.CTRL_MASK));delBook.setMnemonic((int)'D');
delBook.addActionListener(this);
findBook=newJMenuItem("SearchBook");
findBook.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,Event.CTRL_MASK));findB
oo k.setMnemonic((int)'F');
findBook.addActionListener(this);mnuFile.add (newBook);mnuFile.add (newMember);mnuEdit.add
(issueBook);mnuEdit.add (returnBook);mnuEdit.addSeparator();mnuEdit.add(delBook);
mnuEdit.addSeparator();mnuEdit.add (findBook);bar.add (mnuFile);bar.add(mnuEdit);
btnNewBook=newJButton(newImageIcon("Images/NotePad.gif"));btnNewBook.setToolTipText("
A ddNewBook");
btnIssue=newJButton(newImageIcon("Images/Film.gif"));btnIssue.setToolTipText("IssueBook");
btnReturn=newJButton(newImageIcon("Images/Backup.gif"));btnReturn.setToolTipText("ReturnB
o ok");
btnDelBook=newJButton(newImageIcon("Images/Recycle.gif"));btnDelBook.setToolTipText("Del
et eBook");
btnFindBook= newJButton(newImageIcon("Images/Mirror.gif"));btnFindBook.setToolTipText
("Search Book");btnFindBook.addActionListener(this);
toolBar = new JToolBar ();toolBar.add(btnNewBook);toolBar.addSeparator ();toolBar.add
(btnIssue);toolBar.add (btnReturn);toolBar.addSeparator ();toolBar.add
(btnDelBook);toolBar.addSeparator ();toolBar.add
(btnFindBook);if(type==1)userName="Admin"; elseif(type==2)
{
}
elseif(type==3)
{
}
ReturnBook.java
import java.io.*;importjava.awt.*; import java.awt.event.*;import
javax.swing.*;importjava.util.Date;importjava.util.Calendar;importjava.util.*;
importjava.text.SimpleDateFormat;importjava.sql.*;
publicclassReturnBookextendsJInternalFrameimplementsActionListener,FocusListener{privateJPa
ne lpBook=newJPanel();
private JLabel lbBookId,
lbBookName,lbIssued;privateJTextFieldtxtBookId,
txtBookName,txtIssued;privateString urdate;
privateJButtonbtnReturn,btnCancel;private int id1,im,iy,vd,vm,vy,due;privateStatementst;
privateResultSetrs;private long id =
0;privateintmid,bc; publicReturnBook(Connectioncon)
{ super("ReturnBook", false,true, false,true);
setSize(325,250);
lbBookId = new JLabel ("Book Id:");lbBookId.setForeground (Color.black);lbBookId.setBounds
(15, 15, 100, 20);lbBookName=newJLabel("BookName:");lbBookName.setForeground
(Color.black);lbBookName.setBounds (15, 45, 100, 20);lbIssued = new JLabel ("Book Issued
To:");lbIssued.setForeground (Color.black);lbIssued.setBounds (15, 75, 100, 20);txtBookId=new
JTextField ();
txtBookId.setHorizontalAlignment(JTextField.RIGHT);txtBookId.addFocusListener(this);
txtBookId.setBounds (120, 15, 175, 25);txtBookName = new JTextField
();txtBookName.setEnabled (false);txtBookName.setBounds(120,45,175,25);txtIssued = new
JTextField ();txtIssued.setEnabled (false);txtIssued.setBounds (120, 75, 175, 25);btnReturn = new
JButton ("Return Book");btnReturn.setBounds (25, 175, 125, 25);btnReturn.addActionListener
(this);btnCancel = new JButton ("Cancel");btnCancel.setBounds (165, 175, 125,
25);btnCancel.addActionListener(this); txtBookId.addKeyListener(newKeyAdapter()
{publicvoidkeyTyped(KeyEventke){
charc= ke.getKeyChar(); if(!((Character.isDigit(c))||
(c==KeyEvent.VK_BACK_SPACE))){getToolkit().beep(); ke.consume();
}
}
}
);
pBook.setLayout (null);pBook.add (lbBookId);pBook.add (lbBookName);pBook.add
(lbIssued);pBook.add (txtBookId);pBook.add (txtBookName);pBook.add (txtIssued);pBook.add
(btnReturn);pBook.add(btnCancel);
getContentPane().add(pBook,BorderLayout.CENTER);
try{
st=con.createStatement();
} catch(SQLExceptionsqlex){
JOptionPane.showMessageDialog(null,"AProblemOccursWhileLoadingtheForm.");dispose(
);
} GregorianCalendargcal=newGregorianCalendar();id1=
gcal.get(Calendar.DATE);im=(int)gcal.get(Calendar.MONTH)
+1;iy=gcal.get(Calendar.YEAR); String xx,yy,zz;if(id1<10) {xx="0"+id1;
}else{
xx=""+id1;
}
if(im<10) {yy="0"+im;
}
else
{
yy= ""+im;
}
urdate=xx+"/"+yy+"/"+iy;setVisible(true);
}
publicvoidactionPerformed(ActionEventae)
{ Objectobj=ae.getSource();if(obj==btnRetur
n){ if(txtBookId.getText().equals(""))
{
JOptionPane.showMessageDialog(this,"Book'sIdnotProvided.");txtBookId.requestFocus ();
}
else {try{
intrd,rm,ry,urd,urm,ury,x;longv,v1,fine;
Datesd1,d2;bc--;
id=Integer.parseInt(txtBookId.getText())
;
ResultSetrs=st.executeQuery("select*fromBooksWHEREBId="+id+"");
//ExecutingtheQuery.rs.next();
Stringard=rs.getString("BReturn");System.out.println("came here 1");rs.close(); Stringsr=urdate;
StringTokenizerst2=newStringTokenizer(sr,"/");urd=Integer.parseInt(st2.nextToken());urm=Integer
.p arseInt(st2.nextToken());ury=Integer.parseInt(st2.nextToken());
d2=newDates(urm,urd,ury);
StringTokenizerst1=newStringTokenizer(ard,"/");rd=Integer.parseInt(st1.nextToken());rm=Integer.
pa rseInt(st1.nextToken());ry=Integer.parseInt(st1.nextToken());
d1=new Dates(rm,rd,ry);v= d1.toLong();
v1=d2.toLong();fine=v1-v;if(fine<=0)fine=0;
else
{
int reply = JOptionPane.showConfirmDialog (this, "Will you pay the Fine
ofRs."+fine+"now","FinePay", JOptionPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE);
if(reply==JOptionPane.YES_OPTION)
{}
elseif(reply==JOptionPane.NO_OPTION)
{
due+=fine;
}
}
x=st.executeUpdate("Update Books Set Mid ="+0+" WHERE Bid
="+id+"");x=st.executeUpdate("UpdateMembersSetBcnt="+bc+",Mbdues="+due+"WHEREid
="+mid+"");
JOptionPane.showMessageDialog(this,"BookReturned");txtClear();
catch (SQLException sqlex) {JOptionPane.showMessageDialog(this,"Problem");
}
}
}
if(obj==btnCancel){setVisible (false);dispose();
}
}
publicvoid focusGained(FocusEventfe){}publicvoidfocusLost(FocusEventfe){
if(txtBookId.getText().equals("")){
}
else{
id= Integer.parseInt(txtBookId.getText());longbookNo;
booleanfound=false;try{
ResultSetrs=st.executeQuery("Select*fromBookswhereBId="+id+""); //
ExecutingtheQuery. rs.next();
bookNo=rs.getLong("BId");if(bookNo==id) { found =
true;txtBookId.setText(""+id);
txtBookName.setText(""+rs.getString("BName"));mid=rs.getInt("Mid"
); if(mid==0)
{ JOptionPane.showMessageDialog(this,"NotanIssuedBook");dispose
();
}
else
{ ResultSetrs1=st.executeQuery("Select*fromMemberswhereid="+mid+"");rs1.nex
t(); txtIssued.setText(""+rs1.getString(3));bc=rs1.getInt("Bcnt");due=rs1.getInt(6);
}
}
else{
found= false;
}
}
catch(SQLExceptionsqlex){if(found==false){
txtClear();
JOptionPane.showMessageDialog(this,"RecordnotFound.");
}
}
}
}
private voidtxtClear(){
txtBookId.setText ("");txtBookName.setText("");txtIssued.setText ("");txtBookId.requestFocus();
}
}
SearchBook.java
importjava.awt.*;importjava.awt.event.*;import javax.swing.*;importjava.sql.*;
publicclassSearchBookextendsJInternalFrameimplementsActionListener{JPanelpBook=newJPanel(
); JLabel lbSearch;JRadioButton rb1,rb2,rb3,rb4;JTextFieldtxtSearch;
JButtonbtnFind,btnCancel;intflag=0;
Statementst;
Stringbname,bauthor,bcat,search;intbref,bmid,bid,rows=0;
JTable table;JScrollPane jsp;Object data1[][];Containerc;
publicSearchBook(Connectioncon){
super("SearchBooks",false,true,false, true);setSize(510,
300);
lbSearch = new JLabel ("Search Field");lbSearch.setForeground (Color.black);lbSearch.setBounds
(15, 15, 100, 20);txtSearch = new JTextField ();txtSearch.setBounds (120, 15, 175, 25);btnFind =
new JButton ("Find Book");btnFind.setBounds (25, 175, 125, 25);btnFind.addActionListener
(this);btnCancel = new JButton
("Cancel");btnCancel.setBounds(165,175,125,25);btnCancel.addActionListener (this);rb1=new
JRadioButton("By
Title");rb1.addActionListener(this);rb1.setBounds(15,45,100,20);rb2=newJRadioButton("ByAutho
r"
);
rb2.addActionListener(this);rb2.setBounds (15, 75, 100,
20);rb3=newJRadioButton("ByCategory");rb3.addActionListener(this);rb3.setBounds (15, 105,
100,
20);rb4=new JRadioButton("By
id");rb4.addActionListener(this);rb4.setBounds(15,135,100,20);pBook.setLayou
t
(null);pBook.add(lbSearch);pBook.add(txtSearch);pBook.add(btnFind);pBook.add(btnCancel);
ButtonGroupbg=newButtonGroup();bg.add(rb1);
bg.add(rb2);
bg.add(rb3);
bg.add(rb4);pBook.add(rb1);pBook.add(rb2);pBook.add(rb3);pBook.add(rb4);rb1.setSelected(true);
getContentPane().add(pBook,BorderLayout.CENTER);c=getContentPane();
try
{
st=con.createStatement();
}
catch(SQLExceptionsqlex){
JOptionPane.showMessageDialog(null,"AProblemOccursWhileLoadingForm.");dispose(
);
}
setVisible(true);
} publicvoidactionPerformed(ActionEventae)
{Objectobj=ae.getSource(); if(obj==btnFind){
if(txtSearch.getText().equals(""))
{JOptionPane.showMessageDialog(this,"SearchFieldnotProvided.")
;txtSearch.requestFocus ();
}
else
{ Stringbname1,bauthor1,bcat1;intnu
m;
booleanfound=false;try{
Stringq,bavl,bisr;
num=st.executeUpdate("Delete*fromBSearch");
ResultSetrs=st.executeQuery("SELECT*FROMBooks")
;
//ExecutingtheQuery.search=txtSearch.getText();
search=search.toLowerCase();while(rs.next())
{ bname=rs.getString(2);bauthor=rs.getString("BAuthor");bcat=rs.getString("BCat");bref=rs.getInt
("B Ref");if(bref==1)bisr="Yes";
else bisr="No";bmid=rs.getInt("Mid");if(bmid==0)bavl="Available";else bavl="Issued:"+
bmid;bid=rs.getInt("BId");
if(flag==0)
{
bname1=bname.toLowerCase();if(bname1.equals(search)||(bname1.indexOf(search)!=-1))
{ System.out.println("CameHere2");
num=st.executeUpdate("insertintoBSearchvalues("+bid+",'"+bname+"','"+bcat+"','"+bauthor+"','"+
ba vl+"','"+bisr+"')");
rows++;found=true;
}
}
elseif(flag==1)
{
bauthor1=bauthor.toLowerCase();if(bauthor1.equals(search)||(bauthor1.indexOf(search)!=-1))
{ num=st.executeUpdate("insertintoBSearchvalues("+bid+",'"+bname+"','"+bcat+"','"+bauthor+"','"
+ba vl+"', '"+bisr+"')");
rows++;found=true;
}
}
elseif(flag==2)
{ bcat1=bcat.toLowerCase();
if(bcat1.equals(search)||(bcat1.indexOf(search)!=-
1))
{ num=st.executeUpdate("insertintoBSearchvalues("+bid+",'"+bname+"','"+bcat+"','"+bauthor+"','"
+ba vl+"', '"+bisr+"')");
rows++;found=true;
}
}
elseif(flag==3)
{
if(bid==Integer.parseInt(txtSearch.getText()))
{ rows++;
num=st.executeUpdate("insertintoBSearchvalues("+bid+",'"+bname+"','"+bcat+"','"+bauthor+"','"+
ba vl+"','"+bisr+"')");
found=true;
}
}
}
} catch(SQLExceptionsqlex){if(found==false){
JOptionPane.showMessageDialog(this,"RecordnotFound.")
;
}
}
try{ data1=newObject[rows
][6];
Object[]Colheads={"BookId","BookName","Category","Author","Availability","Reference"};Resul
t
Setrs=st.executeQuery("Select*fromBSearch");
for(inti1=0;i1<rows;i1++)
{
rs.next();
for(intj1=0;j1<6;j1++)
{
data1[i1][j1]=rs.getString(j1+1);
}
} table=newJTable(data1,Colheads);
intv=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
inth=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;System.out.println("hai
we
camehere");
jsp=new JScrollPane(table,v,h);TableDisptd=newTableDisp(table);
catch(Exceptionsqlex){if(found==false){
JOptionPane.showMessageDialog(this,"SomeprobFound.")
;
}
}
}
}
if(obj==btnCancel){setVisible (false);dispose();
}
if(obj==rb1)
{
flag=0;
}
if(obj==rb2)
{
flag=1;
}
if(obj==rb3)
{
flag=2;
}
if(obj==rb4)
{
flag=3;
}
}
}
SearchMember.java
importjava.awt.*;importjava.awt.event.*;import javax.swing.*;importjava.sql.*;
publicclassSearchMemberextendsJInternalFrameimplementsActionListener
{
JPanelpBook=new JPanel();JLabellbSearch;JRadioButton
rb1,rb2;JTextFieldtxtSearch;
JButtonbtnFind,btnCancel;intflag=0,rows=0;Statementst;
Stringmname,mcat,search;
JTable table;Object data1[]
[];Containerc; intmid,bcnt;
publicSearchMember(Connectioncon)
{
super("SearchMembers",false,true, false,true);setSize(325, 250);
lbSearch = new JLabel ("Search Field");lbSearch.setForeground (Color.black);lbSearch.setBounds
(15, 15, 100, 20);txtSearch = new JTextField ();txtSearch.setBounds (120, 15, 175, 25);btnFind=
newJButton("FindMember");btnFind.setBounds (25, 175, 125, 25);btnFind.addActionListener
(this);btnCancel = new JButton ("Cancel");btnCancel.setBounds (165, 175, 125,
25);btnCancel.addActionListener (this);rb1=new JRadioButton("By
Id");rb1.addActionListener(this);rb1.setBounds(15,45,100,20);rb2=new JRadioButton("By
Name");rb2.addActionListener(this);rb2.setBounds (15, 75, 100, 20);pBook.setLayout
(null);pBook.add(lbSearch);pBook.add(txtSearch);pBook.add(btnFind);pBook.add(btnCancel
); ButtonGroupbg=newButtonGroup();bg.add(rb1);
bg.add(rb2);pBook.add(rb1);pBook.add(rb2);rb1.setSelected(true);
getContentPane().add(pBook,BorderLayout.CENTER);try
{
st=con.createStatement();
} catch(SQLExceptionsqlex){
JOptionPane.showMessageDialog(null,"AProblemOccursWhileLoadingForm.");dispose(
);
}
setVisible(true);
} publicvoidactionPerformed(ActionEventae)
{Objectobj=ae.getSource(); if(obj==btnFind){
if(txtSearch.getText().equals(""))
{JOptionPane.showMessageDialog(this,"SearchFieldnotProvided.")
;txtSearch.requestFocus ();
}
else
{
Stringmname1;
intnum,id,catid,bcnt1;boolean found = false;ResultSet rs,rs1,rs3;try{
Stringbavl,text,tts;num=st.executeUpdate("Delete*fromMSearch");if(flag==0)
{
id=Integer.parseInt(txtSearch.getText());rs=st.executeQuery("Select*fromMemberswhereid="+id+""
);rs.next();
bavl=rs.getString("Mname");catid=rs.getInt(7);bcnt=rs.getInt(5);
s1=st.executeQuery("Select*fromMeCatwhereMcat="+catid+"");rs1.next(
); mcat=rs1.getString("CName");bcnt1=rs1.getInt("Blmt");
rs3=st.executeQuery("Select*fromBookswhereMid="+id+"");
text="Name: "+bavl+"\n Category: "+mcat+"\n Books Held: "+bcnt+"\n Book Limit:"+bcnt1+"\n";
text+="Books Held:\n";while(rs3.next())
{
tts=rs3.getString(2);text+=tts+"\n";
}
JOptionPane.showMessageDialog(this,text);txtSearch.setText("");txtSearch.requestFocus(
);
}
else
{
search=txtSearch.getText();search=search.toLowerCase();
rs=st.executeQuery("Select*fromMembers");while(rs.next())
{
mname=rs.getString(3);mid=rs.getInt(1);bcnt=rs.getInt(5);catid=rs.getInt(7);if(flag==1)
{
mname1=mname.toLowerCase();if(mname1.equals(search)||(mname1.indexOf(search)!=-1))
{ rs1=st.executeQuery("Select*fromMeCatwhereMcat="+catid+"");rs1.next();
mcat=rs1.getString("CName");bcnt1=rs1.getInt("Blmt");
num=st.executeUpdate("insertintoMSearchvalues("+mid+",'"+mname+"',"+bcnt+",'"+mcat+"',"+bc
nt
1+")");
rows++;found=true;
}
}
}
} catch(SQLExceptionsqlex){if(found==false){
JOptionPane.showMessageDialog(this,"RecordnotFound.")
;
}
}if(flag==1){try{
data1=newObject[rows][5];
Object[]Colheads={"MemberId","Name","BooksHeld","Category","BookLimit"};ResultSetrs2=st.e
x ecuteQuery("Select*fromMSearch");
for(inti1=0;i1<rows;i1++)
{
rs2.next();
for(intj1=0;j1<5;j1++)
{
data1[i1][j1]=rs2.getString(j1+1);
}
} table=new
JTable(data1,Colheads);TableDisptd=newTableDisp(table);txtSearch.setText("");txtSearch.reques
tF ocus();
} catch(Exceptionsqlex){if(found==false){
JOptionPane.showMessageDialog(this,"SomeprobFound.")
;
}
}
}
}
}
if(obj==btnCancel){setVisible (false);dispose();
}
if(obj==rb1)
{
flag=0;
}
if(obj==rb2)
{
flag=1;
}
}
}
TableDisp.java
importjava.awt.*;importjavax.swing.*;
publicclassTableDispextendsJFrame
{
privateJPanelpBook=new JPanel();privateJScrollPane scroller;
privateJTabletable;publicTableDisp(JTablej)
{
super("Table Display");setSize(500,300);pBook.setLayout (null);table=j;
scroller = new JScrollPane (table);scroller.setBounds(20,50,460,200);pBook.add(scroller);
getContentPane().add(pBook,BorderLayout.CENTER);setVisible(true);} }