Download as pdf or txt
Download as pdf or txt
You are on page 1of 150

Integrated Library System

Farhad Taran

Supervisor: Dr. David Huang


Date:
School: Computer Science
Key Words: Application, Software, Library Management.

This report is submitted in partial fulfillment of the requirements for


the BSC (Hons) Computer Communications and Networks Degree at
the University of Westminster.
Acknowledgement
I would like to thank Dr David Huang and Dr David Lancaster for the guidance
and help that they have given me throughout this project.

i
Abstract
The Library Management system is a standalone application for assisting a librarian in
managing a small-scale book library. The System is designed to provide basic set of
features that enables a librarian to add/update members, add/update books, and manage
to check the availability of a book or the existence of books or members.

ii
List of Figures
FIGURE 1: GANTT CHART ................................................................................................. 5
FIGURE 2: ENTITY RELATIONSHIP DIAGRAM.................................................................. 13
FIGURE 3: UML CLASS DIAGRAM .................................................................................. 15
FIGURE 4: VIEW OF SCREEN DESIGN .............................................................................. 17

List of Tables
TABLE 1: PROJECT PLAN................................................................................................... 4
TABLE 2: DATA DICTIONARY ......................................................................................... 16
TABLE 3: TEST OBJECTIVES ............................................................................................ 53

iii
Table of Contents

ACKNOWLEDGEMENT............................................................................................... I
ABSTRACT.................................................................................................................... II
LIST OF FIGURES ......................................................................................................III
LIST OF TABLES ........................................................................................................III
CHAPTER 1: INTRODUCTION.................................................................................. 1
1.1 OVERVIEW ............................................................................................................. 1
1.2 OBJECTIVES ........................................................................................................... 2
1.3 TARGETED USERS .................................................................................................. 2
1.4 USER REQUIREMENTS ........................................................................................... 2
1.5 PROJECT SCOPE ..................................................................................................... 3
1.6 PROJECT PLANNING AND GRANT CHART ............................................................ 3
CHAPTER 2: LITERATURE REVIEW...................................................................... 6
2.1 PRIMARY STUDY .................................................................................................... 6
2.2 PROBLEM STATEMENT .......................................................................................... 9
CHAPTER 3: PROPOSED SOLUTION .................................................................... 10
3.1 WHY THE SYSTEM IS NEEDED? ........................................................................... 10
3.2 SYSTEM REQUIREMENTS .................................................................................... 10
3.3 WHY JAVA? ........................................................................................................ 11
3.4 WHY MICROSOFT ACCESS?................................................................................ 11
3.5 ENTITY RELATIONSHIP DIAGRAM ...................................................................... 12
3.6 UML CLASS DIAGRAM ....................................................................................... 14
3.7 DATA DICTIONARY .............................................................................................. 16
3.8 VIEW OF SCREEN DESIGN .................................................................................... 17
CHAPTER 4: IMPLEMENTATION OF THE APPLICATION............................. 18
4.1 LOGIN WINDOW FRAME ..................................................................................... 18
4.1.1 Closing the Log In Frame .............................................................................. 19
4.1.2 Setting the location of the LogIn screen......................................................... 19
4.1.3 The Database Connection.............................................................................. 20
4.1.4 Password Verification.................................................................................... 21
4.2 MAIN WINDOW FRAME ....................................................................................... 23
4.2.1 Graphical User Interface ............................................................................... 24
4.2.2 Toolbar........................................................................................................... 25
4.2.3 Date panel...................................................................................................... 26
4.2.4 Handling Action Events ................................................................................. 27
4.2.5 Preventing Duplicate Frames ........................................................................ 28
4.3 ADD NEW BOOK................................................................................................... 29
4.3.1 Creating the Internal Frames ........................................................................ 30
4.3.2 Automatic ID Creation................................................................................... 31
4.3.3 Saving New Records....................................................................................... 32
4.3.4 Information Log ............................................................................................. 32
iv
4.4 ADD MEMBER ....................................................................................................... 33
4.4.1 Date Formatting............................................................................................. 34
4.5 ISSUE BOOK .......................................................................................................... 35
4.6 RETURN BOOK ..................................................................................................... 37
4.7 UPDATE BOOK ..................................................................................................... 39
4.8 UPDATE MEMBER ................................................................................................ 40
4.10 DELETE MEMBER .............................................................................................. 42
4.11 CREATING THE REPORTS .................................................................................. 43
4.11.1 Loaned Books Report ................................................................................... 44
4.11.2 All Books Report .......................................................................................... 45
4.11.3 All Members Report ..................................................................................... 46
4.12 CREATING ADMIN ACCOUNTS .......................................................................... 47
4.12.1 KeyListener and KeyAdapter ....................................................................... 49
4.13 BACK UP OF THE DATABASE ............................................................................. 50
4.13.1 Back Up File Chooser.................................................................................. 51
4.13.2 Back Up Loop and Buffer............................................................................. 52
CHAPTER 5: SYSTEM TESTING............................................................................. 53
5.1 TEST PLAN ............................................................................................................ 53
5.2 SYSTEM TEST SCREENSHOTS .............................................................................. 54
5.2.1 Log In ............................................................................................................. 54
5.2.2 Main Window ................................................................................................. 54
5.2.3 Issue Book ...................................................................................................... 55
5.2.4 Return Book ................................................................................................... 56
5.2.5 Add Book........................................................................................................ 57
5.2.6 Add Member................................................................................................... 59
5.2.7 Update Book................................................................................................... 60
5.2.8 Update Member ............................................................................................. 61
5.2.9 Delete Book .................................................................................................... 62
5.2.10 Delete Member............................................................................................. 63
5.2.11 Loaned Books Report ................................................................................... 64
5.2.12 All Books Report .......................................................................................... 65
5.2.13 All Members Report ..................................................................................... 66
5.2.14 Add Admin Account...................................................................................... 67
5.2.15 Back Up Database ....................................................................................... 68
5.3 TEST CONCLUSION .............................................................................................. 69
CHAPTER 6: CONCLUSION..................................................................................... 70
6.1 PROJECT CONCLUSION ....................................................................................... 70
6.2 SYSTEM LIMITATIONS ......................................................................................... 71
6.3 FURTHER ENHANCEMENTS ................................................................................. 72
BIBLIOGRAPHY ......................................................................................................... 73
APPENDIX A: PROJECT PROPOSAL REPORT.................................................. 74
APPENDIX B: PROGRAM SOURCE CODE........................................................... 80

v
Chapter 1: INTRODUCTION

1.1 Overview

In current days libraries are a collection of information resources and services that are
organized for use, and maintained by a public body or institution. And With the
collection of media other than books for storing information, many libraries are now also
repositories and access points for maps, prints or other documents because of this the
process of managing a library has become very complex.

With the age of computers new software solutions have been created that aim to aid
libraries in managing their operations. These software solutions are called integrated
library systems. An integrated library system is an application written in a programming
language, which uses a database that is integrated with the main application to store data
entered by the user. As the main focus point of a library is to keep track of books and
members databases are a great tool as they can be used to organize data to a great extent,
which is the main point of a track and trace system. Integrated library management
software can cut on operation costs of a library and can be very beneficial if they are
designed and created with regards to the right requirements.

The system created by me is a system that can manage all processes that are crucial to
the management of a small-scale library. Book transactions including book registration,
member registration, book issuing, current status of a particular book etc. can be handled
very easily by this system. The other beneficial aspect of my system is that the interfaces
are designed in a way that makes the application easy to manage and learn.

There is some check up features embedded in the system that inform the librarian if a
book is already issued or if a member with the same Id number exists in the database.
This prevents user-generated errors. Overall the application provides enough features
that are capable of handling the operations within a small-scale library, and this is what
it was intended for as stated in the project proposal.

1
1.2 Objectives
There are several objectives for this project:

1. To research the process of book keeping in a library.


2. To research other available Library Management Systems.
3. To research the technologies used to implement the system.
4. To Design an application with regards to achieved knowledge during the
research phase.
5. To design an efficient system.
6. To implement the application.

1.3 Targeted Users


The following are the targeted users:

1. Small scale or independent libraries.


2. The librarians and the library staff.

1.4 User Requirements

The following are the user requirements:

1. Create Administrator Accounts. 12. All Books Report.

2. Add New Books. 13. Back Up Database.

3. Add New Members.

4. Update Book Details.

5. Update Member Details.

6. Delete Books.

7. Delete Members.

8. Issue Books.

9. Return Books.

10. Loaned Books Report.

11. All Members Report.

2
1.5 Project Scope

This system should work in a library that has a small-scale operation such as
a youth center or a book club or any independent library. The main user of
the system would be the library staff.

The primary scope of this project is to create a system, which has the basic
features needed to manage a library. The application should enable the
librarian to manage the library in an easy way. The librarian will be able to
add/update books and members.

There should be preventative feature embedded in the system that disallows


the user from entering duplicate records.

The Librarian should also have a better and clearer view about the library
books. The system design and the layout of the application should provide
the user an interface, which is easy to use and manage.

1.6 Project Planning and Grant Chart

An important factor of project development is Milestones. The milestones are important


checkpoints or goals for a project. Milestones are used to catch scheduling problems
early.

The plan should be flexible and be updated on regular basis. It also helps to identify risk
areas for the project, for example things we don’t know how to do, but we have to learn.
These are risky, as we don’t know how long it will take. We must have a good sense for
how long the task will take.

Based on above discussion the project was divided into different tasks. And a project
plan (figure 1.1) and a Gantt chart (figure1.2) were developed which are displayed in the
following pages.

3
Table 1: Project Plan

4
Figure 1: Gantt Chart

5
Chapter 2: Literature Review

2.1 Primary Study

It would be a very time taking and costly operation if one wanted to attempt to manage a
library without the presence of a computerized system. The maintenance of books,
members, magazines etc. is very hectic, tedious, time taking and involves a large
amount of paper work. It is a very difficult process and it takes lots of man-hours. Along
with this there are a lot of other works in a library like classifications of books,
cataloging etc, which are very slow processes.

First when a book is purchased, the book’s details are entered in the register. The
various entries that are entered in the register are book title, name, publisher, edition,
number of copies, price etc. After that the book is categorized in different categories like
Science, art, history, mathematics etc. At last the books are catalogued and then it’s
allowed to be issued.

When a member comes to the librarian for issuing the book, he has to show his library
card along with his identity card. If the card is valid then only he/she may be allowed to
select a book. On selection of a book he has to again go to the librarian. The librarian
will enter the book details on register and also on the library card and librarian has to
mention the return date on both the card and his/her register. When a member returns
the book, the librarian cuts the entry of returned book on the library register as well as
on the member’s library card. If there is any fine to be imposed on any member it should
be calculated and collected.

Now if a librarian has to view the book statistics in order to find out the current status of
a book, he has to open all the registers and has to search for a particular book record.
Similarly if he wants to view the borrower statistics again he needs to open all the
registers and has to do the hectic work again and again.

If a book is missing or is not returned by a member on time, the librarian would not
know unless he searches entire records for return dates.

By now it should be obvious or understandable that manual keeping of library is very


tedious and time-consuming process.

There are many companies that provide the libraries with library management systems,
and also provide maintenance and training for the library staff. This is usually the case
6
where a library operates on a large scale, has other branches that need to connect to
through Internet servers and has thousands of books, patrons and records to store. These
types of projects are very costly and require a large amount of time, work force and
budget.

A research was done on some of the existing Library Management systems in order to
find out the current standards of such applications. Below are the specifications of some
of the current library management systems:

a) “HCL Smart Library Management System: It has been designed to manage


automate and look after the overall processes of a library. It is capable of managing
Book Issues and returns, Newspaper subscriptions, calculating and managing fine,
and it can generate various reports for Records.

HCL Library Management System efficiently manages libraries, provides


convenience and ease of use to the users as well as librarians. Some of the features
are:

• Application login through smart cards.

• Enables smart library for Cataloging and circulation of materials.

• Centralized database.

• User identification through their smart cards.

• Theft identification

• Statistics and reporting.

• Web Based module” 1

1
Singh, C; “HCL Smart Library Management System”; HCL Infosystems Ltd

14/5/2008 www.hclinfosystems.in/smart-Libry.pdf; (Accessed 29/10/2008)

7
b) “BBSPL Library Management System: its is a system designed to manage the over-
all processing of small or very large-scale libraries. It is capable of managing Book
Issues and Returns, Magazine or Newspaper Subscription, Calculating and
Managing fines and Balances of payments due from Members, and it can generate
various Reports for review or record keeping purposes, with accordance to end user
requirements.

This software is Bar Code enabled and bar code generation and printing is built into
this software. Use of Bar Codes eases the everyday tasks of big Libraries, where
there are several thousand transactions to track. Furthermore the software would be
able to work without the use of barcodes seamlessly. Some of the features are:

• Book and Member records management with the optional help of barcodes

• Customizable Fine Settings for various Categories of Members (Fine per


day/Book) return period etc.

• Membership Subscription period management.

• Member’s Fine Balance management facility.

• Powerful Search Facility for Book and Member Search based on various
Search Criteria.

• Barring of Book issues to Book and/or Fine Defaulters.

• Comprehensive fields for books and members record to suit all


requirements.

• Magazine/Newspaper Subscription management facility.

• Multiple Library Location setup feature.

• Book-Reservation facility” 2

2
Big Byte Solutions (P) Ltd; Library Management System Version 2.3

2005 http://www.bbspl.com/librarysoftwarefeature.htm (Accessed 29/10/2008)

8
2.2 Problem Statement

The problem with the Manual Library management system is that it is not efficient and
its time taking. In Manual Library management librarians have to keep records on paper.
Paper records have many drawbacks; they are incomplete, torn, misplaced or lost. They
also require a lot of space in addition it will require a lot of effort and time from
librarians. New members have to fill membership forms and they are provided with
member Ids. Fast report generation is not possible, tracing a book is difficult,
information about issue/return of books are not properly maintained, no central database
can be created as information is not available in a database.

9
Chapter 3: Proposed Solution

3.1 Why the system is needed?

To the above problem stated, the system is needed to make the processing and managing
of books easier.

The library management system would be an application created using the java
language. This application would use the java database connection to interact with a
database, which is located on the local workstation.

The database would be created in Microsoft access and any records that need to be
saved on this database are first entered into the java interface of the application.

Because the records are saved into a database, which is separated from the java
application, a back up function is made possible, as it is easy to back up a database on a
regular basis.

3.2 System Requirements

Minimum requirements for running the system are as follows:

Summary of requirements:

 Hardware Requirements:

Pentium II or higher

128 MB RAM(minimum) or higher

500MB hard disk space

Screen resolution (various resolutions)

 Software Requirements:

Microsoft Access

Java 1.6

10
3.3 Why JAVA?

Java is a powerful Object oriented programming language. It supports reusability,


polymorphism, encapsulation and abstractions etc. java was originally designed to be
used for network programming and java virtual machine provides a reliable, secure and
easy way for making future enhancements to the system such as adding online
capabilities. Java also has the two Swing and Abstract Window Toolkit libraries, which
allow the programmer to create efficient graphical User interfaces. The other
contributing factor in choosing java for this project was the Java Database Connectivity
feature, which can be used to create and maintain a connection between the application
and a database. Through this connection the programmer can write SQL scripts that
manipulate the data, which in this case is the members and books records through the
application interface and without any direct interaction between the user and the
database. This is essential for data security and integrity.

3.4 Why Microsoft Access?

It is a strong database system for storing and managing records. It is a relational


database, which is an information system that presents information as rows contained in
a collection of tables, each table possessing a set of one or more columns. Microsoft
Access provides a simple wizard feature that can be used to easily create different
tables, which would hold the records for this system. Using java database connection it
can be integrated with the java library software, enabling the manipulation of data
through the java application.

11
3.5 Entity Relationship diagram

The entity relationship diagram on the next page is to show the relationship between
different Entities in the library management system, and how data from different objects
relate to each other.

In this system the primary key Member_Id would be used to uniquely identify members.

The primary key Book_Id uniquely identifies books and it also is used to create unique
records of issued books in the Loaned table.

Any time a book is burrowed or returned by a member a record is either inserted or


deleted from the loaned table.

Admins are the users of the system and are responsible for managing the creation of
other admin accounts, member records, book records, database back ups. They also
manage book circulation, which effectively is the process of issuing and returning of
books.

One member can issue or return one to many books.

12
Figure 2: Entity Relationship Diagram

13
3.6 UML Class Diagram
The UML class diagram on the next page shows that the LogIn window and the main
window are separate and independent frames because they inherit the properties of
JFrame. On the other hand all the other windows inherit from JInternalFrame, which
means that they will appear inside the mainwindow frame.

Since having multiple instances of the same internal frames can consume processing
power and slow the system down, the relationships for all the internal frames is set to
0…1 meaning that either 0 or 1 instance of each internal frame can appear inside the
main window. To prevent the creation of multiple instances of a an internal frame a loop
was used which is activated before an instance of an internal frame is created and checks
to see if that frame is currently open, if the frame already exist in the mainwindow and is
hidden behind other internal frame then it is simply brought forward, if not then a new
instant of the internal frame is created. this prevention mechanism is explained in detail
and can be found in 4.2.5 Preventing Duplicate Frames,on page 29.

14
Figure 3: UML Class Diagram

15
3.7 Data Dictionary

All the attributes have the option required set in the database, just incase a technician
wants to add records directly into the database, but validity checks are done first within
the java interface at the point of data entry. If the librarian has not entered one of the
following the source code would inform the librarian of this and would not allow the
record to be saved in the database. The Loaned table is used to create reports that show
which books are currently loaned and out of the library.

Table 2: Data Dictionary

Table Attribute Name Type Required PK or


FK
Admins
Id Number Yes PK
Password Text Yes
Books
Book_Id Number Yes PK
Book_Name Text Yes
Book_Author Text Yes
Member_Id Number Yes
Issue_Date Text Yes
Return_Date Text Yes
Members
Member_Id Number Yes PK

Member_Name Text Yes

Registration Text Yes


_Date
Book Count Number Yes
Loaned
Book_Id Number Yes PK
Book_Name Text Yes
Member_Id Number Yes
Member_Name Text Yes
Issue_Date Text Yes
Status Text Yes

16
3.8 View of Screen design

Librarian will login through the LogIn window and a new window called the MainWindow will appear. In the Main Window they may select different
options like add, delete, update, issue etc. by selecting any of these option the JInternalFrame relating to the option will appear inside the MainWindow.

Figure 4: View of Screen Design

17
Chapter 4: Implementation Of The Application

4.1 LogIn Window Frame

This is the login screen. This is the first screen that appears when the librarian starts the
system. On entering Login username and password correctly the user will be directed to
the main window of the system. If the librarian enters the wrong information the
following message will appear “Incorrect LogIn Information”. For security reasons, this
is the best message for this purpose, as it does not hint on the correctness of ID or the
password. On entering the correct login information the main window that provides all
the interfaces for interacting with the software will appear.

18
4.1.1 Closing the Log In Frame

Librarian can close the system by clicking on the close or cancel button. This is made
possible by using the following code. It is a short version of an event handler and it can
be used to close a window. Exit on close means the system or virtual machine will be
stopped if the user clicks on the X or close icon of the frame.

this.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );

4.1.2 Setting the location of the LogIn screen

In order to make the application compatible with different screen resolutions


the following code was written. To set the location of the login window on
the users screen the following code was used.

public Dimension dimension =


Toolkit.getDefaultToolkit().getScreenSize();

It Obtains the screen size in pixels using getScreenSize which is a method belonging to
the toolkit class. It stores the value in the Dimension object, which is capable of holding
a component’s width and height.

The log on window can be made to appear in the center of the user’s screen using the
following code.

setLocation (dimension.width / 2 - getWidth() / 2,


dimension.height / 2 - getHeight() / 2);

As specified earlier Dimension holds the screen size. dimension.width/2 places the
pointer in exactly the middle of the screen. getwidth()/2 represents the amount of space
the log in window takes to the right and left of the center of the screen, which is obtained
in dimension.width/2. If this amount is subtracted from the width of the screen size we
calculate the exact amount of space that the log in from takes to the right and left side of
the center of the screen. By doing this the log in window will be placed in the middle of
the screen, but this is the calculation for the horizontal position of the window and the
same calculation is done for its vertical position.

19
4.1.3 The Database Connection

It is created when the LogIn.java class is loaded By using Class.forName() It loads the
appropriate driver class with the Driver class name as an argument. The most common
driver that is used is the JdbcOdbcDriver.

try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");

Here the location of the database is specified. The system would not use a database
hosted by a server but a database, which is located on the local machine. This is
achieved by using the Windows ODBC data source administrator.

String loc = "jdbc:odbc:Library";

Here getConnection method is used to establish a new connection with the data source.

Connect = DriverManager.getConnection (loc); }

If the driver cannot be found or loaded the following exception will be thrown and
caught using the following lines.

Catch (ClassNotFoundException cnf) {

JOptionPane.showMessageDialog (null,cnf.getMessage());
System.exit (0);

The following code catches the SQLException, which is thrown when there is an error
associated with accessing the database. After the error is thrown the appropriate thing is
for the system to stop, and this is done by using system.exit(0);.

catch (SQLException sqlex) {

JOptionPane.showMessageDialog (null, sqlex.getMessage());

System.exit (0); }

20
4.1.4 Password Verification

The password verification process is done through the LogIn screen. In the database a
table named Admins exists. This table contains two fields one is called ID and the other
is called Password. These two fields would contain the information required for logging
into the system. The following code will perform a query through using the JDBC and
compare the information held in these two fields with the information entered by the
user through the login window, which was created earlier.

The following is an SQL statement, which would select a row from the Admins table
where the ID field equals the username entered by the user. Since the user names are ID
numbers and are stored in the database as integers so the session user or user ID obtained
from the textfield as a string has to be converted to integer using parseInt.

try { String query = "SELECT * FROM " + "Admins" + " WHERE


ID = " + Integer.parseInt(sessionUser);

The following code creates a statement object, which is needed for executing SQL
queries. The statement object is like a bridge between the database and the results that
are returned after an SQL statement is executed.

Statement st = Connect.createStatement ();

The following code creates a resultset. This provides interface for retrieving and
manipulating results that are returned after a query is executed. The executeQuery
method will execute the query that was created earlier. This query will be passed as a
string to the database and if there are no errors the database will execute the query and
the result set object will be returned by the executeQuery method.

ResultSet rs = st.executeQuery (query);

After a query is executed the result of that query is returned in a row. To access these
rows of data the resultset uses a cursor. When a result set is created this cursor is not
pointing at a row. So here after the query has been executed I used rs.next to point at the
first row returned by the query.

rs.next();

21
If the query executed were successful, then it would mean that the ID entered by the
admin does exist in the Admins table, so the password which is saved in the database
along with that particular ID is retrieved and Here I set the string variable databasePass
to take the value of that Password in the database.

databasePass = rs.getString ("Password");

The password retrieved from the database is compared to the password entered by the
admin.

if (sessionPass.equals (databasePass)) {

The specifications and coding of the main window of the program that has the entire
interface for managing the library system is held in the MainWindow.java file. By using
the new keyword a new instance of the MainWindow object is created. The database
connection along with the Admins password and user ID which were used to log in to
the current session are passed on to the main window process. These variables will be
used for verification purposes in the database back up and creation of admin accounts
procedures.

new MainWindow (Con,sessionPass,sessionUser);

Then the log in window will be disposed of but system.exit(0); will not be used here
because the virtual machine needs to be running for the Main window and the other
processes that are to be started by the admin.

setVisible (false);

dispose(); }

If the user ID entered by the admin does not exist in the database, an SQLException
regarding invalid cursor state is thrown and caught, but instead of viewing the exception
message user is informed that the login information is incorrect.

log.setText("Incorrect LogIn Information");

22
4.2 Main Window Frame

After the password check has been done in the login window and after permission has
been granted to user to be able to use the features of the library system the above
window would appear on the user’s screen. This would be the main window of the
system and it is from here that all the features of the system are accessible.

The user may select different options either by clicking on the appropriate buttons or
through the toolbar.

The options available to the user are Issue book, Return book, Add new book, Add new
member, Update Book, Update Member, Delete book, Delete member, Loaned Books
Report, All Books Report, All Members Report, Add a New Admin, and Back Up
Database.

23
4.2.1 Graphical User Interface

To create the user interface, first a desktop pane had to be created. The desktop pane is
the main window of the system. It works as a container and all the other internal frames
are contained within its borders. The code that I used to create the desktop pane is shown
below.

private JDesktopPane mainWindow = new JDesktopPane ();

the next step was to create the menu bar. The menu bar is where the system menus are
placed. The code for creating a menu bar is shown below.

private JMenuBar bar;

to create the menu bar object the following code had to be placed in the Class body.

bar = new JMenuBar (); setJMenuBar (bar);

To declare the menus that will be placed in the menu bar I used the following code.

Private Menu file Menu, edit Menu, option Menu;

A menu bar holds system menus like file edit and help, but these menus also hold items,
which have to be declared too. The following is how I declared the items that will be
within the individual menus.

private JMenuItem addBook, newMember, end;

private JMenuItem issueBook, returnBook, delBook;

the menus objects then were created and this was done in the following manner.

mnuFile = new JMenu ("File");

After the creation of the menu items, it was time to add each menu item to their
appropriate menu. the following is an example of the code used To add a menu item to a
menu.

mnuFile.add (addBook);

24
4.2.2 Toolbar

The toolbar in this application would contain buttons and icons, which would provide
the user with an easier way to perform certain actions. For example the user can click on
the add new member button and view the form associated with it rather than browse
through the menu file which I created earlier and click on the option contained in there.
The following code declares a toolbar.

Private JToolBar toolBar;

Next was the declaration of the buttons, which will be placed inside the toolbar by using
the following code.

private JButton btnaddBook, btnNewMember, btnIssue;

Then for each of the declared buttons an object had to be created. In the following code I
have created a button for adding a new book and assigned an image to it. I also have
assigned a tool tip to it. A tool tip is a small pop up window that will tell the user what a
certain button does if the mouse pointer is placed and held on top of the button.

I have added an action listener to the button so when the button is clicked I can later use
the event created by the action to perform the opening of the appropriate form. The same
code has been written for all declared buttons.

btnaddBook = new JButton (new ImageIcon


("Images/addBook.gif"));

btnaddBook.setToolTipText ("Add New Book");

btnaddBook.addActionListener (this);

To create the toolbar I used the following code.

toolBar = new JToolBar ();

And then I added all the buttons that I created earlier to the toolbar. I also used a
separator to put a small space between these buttons.

toolBar.add (btnaddBook);

toolBar.add (btnNewMember);

toolBar.addSeparator ();

25
4.2.3 Date panel

I created a panel, which would hold the current date and placed it at the bottom of the
mainWindow frame. First I had to declare these items. statusBar is the panel that holds
the Date label.

private JPanel statusBar = new JPanel ();

To view the date and time , first the current time is obtained through the java Date utility
package.

private java.util.Date currentDate= new java.util.Date ();

Then a date format was created which enables us to change the format of the date. the
following creates a date format object.

private SimpleDateFormat sdf = new SimpleDateFormat ("dd


MMMM yyyy");

then I created a string, which would hold the actual date and formatted it by using the
date format I created earlier.

private String todayDate = sdf.format (currentDate);

To set the location of the statusBar BorderLayout was used. When adding a component
to a container with a border layout, we need to use one of the five constants, NORTH,
WEST, CENTER and SOUTH to set the location of the components.

lbDate= new JLabel (todayDate);

statusBar.setLayout (new BorderLayout());

statusBar.add (lbDate, BorderLayout.EAST);

26
4.2.4 Handling Action Events

After an action is performed and an event is created using the following method the
source of the event is identified and the appropriate window will be opened. First an
object is created and it would take the value of the object that has had an event occurred
on it. The object, which has had an event occur on it, is obtained by using getSource. At
this point a comparison is made to check if the object is any of the two triggers for
opening a JInternalFrame. The events that can trigger a JInternalFrame to open up are
the menus and the buttons. Any object that can trigger the opening of a form belongs to
one of these groups. before opening an instance of a JInternalFrame first the
isFrameOpen method is used to see if an instance of the window chosen by the user is
already open and running. This prevents the creation and viewing of multiple frames on
the desktop.

public void actionPerformed (ActionEvent ae) {

Object obj = ae.getSource();

if (obj == addBook || obj == btnaddBook) {

boolean b = isFrameOpen ("Add New Book");

if (b == false) {

AddBook adBook = new AddBook (con);

Desktop.add (adBook);

adBook.show ();}

If the Boolean is true, it means that the window is already open and there is no need for a
duplicate of the same window to be created and made visible. A duplicate window that
appears on the screen can consume unnecessary system resources, confuse the user and
cause human errors during the information entry. if the Boolean check was false then a
connection is made to the appropriate class and database and the form is made visible.
The same code was written for all the other windows and works the same way by
checking first to see if the window is already open.

27
4.2.5 Preventing Duplicate Frames

If a user selects an option like adding a member by clicking on the add member button
then the corresponding window has to be made visible so that the user can enter the
details of the new member. But if the user clicks on the add member button multiple
times then multiple copies of the same window will be made visible. This is not
appropriate as it would create clutter on the desktop pane and also it consumes the
processing power and results in a slow and unsatisfactory system.

In order to prevent the occurrence of duplicate windows, the following method was
created to check and see if an internal frame is already open. If the frame is already open
then there is no need to contruct another instance of the same frame, but if it is not then a
new instance of the frame is needed.

First the name of the window is passed to the method through the string parameter. An
array of internal frames is created to hold all the internal frames that are currently open
and visible. The length of the array is obtained using the length keyword; this is done so
we know when to stop the loop. A for-loop goes through the array one by one and a
comparison is done on each internal frame’s title. The titles of the internal frames are
compared to the title of the internal frame that the user has requested to be opened. If the
title of the window that is currently being reviewed in the array is equal to the title of the
window that the user has requested then the method returns a true Boolean value which
means the window is already open and there is no need to create a duplicate of the
window, if not the returned Boolean value would be false which indicates that the
window in question is not currently open and a new window will be created and made
visible.

private boolean isFrameOpen (String title) {

JInternalFrame[] allInternalFrames =
mainWindow.getAllFrames ();

for (int i = 0; i < allInternalFrames.length; i++) {

if (allInternalFrames[i].getTitle().equalsIgnoreCase

(title)) { allInternalFrames[i].toFront();

return true;} }

return false; } }

28
4.3 Add New Book

This is the screen for adding new books to the library. The new Book’s Id is assigned
automatically and is set this way to disallow creation of duplicate records.

txtBookId is a Jtextfield that holds the new records Book Id. It has a focuslistenere
attached to it. So when the focus event is created by clicking on this Jtextfield the
automatic creation piece of code, which exists in the focusGained interface of focus
listener, is executed and a new unique id is generated for the new book entry.

29
4.3.1 Creating the Internal Frames

AddBook inherits the properties of the JInternalFrame class and it implements the
interfaces of the ActionListener, FocusListener and KeyListener classes.

public class AddBook extends JInternalFrame implements


ActionListener, FocusListener, KeyListener {

The super keyword can be used to invoke a superclass’s constructor. Here the AddBook
class extends JInternalFrame, which means that it inherits the properties of the
JInternalFrame class this means that the AddBook window will appear inside the
MainWindow, which was declared as a desktop pane. By using super I can call the
JInternalFrame constructor and construct the frame or window for the AddBook
interface.

The ActionListener interface provides the actionperformed method, which enables


handling of the action events created by the pressing of the buttons in this system.

The Focuslistener methods allow this system to execute certain codes when the focus is
gained or shifted from Id textfields which have had focus listeners set to them and these
fields uniqly identify book or member records in the database.

The KeyListener interface has been used in this system to prevent users from entering
non digit characters into the member or book Id fields.the details of the Keylistener
implementation in this system can be found in 4.12.1 KeyListener and KeyAdapter on
page 49.

Here super is used to invoke the JInternalFrame constructor. The first parameter is the
name of the frame, which would be visible on the top left corner of the frame. The
second parameter is a Boolean value, which determines if the frame is resizable. The
Boolean is set to false here so the user cannot drag the corner of the frame and resize it.
The third parameter is the closable Boolean, here it is set to true so the frame can be
closed by the user. The fourth parameter is set to false which means the window cannot
be maximized to occupy the whole screen. The fifth and the last parameter is set to true
which means that the window is iconifiable. This means that the window can be
minimized to the bottom of the screen to be represented by an icon.

super ("Add New Book", false, true, false, true);

30
4.3.2 Automatic ID Creation

The ID is assigned automatically for each new record in order to prevent duplicate
records and minimizes human errors.

A ResultSet called getRowCount will obtain the rows available in the Books table.

public void focusGained (FocusEvent fe) { try{

ResultSet getRowCount = st.executeQuery("SELECT * FROM


Books");

While there are still rows in the resultset getrowcount and while the cursor can still
move toward the next record in this resultset, the value in the first column of each row
which is a book ID is obtained and held in row count.

while (getRowCount.next()) {

rowcount = getRowCount.getInt(1);

when there are no more rows in the resultset then the while loop stops. And this means
that the rowcount holds the id of the last book in the database. So it is incremented by
one to be the new Books ID.

rowcount++;

newBookId = Integer.toString(rowcount);

txtBookId.setText(newBookId);

} catch (SQLException
sqlex){log.setText(sqlex.getMessage()); }}

31
4.3.3 Saving New Records

To save the record of the new book into the database, the exexuteUpdate function of the
JDBC is used. The following code inserts the values of the new book record into the
books table. Since the record is for a new book, which has not yet been issued, a
customized date format, is also used which would be inserted into the issue and return
date fields of the book record.

int x = 0;

String s = x+"/"+x+"/"+x ;

int result = st.executeUpdate ("Insert into Books values("+


newBookId +",'" + txtBookName.getText() +"','" +
txtBookAuthor.getText() +"'," + 0 + ", '"+ s +"' ,'"+ s +
"')");

4.3.4 Information Log

The information log is a JtextField used to inform the user of important system
messages like informing the user that a record has been saved. It is constructed by using
the following codes and is placed at the bottom of the JInternalFrames.

private JTextField log;

log = new JTextField();

log.setEditable(false);

log.setHorizontalAlignment(JTextField.CENTER);

getContentPane().add (log, BorderLayout.SOUTH);

to set the message shown above in the image to the information log the following code
is used.

public void focusLost (FocusEvent fe) {

log.setText("Enter The Details of Book " + newBookId);}

32
4.4 Add member

Through the above window the librarian can add new members to the system. The new
member’s Id is automatically generated and inserted. This is an insured way of creating
unique Ids for records. The librarian is only required to insert the members name since
the other two attributes are created automatically. Like the Add New Book window this
window also uses the following code in order to generate unique Id numbers for new
members.

public void focusGained (FocusEvent fe) {

try{ ResultSet getRowCount = st.executeQuery("SELECT *


FROM Members");

while (getRowCount.next()) {

rowcount = getRowCount.getInt(1); }

rowcount++;

newMemberId = Integer.toString(rowcount);

txtMemberId.setText(newMemberId);

}catch(SQLException sqlex){

log.setText(sqlex.getMessage());

} }

33
4.4.1 Date Formatting

Formatted dates are used in the system to show the member registration date, and book
issue and return dates.

In order to create a formatted date first a date object called currentDate is created. This
object holds the date of the day that the code is executed on meaning the current day or
todays date.

private java.util.Date currentDate = new java.util.Date ();

then the preferred date format sdf is created using SimpleDateFormat. If this date format
is applied to any date object that date object would take the form of dd/mm/yyyy eg,
03/04/2010.

private SimpleDateFormat sdf = new SimpleDateFormat


("dd/MM/yyyy");

then the formatted type of date is copied into a string variable todayDate. Dates are set to
string types because the system needs to update them into the database using sql scripts
and also the dates are set into the date textfields of the internal frames which accept
string types.

private String todayDate = sdf.format (currentDate);

The date is then set into the appropriate textfield, which in this case is the registration
date of the member.

txtRegistrationDate.setText(todayDate);

34
4.5 Issue Book

The user enters the book id, which is going to be issued into the book Id textfield. Since
the textfields for the other details of the book are not editable, the user can then click
anywhere else on the book issue frame and the following code will search for the book
id and obtain the book’s details and set them into their appropriate textfields.

This is done so the admin is able to issue books in a fast and user-friendly manner.

First the query finds the book id provided by the user by traversing through the database.
It checks individual book Ids in the database against the one provided by the user.

try { //SELECT Query to Retrieved the Record.

String q = "SELECT * FROM Books WHERE Book_Id = " + id +


"";

ResultSet rs = st.executeQuery (q);

rs.next ();//Moving towards the Record.

bookNo = rs.getLong ("Book_Id");

int mid=rs.getInt("Member_Id");

if(mid!=0)

{txtClear();

Log.setText("Book Already Issued");}

35
If a match is found the details of the book in question are set into the appropriate
textfields. If the record is not found then user is informed through the confirmation log at
the bottom of the screen.

txtBookName.setText ("" + rs.getString ("Book_Name"));

txtBookAuthor.setText ("" + rs.getString ("Book_Author"));}

else {found = false;}

The same procedure is done for finding the member details and setting them into the
appropriate textfields.

After the details of the books and members are found it is time to save the records into
the tables. First it searches the records for that particular member Id and it obtains the
book count of that member. Since the member is being issued another book, the book
count is increased by one and then updated to the record of that member.

try { int i1= Integer.parseInt(txtMemberId.getText());

ResultSet rs = st.executeQuery("Select * from Members


where Member_Id="+ i1 +"");

rs.next();

int bc=rs.getInt("Book_Count");

bc++;

int bid1=Integer.parseInt(txtBookId.getText());

st.executeUpdate ("Update Members SET Book_Count="+ bc +"


WHERE Member_Id="+ i1 +""); //Running Query.

If the update is successful the textfields are emptied for the next book issue and a
message is shown informing the user that the record has been saved. If it has not been
successful a message is shown which informs the user that the record could not be saved.

36
4.6 Return Book

First the Book Id provided by the user is retrieved to later be used for comparing against
the book Ids in the Loaned table.

id = Integer.parseInt (txtBookId.getText ());

As the Loaned table contains only the books that are currently on loan, then the id
provided by the user is compared against all the Book Ids in the Loaned table.

try {

ResultSet rs = st.executeQuery ("Select * from Loaned where


Book_Id="+id+"");

rs.next ();

if a matching Id has been found the details corresponding to that Id within the Loaned
table in the database can be taken and set to the textfields in the Jframe. These include
the issue date, and the Book name.

txtIssued.setText ("" + rs.getString (5)); //issue date

txtBookName.setText ("" + rs.getString ("Book_Name"));

the mid has been set earlier to take the value of the field Member_Id from the Loaned
table. This field represents the id of the member whom the book has been issued to.

mid=rs.getInt("Member_Id");
37
the number of the books held by the member are retrieved from the Members table using
the member id.

ResultSet rs1=st.executeQuery("Select * from Members where


Member_Id="+mid+"");

rs1.next();

bc=rs1.getInt("Book_Count");

the book count is decreased by 1 every time the member returns a book and is updated
into the members table.

st.executeUpdate("Update Members Set Book_Count ="+bc+"


WHERE Member_Id ="+mid+"");

It is very important for this value to always be accurate as it is used as in a prevention


mechanism in deleting the member’s record.

38
4.7 Update Book

To update the book details, the user enters the ID number of a certain book and when the
focus of the Book ID field is lost the code will retrieve the details of the book and insert
them into the appropriate fields. The ID of a book won’t be updated even if the user
changes the value in the ID field.

If the book is being held by a member the id of that member is also retrieved from the
same table and stored in bissued. If this value is not equal to zero this would mean that
the book is currently issued to a member and the book details would not be updated.

else if(bissued!=0)

{ txtClear();

log.setText("Book is held by a member"); }

if the book is not issued to any member then the update statement below will change the
details of the book in the books table.

st.executeUpdate("Update Books Set Book_Name


='"+txtBookName.getText()+"' WHERE Book_Id ="+id+"");

st.executeUpdate("Update Books Set Book_Author


='"+txtBookAuthor.getText()+"' WHERE Book_Id ="+id+"");

39
4.8 Update Member

The same approach is taken in order to update the details of a member. In the members
update window, an ID is entered by the user and when the focus is taken away from the
ID field the details corresponding to that ID are retrieved and inserted into the
appropriate fields. Note that Member IDs cannot be changed or updated.

If an ID match is not found in the result set of the query It would cause the
“SQLException invalid cursor state” to be thrown. In the event of this exception being
thrown the program is set to view the message “Member not found.” In the log at the
bottom of the frame.

catch (SQLException sqlex) {

if (found == false) {

txtClear (); //Clearing the TextFields.

log.setText("Record not Found.");

40
4.9 Delete Book

This window would enable the librarian to delete a book from the database. First the
book Id is entered into the appropriate field and when the user clicks onto the second
field or anywhere else on the delete book window the system would automatically
search for the provided book ID and assign the information related to the book id into
the book name and book author fields.

The following statement deletes the book from the appropriate table.

String q = "DELETE FROM Books WHERE Book_Id = " +


id + "";

ResultSet rs = st.executeQuery (q);

The following would show a confirmation message at the bottom of the


frame.

log.setText ("Book "+id+" Deleted.");

41
4.10 Delete Member

The librarian enters the member Id of the account that needs to be deleted
into the appropriate field and moves the cursor to the next field or clicks
anywhere inside the delete member form, if the Id exists in the database the
system would search for it and the member name is automatically inserted
into the appropriate field. If the Id does not exist the librarian is informed
about it. If the librarian chooses to delete a record first the application would
check to see if the member is holding any books by checking the value of
heldBooks, which is obtained earlier by performing a query on the members
table. If the member is holding any books then the application would prevent
the librarian from deleting the record.

else if(heldBooks!=0)

{ log.setText("Member is Holding Books. Can’t Delete


Record"); txtClear(); }

After the checks have been done the record is deleted from the database in the following
way.

String q = "DELETE FROM Members WHERE Member_Id = " + id +


"";

42
4.11 Creating the Reports

The following code creates the tables that are visible in the different reports in the
program. First the number of rows that exist in a particular table are retrieved and stored
into rowcount.
ResultSet resultSet = st.executeQuery("SELECT COUNT(*) FROM
Loaned");

resultSet.next();

rowcount = resultSet.getInt(1);

Then using the number of rows that were retrieved earlier an array of objects is created
which is later used with the JTable constructor to create a visible table in the java
environment. Rowcount is the index and essentially the first dimension of this two
dimensional array.

try{ data=new Object[rowcount][6];

another array of objects is created to hold the names of the JTable columns.

Object[] columnNames={"Book Id","Book Name","Member


ID","Member Name","Issue Date","Status"};

Then all the columns in the database table are selected using the following code.
ResultSet rs=st.executeQuery("Select * from Loaned");

A nested loop is used to store the columns that are in the resultset into the object array.
Row is the index or the first dimension f the array and it would not exceed the number of
the rows in the database table, which is stored in rowcount.

for(int row=0;row<rowcount;row++){ rs.next();

Now that all the columns from a particular row are available we can proceed to store
them in the second dimension. The second dimension array would not exceed 6 because
there are 6 columns in the Loaned table in the database and starting from 0 up till 5 will
be equal to 6 columns.

for(int column=0;column<6;column++){

the first column in the resultset is identified by number 1 therefore column+1 is used to
retrieve the first column from the resultset and store it into the object array’s second
dimension. As the for loop parameters increase so does the value of column plus one
which now for example is 1+1=2 which would identify the second column from the
resultset and it would go through this cycle and stop before the column parameter
reaches value of 6.
data[row][column]=rs.getString(column+1); } }

43
4.11.1 Loaned Books Report

The above image is of the Loaned books report. The Loaned books report consists of a
table, which holds the details of the books that are currently on loan.

In the implementation of Issue Book window, a line of code is written which is essential
to creating the Loaned Books Report. The statement below inserts into the Loaned table
values related to the issued book and the member who the book has been issued to. On
returning the book the book id is used to delete the specific record from the Loaned table
in the database, hence the Loaned books report only shows the books that are currently
on loan and out of the library.

int LoanedUpdate = st.executeUpdate ("Insert into Loaned


values(" + bookId + ",'" + txtBookName.getText() +"'," +
memberId + ",'" + txtMemberName.getText() + "' ,'" +
issueDate+ "','"+Status+"')");

The below code is implemented within Return Book window and will delete the returned
book from the Loaned table.

int deleteLoaned = st.executeUpdate("DELETE FROM Loaned


WHERE Book_Id = " + id + "");

44
4.11.2 All Books Report

The all books report views all the books including the books that are currently on loan
and issued to members.

You can see that book ID 2 is issued to member ID 1 and book ID 3 is issued to member
ID 2. The report also shows the last return and issue dates of the book.

If the book is currently on loan to a member then the last return date column says “Not
Returned” and also the member ID of the person holding the book is set in the Member
ID field.

if the book is returned then the last return date will be set to the return date of the book
and member ID will be set to zero ready to be updated to the next member’s ID who will
be burrowing the book. The following image shows the books with different issue dates
and it shows that all books were returned on 01/03/2010. Member IDs have also been set
to Zero since these books are not currently on loan to any members.

The same procedure is taken in creating all the reports, and the only difference in the
coding is the data is taken from different tables. that the data for creating the books
report is retrieved from the books table.

The following code selects all columns from the books table that exists in the database.

ResultSet rs=st.executeQuery("Select * from Books");

45
4.11.3 All Members Report

The all members report internal frame is a report of all the details of members that are
currently registered with the library.

The report shows each members ID, member name, registration date and the number of
books they are currently holding, which is in the column Book Count.

As you can see member 1 has been loaned 1 book, which he has not returned, and
member ID 2 has been issued two books that are currently not returned to the library,
while member 3 is not holding any books at all.

If a member returns a book the Book Count value is decreased by one. This however is
done in the ReturnBook.class implementation.

As you can see in the following pictures when all the books were returned the book
counts were decreased until they reached zero. Also the corresponding member ID in the
books report were set to zero meaning that no member is holding that particular book.

The data for creating the members report is retrieved from the members table.

The following code selects all columns from the members table that exists in the
database.

ResultSet rs=st.executeQuery("Select * from Members");

46
4.12 Creating Admin Accounts
For security reasons and to prevent data thieves from stealing customer information,
passwords and admin accounts have been adopted by this system. In order for Admins to
be able to make a back up copy of the database or to create new admin accounts they
would have to verify their passwords.

Only administrators are allowed to create an admin account. And only the administrator
who has started the current session of the program can do that. An administrator has to
first enter the password for the session and if the password is correct they can create an
admin account, which consists of an admin ID and a password. This ensures that data
thieves will not be able to back up the database and use it for other purposes.

the above image shows the creation of a new admin account, which has the user id
12345.

The new account is being created by admin 10688182. After the account has been
created the following values are inserted into the Admins table. You can see who has
created the new admin account by looking at the Creator ID column. For security
purposes, an approach of separation of data from management has been taken in creating
this program so Off course the database is stored away from the view of the user in the
default program folder.

47
In order to be able to use the session password for verification purposes the current
session pass and user id are passed as parameters to AddAdmin.java class on execution
of this class.

AddAdmin verify = new AddAdmin(con,pass,user);

mainWindow.add (verify);

In the AddAdmin class these values are copied into the following parameters.

public AddAdmin (Connection con,String p, String u) {

super("Create New Admin");

sessionPass = p;

sessionUser = u;

In order to verify the password the session pass which was used to start this session of
the system is compared to the pass entered by the admin into the add admin internal
frame.

if(password.equals(sessionPass)) {

If the password is equal to that of the session pass then the code proceeds to create the
new admin account by entering the details of the new account into the database.

String q = "INSERT INTO Admins " +"VALUES ('" +


userName.getText() + "', '" + NewPassword + "', '" +
sessionUser+ "')";

The query is then executed using the following code and if it is successful then the value
of int result would be set to 1.

int result = st.executeUpdate (q); //Run Query.

If the value of result is 1 then message would be viewed to inform the user that the new
admin account has been created.

if (result == 1) {

JOptionPane.showMessageDialog (this, "Admin Account [


"+userName.getText()+" ] Was Created.");

48
4.12.1 KeyListener and KeyAdapter

Because the records in a database are recognized and retrieved by their Id numbers,
which are unique integers, therefore the user should not be allowed to enter a character
into the id field of a new record. For this reason I have added a key listener to the ID
fields and used a key adapter to prevent the user from entering certain Unicode
characters into the ID fields. This way only a digit or the backspace key is allowed to be
typed inside the ID text fields. The internal frames which operate on the Id fields of
records all implement the kelistener interface.

public class DeleteBook extends JInternalFrame implements


ActionListener, FocusListener, KeyListener {

I have assigned key listeners to the text fields where the IDs are entered.

txtBookId.addKeyListener(this);

This means that whatever key is entered inside the text field the key event created by
that action can be captured and compared to certain rules. The variable c is set to be a
char and every time a character is typed the keylistener will be invoked and char c will
contain the character that is typed by the admin by using getKyChar. This means that
every time the user presses a key in the ID text field the key event would be captured
and the getKeyChar would return the Unicode character for the key that has been
pressed and char c would take that value. The value returned by getKeyChar can be a
Unicode number or character, so char c can now be either a character or a number.

The next part explains that if the value held by char c is NOT a digit and if the key event
were not the key code for the backspace key , then system would get the toolkit and use
the beep method to create an audio beep. The method will then consume the unwanted
key event and the unwanted character would not appear in the text field.

The key event created by backspace is exempt from this condition, so that the user can
use backspace to delete undesired digits.

public void keyTyped(KeyEvent ke) {

char c = ke.getKeyChar ();

if (! ((Character.isDigit (c)) || (c ==
KeyEvent.VK_BACK_SPACE))) {

getToolkit().beep ();

ke.consume ();

49
4.13 Back Up of the Database
In order to back up the database the admin who has started the current session of the
system has to authorize the procedure by verifying their password.

The password of the current session is passed to the BackUp.java class in the following
manner. Since there are no needs to execute any SQL queries in this procedure therefore
there isn’t a need for a database connection, so it is not passed to the BackUp.java class.

BackUp BackUp_Database = new BackUp (pass);

mainWindow.add (BackUp_Database);

Since these parameters are not local to BackUp.java class, they have to be assigned and
copied to new variables.

public BackUp (String pass) {

super("Back Up Database");

SessionPass = pass;

The password entered by user is then compared to the session pass to verify that it is
correct. If the password is correct then the back up database is disposed frame is
disposed of.

if(password.equals(SessionPass)) {

dispose();

50
4.13.1 Back Up File Chooser
After disposing the back up internal frame, which is used to verify the password of the
admin, a JfileChooser Is made visible. The admin can use this file chooser to select the
destination of the back up file.

The Jfile chooser is declared and displayed in the following manner.

fc = new JFileChooser();

int rs = fc.showSaveDialog(this);

The file chooser is set to only view directories, this way the user can select their desired
directory for the back up of the library to be saved to.

fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

If the user selects a directory by clicking on the save button it would mean the approve
option is returned, so the chosen directory is saved into a variable type File called
directory.

if (rs == JFileChooser.APPROVE_OPTION) {
File directory= fc.getSelectedFile();

The variable directory now holds the path name of the directory where the copy of the
database will be backed up to. for example. C:\Documents and Settings\1\Desktop.

51
4.13.2 Back Up Loop and Buffer

After the desired destination of the user for backing up the database has been obtained
the system proceeds with saving the file. The back up procedure uses a file stream, a
loop and an array of bytes in order to copy each byte from the input stream, which is the
database file, to the output stream, which is the desired destination.

The input file stream is created and it is set to retrieve the file Library.mdb from the
database folder.

try{

InputStream in = new
FileInputStream("Database/Library.mdb");

The output file stream is set to create the file in the destination that the user has chosen
and by appending the Library.mdb the program would know that it has to create the
copied file with the exact same name and extension format.

OutputStream out = new


FileOutputStream(directory+"\\Library.mdb");

An array of bytes is created to work as a buffer.

byte[] buf = new byte[1024];

The below loop condition states that while there is still a byte to be read into the array of
bytes buf, the loop must go on. In this case in. read is set to read single bytes of data
from the input stream, which is pointed at the library.mdb file.

while (in.read(buf) > 0) {

every byte that is read into the buffer, is then written out to the output stream which
points to the destination directory and creates the copy of the file library.mdb. the loop
takes the first-in, first-out approach in copying each byte.

out.write(buf); }

when the while loop ends meaning that there are zero bytes to be read from the input
stream into the buffer, the input and output streams are closed.

in.close();

out.close();

52
Chapter 5: System Testing

5.1 Test plan


The purpose of testing the system is to locate and fix any errors that might still exist. In
this chapter the results of the system availability and system tests are made available
through the use of screenshots and annotations. After each test the effects and changes
on the data in the database were also documented in order to insure data integrity.

These are the results of the final testing phase and show that the system works
completely and without any errors. all earlier detected errors have been fixed after
detection in earlier tests.

Below are the main objectives of the testing phase. Testing was done on all the frames,
internal frames and their functionalities.

Table 3: Test Objectives

No Objectives
1. On run the login window will appear or not.
2. The user should enter the correct user name and password.
3. On entering the wrong user name and password an error message will
be displayed and user has to reenter Login details.
4. Make sure that on entering correct user name and password
the main screen will appear.
5. While adding a book makes sure the user will enter all the
fields otherwise user should get an error message.
6. Make sure while adding a member all the field should be
entered, otherwise the user should get an error dialog.
7. Make sure that while deleting members or books
information is filtered and search is working correctly.
8. Make sure while issuing of book the text fields at the
bottom like member id and book id should not be empty.
9. Check the data in the database after each procedure for
correct information.
10. Check that all the menus work properly.

53
5.2 System Test Screenshots
Here are the test screenshots. These have been taken during the testing phase as evidence
to prove that the system is in perfect working order.

5.2.1 Log In

User Id and password was entered to check for log in procedure errors.

On entering the correct Id and password main menu appeared.

On entering the wrong Id and password an error message appeared.

5.2.2 Main Window

Checked each menu item for functionality.


54
All menu items are working as demonstrated in the following screenshot.

5.2.3 Issue Book

The details of the book and the member to whom the book is being issued to are entered.

55
Confirmation message is shown at the bottom of the frame.

The details, which include member Id, issue date and return date are entered into the
database.

The book count of the member is increased by one.

5.2.4 Return Book


The book id is entered and details of the book are retrieved automatically.

56
If the operation was successful the following confirmation is shown.

The member id is set to zero meaning the book is not issued to anyone. The return date is
also updated to the date that the book was returned on.

The book count of the member is deducted by one and is now equal to zero, meaning
that the member does not hold any books.

If a book issued record is not found in the Loaned tables then the following message will
appear.

5.2.5 Add Book


A book is generated automatically and details for the book have to be entered.

57
A confirmation message appears when the new record is saved.

The book record appears in the books table, which resides in the database.

58
5.2.6 Add Member

a new member ID is generated automatically to prevent duplicate records. The new


member details are entered in the form.

Confirmation message states that new record has been saved.

The database is updated with the new record.

59
5.2.7 Update Book

The book ID is entered and the book details to be updated are retrieved.

New details are entered; note that ID won’t be updated even if the user changes it.

After the details are updated, a confirmation message is shown.

The details have been updated to the database.

If a book does not exist the following message is shown.

60
5.2.8 Update Member

ID is entered and the details of the member are retrieved automatically.

New details are entered into the form.

A confirmation message is shown.

The new details are updated into the database.

61
5.2.9 Delete Book

The id of the book is entered into the appropriate field and other information is retrieved
automatically.

On deletion the following message is shown.

The record is deleted from the database.

62
5.2.10 Delete Member

The id of the member is entered into the appropriate field and the member name is
retrieved automatically.

If the user chooses the yes option the record is deleted and a confirmation message
appears.

The record is deleted from the Members table.

63
5.2.11 Loaned Books Report

Book 2 is issued to member 1.

When the loaned books report is launched the record can be seen.

When the book is returned, the record is removed from the loaned books report.

64
5.2.12 All Books Report

When the books report is launched all books that are in the books table inside the
database are viewed in the report.

You can see that all the records from the report originate from the database books table.

65
5.2.13 All Members Report

When the members report is launched all books that are in the members table inside the
database are viewed in the report.

You can see that all the records from the report originate from the database members
table.

66
5.2.14 Add Admin Account

User 10688182 types its password into the password field to authorize this procedure
and also user would enter the new log in details for the new admin account.

When the new admin account is created the following message is shown.

The admin details of admin 123456 were entered into the database.

67
5.2.15 Back Up Database

The admin enters the password to authorize the process.

If password is correct, a directory chooser appears. The user can now choose where to
save the back up copy.

A confirmation message shows the directory of the back up copy.

68
5.3 Test Conclusion

All the tests were successful and the program works perfectly. No errors could be found.

Firstly the login module was tested with wrong login information. On login screen with
invalid user name and password, the user was not allowed to access the main window
and was prompted to enter the correct login information.

On login with valid user name and password user was able to access the main screen. On
closing the login screen or clicking on cancel button on login screen the user exits the
system.

Next on add book screen, I have validated all the input fields. While adding a book, if a
field is empty then an error message appears to enter the valid value for the
corresponding fields. Also if any non-numeric characters are entered in the Id fields of
either books or member forms, a beep sound is played and the invalid characters entered
by the user are consumed so the user has to enter valid characters.

While adding records, if any fields are left empty or if there are only spaces in any fields
an error message will appear to ask for the correct values to be entered.

Also it is not possible to add books or members that have identical IDs, because the
code generates a unique id for each record.

On deleting books and members the filtering criteria are working fine, it is able to delete
books or members accordingly.

Similarly on Issue and Return book screen all the fields are checked for validation.

In sum, the system is free from errors. All the screen fields are validated. Also the tables
are loaded with correct values and are filtered accordingly. Finally the system is tested
for exit. On clicking on Quit menu Item the system exit properly. All tests are successful
as expected.

69
Chapter 6: Conclusion

6.1 Project Conclusion

The project is complete and works perfectly. All the project objectives were achieved
and the finished application has all the main features that are needed in order to manage
the circulation of library items.

This system is a comprehensive library management solution that is suitable for small
libraries. Its flexible design enables this system to be learnt and managed easily by a
librarian.

The computerized library system has all the main features needed to be functional in a
small-scale library and not only it improves the efficiency but will also reduce human
stress, thereby indirectly reducing human efforts.

From a proper analysis of the system the positive point is that it is an efficient GUI
based component and is working properly. This system can be easily plugged into other
systems.

All the aspects and features of the developed software were tested so that the finished
product would be a reliable application. The main objective of this project was to
computerize the manual Library Management System that was in place. This in turn
would reduce the human errors and human efforts by which there some savings on costs
of operating the library.

I encountered many problems in java coding. It was the most hectic part during the
entire project period. There were errors in programming and coding that is solved only
after study or finding references from books and websites. Sometimes I need to discuss
the problems with my friends to have the solution. Through the development process I
had learnt a lot of things in Java programming. I also learnt how to create database
connections using a java program, and also how to execute a query on a database
through a program and how to show the results on swing at run time.

Java database connectivity does provide an efficient way to integrate an application with
a database. If one has great knowledge and practice over JDBC it is possible to create an
application that has a lot of useful features. By using the SQL scripts, update or execute

70
features of JDBC one can easily manipulate records in a database in a way that is
satisfactory.

Java swing was very easy to learn and provides many tools and features that can be used
to create an efficient user interface this is because of the repetitive coding that has to be
done in order to create the graphical user interface. There are other features of java swing
like a drop down box or radio buttons that can be added to this system if the application
was to be expanded but for now this would be unnecessary.

The maintenance of the records is made easier as all the records are stored in MS Access
Database and this database can be backed up easily through the library system.

Overall I am happy to say that the project is a success and in fully working order.

6.2 System Limitations

The system was developed as planned but as we know, no system should be perfect and
there are some limitations to the system.

One of the limitations to the system is that it is a standalone system and can be accessed
on a single machine and only a staff can access the system. If a member wants to know
the availability of any books they have to go to the library and ask the librarian for the
availability of a particular book, then the librarian will check the system for availability
of a book in the library. If no book is available then it will be a waste of time as well as
effort for both the member and the librarian.

71
6.3 Further Enhancements
The limitations of the system were discussed in the previous section and it can be
assumed that the system can be expanded to some degree by overcoming those
limitations.

The system should be further enhanced to an online system from a standalone system.
We may convert the Library Management system to an online system so that each and
every user of library can access the system. Using access control settings each user type
(role) must be granted different privileges to access the system. Like a librarian will have
the privilege to do almost everything with the system from adding book, adding
members, to issuing and returning of the books. While other members can only view the
status of the books, like its availability in the library. If the system were to be deployed
in an intranet system then the members can view the details of a book from anywhere.
The members do not have to go to a library only to know if a certain book is available.

72
Bibliography
 Elliott, J., Eckstein, R., Loy, M., Java Swing,, Second Edition, O'Reilly, 2002,
ISBN 0596004087.

 Fisher, M., Ellis, J., Bruce, J., JDBC(TM) API Tutorial and Reference, Third
Edition, Prentice Hall, 2003, ISBN 0-321-17384-8.

 Parsian, M., JDBC Recipes: A Problem-Solution Approach, Apress, 2005, ISBN


1590595203.

 Sun Microsystems; The Java Tutorials; (c) 1995-2010 Sun Microsystems, Inc.
URL: http://air-ticket.technology-related.com/docs/books/tutorial/

 Sun Microsystems; Java 2, Standard Edition, v 1.4.2, API Specification; (c)


2003 Sun Microsystems, Inc. URL: http://java.sun.com/j2se/1.4.2/docs/api/

 Tidwell, J., Designing Interfaces: Patterns for Effective Interaction Design,


O'Reilly, 2005, ISBN 0596008031.

73
Appendix A: Project Proposal Report
Scenario
Acton youth center is the local youth center administered and run by the Acton council.
It is a community-based, non-profit organization serving the social services needs of
youth and families. Recently the council decided that the center and it’s youth members
would benefit from having an on site library. Books will be available in a variety of
topics
Provided services can be used by teens who choose not to or cannot afford to purchase
an extensive collection of books, who need material no individual can reasonably be
expected to have, or who require professional assistance with their research.
With the introduction of the library the need for a library system to regulate and manage
the processes that happen in a library is evident.
Library systems are systems for a library, used to track items and patrons who have
borrowed.
A computerized library system is called an integrated library system. It is more effective
in managing and delivering library services than the old manual systems and is
comprised of a relational database and software that acts on that database.

There are many companies that provide the libraries with this type of software, and also
provide maintenance and training for the library staff. This is usually the case where a
library operates on a large scale, has other branches that need to connect to through
Internet servers and has thousands of books, patrons and records to store. These types of
projects are very costly and require a large amount of time, work force and budget.

On the other hand some smaller libraries have started to explore the opportunities in the
open source software world. Various Companies like Equinox and LibLime have
developed open source integrated library systems like Evergreen and Koha, which
makes them totally free to use and also they provide commercial and technical support at
quite high cost.

After considering the options above the manager of the library has approached me and
asked me to create an API that suits the library’s requirements.

74
User Requirements

• Book and borrower search. It is the ability to search a book or a member by their
name or Ids.
• Issue book. When the book is issued it should be clearly stated in the system and
in case only one copy of a book is available the system should not allow the
reissuing of the book until it is returned.
• Return book. The system will make the book available for reissuing.
• Reissue book. There should not be a need for creating a new record if a person
who is holding a book wants to extend the return time.
• Reserve book. If a book is not available, it can be reserved for a member on its
return.
• Book and borrower details. When a book is issued, its details and the borrower’s
details should be recorded.
• Book and borrower notes. Being able to write special notes incase of damages,
fines, or etc about a book, member or a book issued record.
• Book history. On which date a book has been issued and to whom.
• Maintenance of fines for books returned late. System should inform the clerk of
outstanding fines on the return of the
• Borrower history. On which date a member has borrowed and what book.
• Reports on library statistics, borrower usage, etc. Report containing the number
of borrowed books by each member and reports containing book details and
number of times they been issued.
• Generation of overdue books reports and letters to borrowers. Print an
automated letter containing the member details and the overdue book being held
by the member for the purpose of informing the member

75
Research

Circulation is the process of issuing and returning of books and it is crucial to a library’s
success that this process is done properly.
The only way that circulation is done successfully is by Registering and recording the
member ID and the book ID using barcode scanning or magnetic swipe card or a RFID
chip. RFID chips are being used in some large libraries but they are very costly, and not
suitable for this operation. Magnetic swipe cards are usually used to gain information
about the cardholder or allow entry into buildings. The magnetic stripe on the back of
the card would contain too much information, which is not needed as the youth center is
open to anyone to enter and the money spent for issuing new cards could be used to buy
new books.

Considering the size of the library and the budget, having a barcode system is
more appropriate than magnetic or smart card systems. A barcode is
representation and encryption of data into image form and can be read and
decrypted back to data using a barcode scanner. Barcodes define data using width
of single vertical lines and the spacing between those lines, these types of
barcodes are called 1 dimensional barcodes or symbologies.
The symbologies that are commonly used in libraries are, Plessey, UPC, Codabar,
interleaved 2 of 5, EAN 5, and Telepen.

Barcodes can be used to identify books and members. Member and book Ids can be
encrypted into barcodes, which in turn will make the process of circulation faster and
more reliable.Java does not have a library or facility that enables creating barcodes in
APIs, but there are companies that sell customized libraries, which can be included in
the source file and adds the ability of creating and printing of barcodes. After searching
through the Internet I came to conclusion that these packages are very expensive, but I
was successful in finding an open source barcode package.

Barbecue barcode is an open source library for java that allows the creation and printing
of barcodes in java APIs.

The symbologies supported by Barbecue barcode are listed below:

76
Code128, Code128A, Code128B, Code128C, UCC128, EAN128, EAN13, Bookland,
UPC-A, Standard 2 of 5, Interleave 2 of 5, PDF417, Code 39, Codabar, PostNet.

The table below shows the common barcodes used in libraries and its availability in the
barbecue barcode package.

Common Library Symbologies Barbecue barcode symbologies

Plessey

UPC

EAN 5

Interleaved 2 of 5

Codabar

Telepen

The available barcode symbologies that I can use as the main barcode system for the ILS
are, Plessey, UPC, Interleaved 2 of 5 and Codabar.
One of the common problems with barcodes is that if they are not printed properly or the
printing is of poor quality, or they are damaged by passage of time and being used the
scanner would not be able to read the image, so the printer has to print the images in
high resolution.
the symbology interleaved 2 of 5 is one that prints the vertical lines with extra spacing
and it is two-width symbology which means the lines representing the data would be
thicker than usual, which in turn when printed and scanned would have better chance of
being read.

Software and hardware requirements

Software required

Java Development Kit: Is a development kit created by the Sun Microsystems and is a
selection of programming tools, which lets programmers create java APIs.

77
JCreator Pro: Is a Java integrated development environment for programmers and the
programmers are able to create the source code, compile, build and debug using this
IDE.

Javadoc: Is an application that prints the comments made by the programmer in the
source code, and aids in creating the end documentation.

Microsoft Office Access: Microsoft Access is the relational database system that will be
used in the application to store records of members and books.

Java Runtime Environment: JRE is the package containing java virtual machine and the
Java API as and is required for running java applications on windows.

Hardware required

Printer: Used for printing the barcodes of the books and members.

Barcode Scanner: Barcode scanner is the device that is used to scan the barcodes and
usually connects to the USB or the PS2 keyboard interface.Older barcode scanners are
connected to the PS2 interface and require separate programming to be able to interact
with the API, but the new modern USB scanners are more reliable and easier to use.
After scanning the barcode the decryption is done in the device and data is sent into the
system. When the data is sent in, it is as if the user is pressing keys on the keyboard, the
advantage is that they do not need any extra programming.

Conclusion

Considering the small size of the library compared to larger libraries, and the small
budget I have been given, I have to create an integrated library system which Is cost
effective and reliable.In order to create this system I have to create modules in java
which would act up on a certain database.Java Database Connectivity is a facility in java
which provides programmers with tools that allow the connection between a java API
and a database. using JDBC allows programmers to create and define methods for
creating queries and updating records on a database.
I have to use JDBC to create a connection is between the database and the classes in the
java API.Then by using java swing a graphical user interface will be created which will
make the system easy to interact with.

78
The applets that are created in the java Swing facility will allow the user to add
or delete records without the user having a direct interaction with the database
itself.

Webliography
http://www.linux.com/articles/58836

http://www.linux.com/articles/57322

http://java.sun.com/docs/books/tutorial/jdbc/index.html

http://www.bokai.com/ordering.htm

http://barbecue.sourceforge.net/faq.html#symbologies

http://en.wikipedia.org/wiki/Telepen

http://en.wikipedia.org/wiki/EAN_5

http://en.wikipedia.org/wiki/Interleaved_2_of_5

http://en.wikipedia.org/wiki/Codabar

http://en.wikipedia.org/wiki/Universal_Product_Code

http://en.wikipedia.org/wiki/Plessey#Plessey_barcodes

Bibliography

Rubin, Richard E. Foundations of Library and Information Science. New York: Neal-
Schuman Publishers, Inc., 2004.

Harmon and Adams(1989). Reading Between The Lines, p.13. Helmers Publishing, Inc,
Peterborough, NH. ISBN 0911261001.

79
Appendix B: Program Source Code
The following java files were printed and are available in the following section:

• LogIn.java

• MainWindow.java

• IssueBook.java

• ReturnBook.java

• AddBook.java

• AddMember.java

• UpdateBook.java

• UpdateMember.java

• DeleteBook.java

• DeleteMember.java

• LoanedBooksReport.java

• BooksReport.java

• MembersReport.java

• AddAdmin.java

• BackUp.java

80
/***************************************LogIn.java******************************
*Main() or the entrance to the program is in this file, this window creates the
Login frame and allows an admin to enter login details, if login details are
correct then the admin is granted access, if not it prompts the admin to enter
the correct details.
******************************************************************************/

import java.awt.*;//toolkit, dimension,color


import java.awt.event.*;//actionlistener,events
import javax.swing.*;//dispose, setvisible, getheight()
import java.sql.*;//connection, drivermanager, statement, resultset

//create the log on window and implement the actionlistener interface


public class LogIn extends JFrame implements ActionListener{

//panel or the background, used to add other components


private JPanel Panel = new JPanel();

//username and password labels


private JLabel userLabel, passLabel;
private JTextField userName; //username
private JButton okButton, cancelButton;
private Connection Con; //database connection

//to hide password from undesirables


private JPasswordField passText;

//get the size of the user's screen


public Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();

private JTextField log;

public LogIn () {

//seting the name and size of the logon window


setTitle("Integrated Library System");
setSize (275, 175);
setResizable (false);

//default window, close operation


//exit the program when frame is closed
this.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );

//Setting the Logon Form Position on User's Screen.


setLocation (dimension.width/2 - getWidth()/2,dimension.height/3-getHeight()/2);

81
//to manually layout components, layout manager is set to null
Panel.setLayout (null);

//Information log located at the bottom of frames, shows confirmation messages


log = new JTextField();
log.setEditable(false);
log.setHorizontalAlignment(JTextField.CENTER);

//Setting the Form's Labels.


userLabel = new JLabel ("Username:");

userLabel.setBounds (20, 15, 75, 25);


passLabel = new JLabel ("Password:");

passLabel.setBounds (20, 50, 75, 25);

//Setting the Form's TextField & PasswordField.


userName = new JTextField ();
userName.setBounds (100, 15, 150, 25);
passText = new JPasswordField ();
passText.setBounds (100, 50, 150, 25);

//Setting the Form's Buttons.


okButton = new JButton ("OK");
okButton.setBounds (20, 90, 100, 25);
okButton.addActionListener (this);
cancelButton = new JButton ("Cancel");
cancelButton.setBounds (150, 90, 100, 25);
cancelButton.addActionListener (this);

//Adding All the Controls in Panel.

Panel.add (userLabel);
Panel.add (passLabel);
Panel.add (userName);
Panel.add (passText);
Panel.add (okButton);
Panel.add (cancelButton);

getContentPane().add (log, BorderLayout.SOUTH);

//Adding Panel to the Form.


getContentPane().add (Panel);

//Opening the Database.


//database file is named " Library ".
try {

82
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
String loc = "jdbc:odbc:Library";
Con = DriverManager.getConnection (loc);
}
catch (ClassNotFoundException cnf) {
JOptionPane.showMessageDialog (null,cnf.getMessage());
System.exit (0);
}
catch (SQLException sqlex) {
JOptionPane.showMessageDialog (null, sqlex.getMessage());
System.exit (0);
}

//Show The Logon Form.


setVisible (true);
}//end of login()

/******************************************************************************
*this part of the code is executed when either the ok button or cancel button
are clicked.if cancel button is pressed the frame is closed, if ok button is
pressed, the password entered by admin is copied and a query is made to the
database also to search and find the ID entered by the admin. if the ID is
found in the database, the password that exists along with that ID in the
admins table is retrieved,this password is then compared to the password
entered by admin and if correctthe admin is granted access, if not the
textfields are cleard and await the entry of new logIn info.
******************************************************************************/

public void actionPerformed (ActionEvent ae) {


Object Choice = ae.getSource();

if (Choice == cancelButton) { //If Cancel Button Pressed


setVisible (false); //Unload the From.
dispose();
}
else if (Choice == okButton) { //If OK Button Pressed.

String sessionPass = new String (passText.getPassword());


String sessionUser = new String (userName.getText());
String databasePass; //To Hold the Password.
String databaseUser;

83
try {
boolean foundID = false;
Statement st = Con.createStatement (); //Creating Statement Object.
//a Query to Retrieved the login details.
String query = "SELECT * FROM " + "Admins" + " WHERE Id = "
+Integer.parseInt(sessionUser);
ResultSet rs = st.executeQuery (query); //Executing the Query.
rs.next(); //Moving Towards the Record.
databaseUser = rs.getString ("ID"); //Storing UserName.
databasePass = rs.getString ("Password"); //Storing Password.

//compare databse pass to pass entered by user


if (sessionPass.equals (databasePass)) {

/*send this session's user name and password to mainwindow process, these will be
used later, when user wants to back up database, or create admin accounts, they
will be verified using these parameters.*/

new MainWindow (Con,sessionPass,sessionUser);


setVisible (false); //Hide the login window.
dispose(); //realease the Resources.
}
else{
log.setText("Incorrect LogIn Information");
userName.setText ("");
passText.setText ("");
userName.requestFocus ();
}

/*if user ID does not exist invalid cursor state exception is caught
here*/
catch (Exception sqlex) {
log.setText("Incorrect LogIn Information");
userName.setText ("");
passText.setText ("");
userName.requestFocus ();
//JOptionPane.showMessageDialog(this,sqlex.getMessage());
}}}
//the main method/entrance to the program.
public static void main(String args[]) {

LogIn start=new LogIn();}

84
/**************************************MainWindow.java*************************
*this window is the main window of the system,it is the desktop pane and all
other frames appear in this frame as internal frames, from this window all
the features of the system can be selected and executed,this window is
initiated and appears when the user proves his identity by entering the correct
login details in the login.java frame, which is the main entrance to the
program.
******************************************************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;
import java.text.*;

//implements action listener to manage actions created by buttons


public class MainWindow extends JFrame implements ActionListener{

private JDesktopPane mainWindow = new JDesktopPane ();


private JMenuBar bar;
private JMenu fileMenu,editMenu ,helpMenu;
private JMenuItem addBook, newMember,newUser,BackItUp;
private JMenuItem issueBook, returnBook, delBook, delMember,UpdateB,UpdateM;
private JMenuItem about;
private JToolBar toolBar;
private JButton
btnAddAdmin,btnBackUp,btnBooksReport,btnMembersReport,btnLoanedBooks,btnaddBook,
btnNewMember, btnIssue, btnReturn, btnDelB,btnDelM,btnUpdateB,btnUpdateM;

private JPanel statusBar = new JPanel ();


private JLabel lbDate;

private java.util.Date currentDate = new java.util.Date ();


private SimpleDateFormat sdf = new SimpleDateFormat ("dd MMMM yyyy");

private String todayDate = sdf.format (currentDate);


private Connection con;
private Statement st;
public Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
private String pass,user;

//database connection, session password and session username


public MainWindow (Connection c,String p,String u)
{
super ("Farhad Taran's Integrated Library System");

85
//the database connection is passed to the instances of internal frames when they
are created.
con=c; pass = p; //holds password for current session
user=u; //holds ID of session user

//default window, close operation


//exit the program when frame is closed
this.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );

//maximizes the window onto the users screen


this.setExtendedState(JFrame.MAXIMIZED_BOTH);
bar = new JMenuBar (); //Create MenuBar Object.
setJMenuBar (bar); //Set Main Window MenuBar.

//menu items
fileMenu= new JMenu ("File");
editMenu = new JMenu ("Edit");
helpMenu = new JMenu ("Help");
// Create Menu Items of Program.
//Menu Items for FileMenu.
addBook = new JMenuItem ("Add New Book");
addBook.addActionListener (this);
newMember = new JMenuItem ("Add New Member");
newMember.addActionListener (this);
newUser = new JMenuItem ("Add New Addmin");
newUser.addActionListener (this);
BackItUp = new JMenuItem ("Back Up Database");
BackItUp.addActionListener(this);
//Menu Items for EditMenu.
issueBook = new JMenuItem ("Issue Book");
issueBook.addActionListener (this);
returnBook = new JMenuItem ("Return Book");
returnBook.addActionListener (this);
delBook = new JMenuItem ("Delete Book");
delBook.addActionListener (this);
delMember = new JMenuItem ("Delete Member");
delMember.addActionListener (this);
//Menu Items for HelpMenu.
about = new JMenuItem ("About");
about.addActionListener (this);
UpdateB = new JMenuItem ("Update Book");
UpdateB.addActionListener (this);
UpdateM = new JMenuItem ("Update Member");
UpdateM.addActionListener (this);
//Adding All Menu Items to their Menu.
//File Menu Items.
fileMenu.add (newUser);

86
fileMenu.addSeparator ();
fileMenu.add (BackItUp);
fileMenu.addSeparator ();
//Edit Menu Items.
editMenu.add (issueBook);
editMenu.add (returnBook);
editMenu.addSeparator ();
editMenu.add(addBook);
editMenu.add (newMember);
editMenu.addSeparator ();
editMenu.add (UpdateB);
editMenu.add (UpdateM);
editMenu.addSeparator ();
editMenu.add (delBook);
editMenu.add (delMember);
//Help Menu Items.
helpMenu.add (about);
//Adding All Menus to MenuBar.
bar.add (fileMenu);
bar.add (editMenu);
bar.add (helpMenu);
//create buttons for the toolbar and add images to the buttons
btnaddBook = new JButton (new ImageIcon ("Images/addBook.gif"));
btnaddBook.setToolTipText ("Add New Book");
btnaddBook.addActionListener (this);
btnNewMember = new JButton (new ImageIcon ("Images/addMember.gif"));
btnNewMember.setToolTipText ("Add New Member");
btnNewMember.addActionListener (this);
btnIssue = new JButton (new ImageIcon ("Images/issueBook.gif"));
btnIssue.setToolTipText ("Issue Book");
btnIssue.addActionListener (this);
btnReturn = new JButton (new ImageIcon ("Images/returnBook.gif"));
btnReturn.setToolTipText ("Return Book");
btnReturn.addActionListener (this);
btnDelB = new JButton (new ImageIcon ("Images/delBook.gif"));
btnDelB.setToolTipText ("Delete Book");
btnDelB.addActionListener (this);
btnDelM = new JButton (new ImageIcon ("Images/delMember.gif"));
btnDelM.setToolTipText ("Delete Member");
btnDelM.addActionListener (this);
btnUpdateB= new JButton (new ImageIcon ("Images/updateBook.gif"));
btnUpdateB.setToolTipText ("Update Book Details");
btnUpdateB.addActionListener (this);
btnUpdateM= new JButton (new ImageIcon ("Images/updateMember.gif"));
btnUpdateM.setToolTipText ("Update Member Details");
btnUpdateM.addActionListener (this);
btnLoanedBooks=new JButton (new ImageIcon ("Images/loanedBooks.gif"));
btnLoanedBooks.setToolTipText("View Loaned Books");

87
btnLoanedBooks.addActionListener(this);
btnBooksReport = new JButton(new ImageIcon ("Images/bookReport.gif"));
btnBooksReport.setToolTipText("View All Books");
btnBooksReport.addActionListener (this);
btnMembersReport = new JButton(new ImageIcon ("Images/memberReport.gif"));
btnMembersReport.setToolTipText("View All Members");
btnMembersReport.addActionListener (this);
btnAddAdmin=new JButton(new ImageIcon ("Images/addAdmin.gif"));
btnAddAdmin.setToolTipText("Create a New Admin Account");
btnAddAdmin.addActionListener(this);
btnBackUp=new JButton(new ImageIcon ("Images/backupDatabase.gif"));
btnBackUp.setToolTipText("Back Up The Database To Your Desired Location");
btnBackUp.addActionListener(this);

//add the buttons to the toolbar and seperate them by diffrent amounts of space
toolBar = new JToolBar ();
Dimension five = new Dimension(5,0);
Dimension fifteen = new Dimension (15,0);
Dimension thirty = new Dimension(30,0);
toolBar.add (btnIssue);
toolBar.addSeparator (five);
toolBar.add (btnReturn);
toolBar.addSeparator (fifteen);
toolBar.add (btnaddBook);
toolBar.addSeparator (five);
toolBar.add (btnNewMember);
toolBar.addSeparator (fifteen);
toolBar.add (btnUpdateB);
toolBar.addSeparator (five);
toolBar.add (btnUpdateM);
toolBar.addSeparator (fifteen);
toolBar.add (btnDelB);
toolBar.addSeparator (five);
toolBar.add (btnDelM);
toolBar.addSeparator (fifteen);
toolBar.add(btnLoanedBooks);
toolBar.addSeparator(five);
toolBar.add(btnBooksReport);
toolBar.addSeparator(five);
toolBar.add(btnMembersReport);
toolBar.addSeparator(fifteen);
toolBar.add(btnAddAdmin);
toolBar.addSeparator(fifteen);
toolBar.add(btnBackUp);

//shows the date on the buttom of the window


lbDate= new JLabel (todayDate);

88
statusBar.setLayout (new BorderLayout());
statusBar.add (lbDate, BorderLayout.EAST);

//Setting the Contents of Programs.


getContentPane().add (toolBar, BorderLayout.NORTH);
getContentPane().add (mainWindow, BorderLayout.CENTER);
getContentPane().add (statusBar, BorderLayout.SOUTH);

//view the mainwindow


setVisible (true); }

/******************************************************************************
*all the menu items are assigned actionlisteners, if an action event is created
by choosing a menu item,the action event's source is copied into a object
variable,the object variable is checked to find out which menu item has
created the event, e.g. if event has occured because the user has clicked
on addmember or has chosen the addmember menu item? if yes then it would
launch the addmember button. before the particular frame is launched it would
first check to see if the window is already open somewhere inside the
mainwindow,if the particular frame is already open then it would bring the
frame to front, if it is not open a new instant of the frame is created, this
is done so multiple instances of addmember window are not created.
*****************************************************************************/

public void actionPerformed (ActionEvent ae) {


Object obj = ae.getSource();

if (obj == addBook || obj == btnaddBook) {

boolean b = isFrameOpen ("Add New Book");


if (b == false) {
AddBook adBook = new AddBook (con);
mainWindow.add (adBook); //Adding Child Window to DesktopPane.
adBook.toFront (); //Showing the Child Window.
}}

else if (obj == newMember ||obj == btnNewMember) {

boolean b = isFrameOpen ("Add New Member");


if (b == false) {
AddMember adMember = new AddMember (con);
mainWindow.add (adMember);
adMember.toFront ();

}}

else if (obj == issueBook || obj == btnIssue) {

89
boolean b = isFrameOpen ("Issue Book");
if (b == false) {
IssueBook isBook = new IssueBook (con);
mainWindow.add (isBook);
isBook.toFront ();
}}

else if (obj == returnBook || obj == btnReturn) {

boolean b = isFrameOpen ("Return Book");


if (b == false) {
ReturnBook rtBook = new ReturnBook (con);
mainWindow.add (rtBook);
rtBook.toFront ();
}}

else if (obj == delBook || obj==btnDelB) {

boolean b = isFrameOpen ("Delete Book");


if (b == false) {
DeleteBook dlBook = new DeleteBook (con);
mainWindow.add (dlBook);
dlBook.toFront ();
}}

else if (obj == delMember || obj==btnDelM) {

boolean b = isFrameOpen ("Delete Member");


if (b == false) {
DeleteMember dlMember = new DeleteMember (con);
mainWindow.add (dlMember);
dlMember.toFront ();
}}

else if (obj == newUser||obj==btnAddAdmin) {

boolean b = isFrameOpen ("Create New Admin");


if (b == false) {
AddAdmin verify = new AddAdmin(con,pass,user);
mainWindow.add (verify);
verify.toFront(); } }

else if (obj == btnLoanedBooks) {

boolean b = isFrameOpen ("Loaned Books Report");


if (b == false) {
LoanedBooksReport onLoan = new LoanedBooksReport(con);
mainWindow.add(onLoan);

90
onLoan.toFront();} }

else if (obj == about) {

String msg = "Integrated Library System.\n\n" + "Created & Designed By:\n" +


"Farhad Taran 10688182\n\n";
JOptionPane.showMessageDialog (this, msg, "About", JOptionPane.PLAIN_MESSAGE);

else if (obj == UpdateB|| obj == btnUpdateB) {

boolean b = isFrameOpen ("Update Book");

if (b == false) {
UpdateBook UpdateBookDetail = new UpdateBook (con);
mainWindow.add (UpdateBookDetail);
UpdateBookDetail.toFront ();
}}

else if (obj == UpdateM|| obj == btnUpdateM) {

boolean b = isFrameOpen ("Update Member");

if (b == false) {
UpdateMember UpdateMemberDetail = new UpdateMember (con);
mainWindow.add (UpdateMemberDetail);
UpdateMemberDetail.toFront ();
}}

else if (obj == BackItUp || obj == btnBackUp) {

boolean b = isFrameOpen ("Back Up Database");

if (b == false) {
BackUp BackUp_Database = new BackUp (pass,user);
mainWindow.add (BackUp_Database);
BackUp_Database.toFront ();
}}

else if (obj == btnBooksReport) {

boolean b = isFrameOpen ("Books Report");

if (b == false) {

91
BooksReport NewBookReport = new BooksReport (con);
mainWindow.add (NewBookReport);
NewBookReport.toFront();
}}

else if (obj == btnMembersReport) {

boolean b = isFrameOpen ("Members Report");

if (b == false) {
MembersReport NewMembersReport = new MembersReport (con);
mainWindow.add (NewMembersReport);
NewMembersReport.toFront();
}}}
/******************************************************************************
*this method is called to check if a frame already is open inside the
mainwindow, if the frame is open then creating a new instance of that frame
would mean that we would have two copies of the same frame on the desktop and
this clutters up our desktop (mainwindow) as well as consuming procssing power
so instead of creating another copy the frame is simply brought forward in this
method using allInternalFrames[i].toFront; if the frame is not already open,
then this method informs the procedure that has called it by sending a false
boolean value meaning that creating a new instance of the frame would not
result in duplicate internal frames.
******************************************************************************/

private boolean isFrameOpen (String title) {

//craete an array of internal frames and retrive all internal frames


presently open and store them in this array.
JInternalFrame[] allInternalFrames = mainWindow.getAllFrames ();

//iterate one by one through the internalFrames stored in the array


for (int i = 0; i < allInternalFrames.length; i++) {

//check if the internalFrame is already open


if (allInternalFrames[i].getTitle().equalsIgnoreCase (title)) {

//if internalFrame is already open, then make it visible.


allInternalFrames[i].toFront();

//return true if the internalFrame is open


return true;}}

//return false if the internalFrame is not already open


return false;}}

92
/***********************************IssueBook.java******************************
* class provides the GUI and functionality for issuing books to users
******************************************************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;

public class IssueBook extends JInternalFrame implements ActionListener,


FocusListener,KeyListener {

private JPanel pBook = new JPanel ();


private JLabel lbBookId, lbBookName, lbBookAuthor, lbMemberId,
lbMemberName,lbDate;
private JTextField txtBookId, txtBookName, txtBookAuthor, txtMemberId,
txtMemberName,txtDate,log;
private JButton btnOk, btnCancel;
private Statement st; //needed for creating sql scripts
private long bookId = 0;
private int memberId = 0;
private int day,month,year;
private String issueDate,nullDate=("0/0/0"),Status=("Not Returned");

public IssueBook (Connection con) {

//super (Title, Resizable, Closable, Maximizable, Iconifiable)


super ("Issue Book", false, true, false, true);
setSize (325, 325);

/********************************************************/
/*creates GUI components, labels, buttons, textfields */
/********************************************************/
log = new JTextField ();
log.setEditable(false);
log.setHorizontalAlignment(JTextField.CENTER);
lbBookId = new JLabel ("Book Id:");
lbBookId.setBounds (15, 15, 100, 20);
lbBookName = new JLabel ("Book Name:");
lbBookName.setBounds (15, 45, 100, 20);
lbBookAuthor = new JLabel ("Book Author:");
lbBookAuthor.setBounds (15, 75, 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);

93
lbMemberName.setBounds (15, 165, 100, 20);
lbDate = new JLabel ("Issue Date:");
lbDate.setForeground (Color.black);
lbDate.setBounds (15, 195, 100, 20);
txtBookId = new JTextField ();
txtBookId.setHorizontalAlignment (JTextField.RIGHT);
txtBookId.addFocusListener (this);
txtBookId.setBounds (120, 15, 175, 25);
txtBookName = new JTextField ();
txtBookName.setEditable(false);
txtBookName.setBounds (120, 45, 175, 25);
txtBookAuthor = new JTextField ();
txtBookAuthor.setEditable(false);
txtBookAuthor.setBounds (120, 75, 175, 25);
txtMemberId = new JTextField ();
txtMemberId.setHorizontalAlignment (JTextField.RIGHT);
txtMemberId.addFocusListener (this);
txtMemberId.setBounds (120, 135, 175, 25);
txtMemberName = new JTextField ();
txtMemberName.setEditable(false);
txtMemberName.setBounds (120, 165, 175, 25);
txtDate = new JTextField ();
txtDate.setBounds (120, 195, 175, 25);
txtDate.setEditable(false);
btnOk = new JButton ("OK");
btnOk.setBounds (50, 235, 100, 25);
btnOk.addActionListener (this);
btnCancel = new JButton ("Cancel");
btnCancel.setBounds (170, 235, 100, 25);
btnCancel.addActionListener (this);
pBook.setLayout (null);
pBook.add (lbBookId);
pBook.add (lbBookName);
pBook.add (lbBookAuthor);
pBook.add (lbMemberId);
pBook.add (lbMemberName);
pBook.add (txtBookId);
pBook.add (txtBookName);
pBook.add (txtBookAuthor);
pBook.add (txtMemberId);
pBook.add (txtMemberName);
pBook.add (btnOk);
pBook.add (btnCancel);
pBook.add (txtDate);
pBook.add (lbDate);
//Adding Panel to Form.
getContentPane().add (pBook);
getContentPane().add (log, BorderLayout.SOUTH);

94
/****************end of GUI components****************/
//adding keylisteners to the Id fields
txtBookId.addKeyListener(this);
txtMemberId.addKeyListener(this);

/***creating a connection to the dtabase needed for executing sql scripts******/

try {
st = con.createStatement ();
}
catch (SQLException sqlex) {
JOptionPane.showMessageDialog (null, sqlex.getMessage());
dispose ();
}

/******action event handling for the actions created by frame's buttons*********


if the ok button is pressed, first checks to see if book and member IDs have
been entered,if so then member record is retrieved and its book count is
incremented by one to indicate that member has been issued a book, then an
issued book record is inserted into the loaned table,the details of the
particular book being issued are also updated in the books table.
******************************************************************************/

public void actionPerformed (ActionEvent ae) {

Object obj = ae.getSource();


if (obj == btnOk) { //If OK Button Pressed.
if (txtBookId.getText().equals ("")) {
log.setText( "Book's Id not Provided.");
txtBookId.requestFocus ();}

else if (txtMemberId.getText().equals ("")) {


log.setText("Member's Id not Provided.");
txtMemberId.requestFocus ();}

else {try {
int i1= Integer.parseInt(txtMemberId.getText());
ResultSet rs = st.executeQuery("Select * from Members where Member_Id="+ i1 +"");
rs.next();
int bc=rs.getInt("Book_Count");
bc++;
int bid1=Integer.parseInt(txtBookId.getText());
st.executeUpdate ("Insert into Loaned values(" + bookId + ",'" +
95
txtBookName.getText() +"'," + memberId + ",'" + txtMemberName.getText() + "' ,'" +
todayDate+ "','"+Status+"')");
//updates number of books held by member
st.executeUpdate ("Update Members SET Book_Count="+ bc +" WHERE Member_Id="+ i1
+""); //Running Query.
//update details of book in the books table
st.executeUpdate("Update Books SET Member_Id= "+ i1 + ", Issue_Date = '"+
todayDate +"',Return_Date = '"+ Status +"' where Book_Id="+bid1+"");
log.setText("Book has been issued");
txtClearBook();
txtClearMember();}

catch (SQLException sqlex) {JOptionPane.showMessageDialog (this,


sqlex.getMessage()); }}}
if (obj == btnCancel) {//If Cancel Button Pressed Unload the From.
setVisible (false);
dispose();}}

/****************Focus handling for book's details fields***********************


*the focus listener is executed when the focus is shifted from the ID textfield
this means that the user has entered a book ID and wants to issue the specific
book using the ID, in the event of book id textfiled losing focus, the
following code is executed,the bookid is checked, the book record is retrieved
from books table and inserted into the frame.s set true. then the record
details are retrieved and appended to the form.
******************************************************************************/

public void focusGained (FocusEvent fe) { }


public void focusLost (FocusEvent fe) {
Object obj = fe.getSource ();
if (obj == txtBookId) {
bookId = Integer.parseInt (txtBookId.getText ()); //Converting String to
integer.
long bookNo;//Use for Comparing the Book's Id.
boolean found = false;//To Confirm the Book's Id Existance.
try { //SELECT Query to Retrieved the Record.
String q = "SELECT * FROM Books WHERE Book_Id = " + bookId + "";
ResultSet rs = st.executeQuery (q); //Executing the Query.
rs.next (); //Moving towards the Record.
bookNo = rs.getLong ("Book_Id"); //Storing the Record.
int mid=rs.getInt("Member_Id");

if(mid!=0){
txtBookId.requestFocus ();
txtBookId.setText ("");
txtBookName.setText ("");
txtBookAuthor.setText ("");
log.setText("Book is Already Issued");}

96
else { //If Record Found then Display Records.
txtBookId.setText ("" + bookId);
txtBookName.setText ("" + rs.getString ("Book_Name"));
txtBookAuthor.setText ("" + rs.getString ("Book_Author"));}

//if record is not found invalid cursor state is thrown


catch (SQLException sqlex) {

txtClearBook();
log.setText( "Book not Found.");
}}

/*************Focus handling for member's details fields************************


*the following part is executed when focus is shifted from the member id field
this means that the user has entered a member ID and wants to issue a specific
book to this member ID.when the following code is executed,the member id is
checked, the member record is retrieved from members table and inserted into
the frame.
******************************************************************************/

else if (obj == txtMemberId) {

memberId = Integer.parseInt (txtMemberId.getText ()); //Converting String to


Numeric.
int memberNo,heldBooks; //Use for Comparing the
Member's Id.
boolean find = false;//To Confirm the Member's Id Existance.

try { //SELECT Query to Retrieved the Record.


String q = "SELECT * FROM Members WHERE Member_Id = " + memberId + "";
ResultSet rs = st.executeQuery (q); //Executing the Query.
rs.next (); //Moving towards the Record.
heldBooks=rs.getInt("Book_Count");
txtMemberName.setText ("" + rs.getString ("Member_Name"));
rs.close();

}catch (SQLException sqlex) {


txtClearMember(); //Clearing the TextFields.
log.setText("Member not Found.");
}}}
/************************end of focus handling*********************************/

//now clear all the fields.


private void txtClearMember () {
txtMemberId.setText ("");
txtMemberName.setText ("");

97
txtMemberId.requestFocus ();
}
private void txtClearBook() {
txtBookId.setText ("");
txtBookName.setText ("");
txtBookAuthor.setText ("");
txtBookId.requestFocus ();
}

/*******************************************************************************
keylistener prevents users from entering non digit character into the id fields
of members and books, and consumes the key followed by a beep sound.
*******************************************************************************/
public void keyTyped(KeyEvent ke) {

char c = ke.getKeyChar ();


if (! ((Character.isDigit (c)) || (c == KeyEvent.VK_BACK_SPACE))) {
getToolkit().beep ();
ke.consume ();}
}
public void keyPressed(KeyEvent ke) {}
public void keyReleased(KeyEvent ke) {} }

98
/****************************Returnbook.java***********************************
*creates the GUI and the functionality that allows the user to enter details of
a book that is being returned to the library.
******************************************************************************/

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.sql.*;
import java.text.*;

public class ReturnBook extends JInternalFrame implements ActionListener,


FocusListener, KeyListener {

private JPanel pBook = new JPanel ();


private JLabel lbBookId, lbBookName,lbIssued,lbDate;
private JTextField txtBookId, txtBookName, txtIssued,txtDate,log;
private boolean Issued;//is book issued? true, false
private JButton btnReturn, btnCancel;
private int day,month,year;
private String returnDate,nullDate=("0/0/0");
private Statement st; //needed for creating sql scripts
private ResultSet rs; //needed for creating statements
private long id = 0; //book id
private int memberId,bc; //member ID, Book Count
private java.util.Date currentDate = new java.util.Date ();
private SimpleDateFormat sdf = new SimpleDateFormat ("dd/MM/yyyy");
private String todayDate = sdf.format (currentDate);

public ReturnBook (Connection con) {

//super (Title, Resizable, Closable, Maximizable, Iconifiable)


super ("Return Book", false, true, false, true);
setSize (325, 235);

/********************************************************/
/*creates GUI components, labels, buttons, textfields */
/********************************************************/
log = new JTextField ();
log.setEditable(false);
log.setHorizontalAlignment(JTextField.CENTER);
lbBookId = new JLabel ("Book Id:");
lbBookId.setBounds (15, 15, 100, 20);
lbBookName = new JLabel ("Book Name:");
lbBookName.setBounds (15, 45, 100, 20);

99
lbIssued = new JLabel ("Book Issued On:");
lbIssued.setBounds (15, 75, 100, 20);
lbDate = new JLabel ("Return Date:");
lbDate.setBounds (15, 105, 100, 20);
txtBookId = new JTextField ();
txtBookId.setHorizontalAlignment (JTextField.RIGHT);
txtBookId.addFocusListener (this);
txtBookId.setBounds (120, 15, 175, 25);
txtBookId.addKeyListener(this);
txtBookName = new JTextField ();
txtBookName.setEditable(false);
txtBookName.setBounds (120, 45, 175, 25);
txtIssued = new JTextField ();
txtIssued.setBounds (120, 75, 175, 25);
txtIssued.setEditable(false);
txtDate = new JTextField ();
txtDate.setBounds (120, 105, 175, 25);
txtDate.setEditable(false);
txtDate.setText(todayDate);
btnReturn = new JButton ("Return Book");
btnReturn.setBounds (25, 145, 125, 25);
btnReturn.addActionListener (this);
btnCancel = new JButton ("Cancel");
btnCancel.setBounds (165, 145, 125, 25);
btnCancel.addActionListener (this);
pBook.setLayout (null);
pBook.add (lbBookId);
pBook.add (lbBookName);
pBook.add (lbIssued);
pBook.add (txtBookId);
pBook.add (txtBookName);
pBook.add (txtIssued);
pBook.add (txtDate);
pBook.add (lbDate);
pBook.add (btnReturn);
pBook.add (btnCancel);
getContentPane().add (pBook);
getContentPane().add (log, BorderLayout.SOUTH);

/*************************************************************************
*creating a connection to the database, in case of error close the frame*/

try {st = con.createStatement (); } //Creating Statement Object.


catch (SQLException sqlex) { //If Problem then Show the User a Message.
JOptionPane.showMessageDialog (null, sqlex.getMessage());
dispose ();} //Closing the Form
// show the frame
setVisible (true); }//end of return book class

100
/*******************************************************************************
*the following code is executed after the focuslistener interface,creates an
object of the action event created by the user when clicking on a button if
user chooses the return button, first checks if the user has entered the book
ID or if the book id is for a book that hasnt been issued, if so asks for
correct ID, if the ID is correct, the book count of the member who is holding
that book is deducted by 1. the corresponding data is updated to all the tables
******************************************************************************/
public void actionPerformed (ActionEvent ae) {
Object obj = ae.getSource();
if (obj == btnReturn) { //If Return Button Pressed.
if( (Issued==false)||txtBookId.getText().equals ("")) {
log.setText( "Not An Issued Book");
txtBookId.requestFocus ();}
else {
try {bc--;//deduct member’s book count
id = Integer.parseInt (txtBookId.getText ());
ResultSet rs = st.executeQuery ("select * from Books WHERE Book_Id ="+id+"");
rs.next();
rs.close();

if (Issued==true){ //update values of the book and member records


st.executeUpdate("DELETE FROM Loaned WHERE Book_Id = " + id + "");
st.executeUpdate("Update Books Set Return_Date ='"+todayDate+"' WHERE Book_Id
="+id+"");
st.executeUpdate("Update Books Set Member_Id ="+0+" WHERE Book_Id ="+id+"");
st.executeUpdate("Update Members Set Book_Count ="+bc+" WHERE Member_Id
="+memberId+"");
log.setText( "Book Returned");
txtClear();}}

catch (SQLException sqlex) {


JOptionPane.showMessageDialog(this,sqlex.getMessage());}}}

if (obj == btnCancel) {//If Cancel Button Pressed Unload the From.


setVisible (false);
dispose();}}

101
/*******************************Focus handling**********************************
the focus listener is executed when the focus is shifted from the ID textfield
this means that the user has entered a book ID and proceeds to return the
specific book using the ID, in the event of losing focus, the following code is
executed,the id is checked the records in the loaned table to see if the book
has been issued, if so boolean value issued is set true. then the record
details are retrieved and appended to the form
******************************************************************************/
public void focusGained (FocusEvent fe) { }
public void focusLost (FocusEvent fe) {
id = Integer.parseInt (txtBookId.getText ()); //Converting String to
Numeric.
long bookNo;
try { //gets the record.
ResultSet rs = st.executeQuery ("Select * from Loaned where Book_Id="+id+"");
rs.next (); //Moving towards the Record.
log.setText("");
Issued=true; //If boolean true then delete record from loaned table too
txtIssued.setText ("" + rs.getString (5));
txtBookId.setText ("" + id);
txtBookName.setText ("" + rs.getString ("Book_Name"));
memberId=rs.getInt("Member_Id");
ResultSet rs1=st.executeQuery("Select * from Members where
Member_Id="+memberId+"");
rs1.next();
bc=rs1.getInt("Book_Count");
}
catch (SQLException sqlex) {//if record is not found, invalid cursor state is
thrown
log.setText("Not an Issued Book.");
txtClear();
}}

private void txtClear () {


txtBookId.setText ("");
txtBookName.setText ("");
txtIssued.setText ("");
txtBookId.requestFocus ();
}
public void keyTyped(KeyEvent ke) {
char c = ke.getKeyChar ();
if (! ((Character.isDigit (c)) || (c == KeyEvent.VK_BACK_SPACE))) {
getToolkit().beep ();
ke.consume ();
}}
public void keyPressed(KeyEvent ke) {}
public void keyReleased(KeyEvent ke) {}}

102
/*********************************AddBook.java *********************************
prvides the interface for adding book records to the database.
the focuslistener in this class contains a code which creates unique Ids for
new book records.the actionlistener contains sql scripts that insert new
records with unique ids into database when the ok button is pressed by user.
******************************************************************************/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.lang.String;

public class AddBook extends JInternalFrame implements ActionListener,


FocusListener {

private JPanel pBook = new JPanel ();


private JLabel lbBookId, lbBookName, lbBookAuthor;
private JTextField txtBookId, txtBookName, txtBookAuthor;
private JButton btnOk, btnCancel;
private Statement st;
private int rowcount=0;
private String newBookId;
private JTextField log;

public AddBook (Connection con) {

//super (Title, Resizable, Closable, Maximizable, Iconifiable)


super ("Add New Book", false, true, false, true);
setSize (325, 210);

//Setting the Logon Form Position on User's Screen.


setLocation (20,20);

/*create all the GUI and position them manually(absolute positioning)*/


log = new JTextField();

103
log.setEditable(false);
log.setHorizontalAlignment(JTextField.CENTER);
lbBookId = new JLabel ("Book Id:");

lbBookId.setBounds (15, 15, 100, 20);


lbBookName = new JLabel ("Book Name:");

lbBookName.setBounds (15, 45, 100, 20);


lbBookAuthor = new JLabel ("Book Author:");

lbBookAuthor.setBounds (15, 75, 100, 20);


txtBookId = new JTextField ();
txtBookId.setHorizontalAlignment (JTextField.RIGHT);
txtBookId.setEditable(false);
txtBookId.addFocusListener (this);
txtBookId.setBounds (120, 15, 175, 25);
txtBookName = new JTextField ();
txtBookName.setBounds (120, 45, 175, 25);
txtBookAuthor = new JTextField ();
txtBookAuthor.setBounds (120, 75, 175, 25);
btnOk = new JButton ("Add Book");
btnOk.setBounds (25, 120, 125, 25);
btnOk.addActionListener (this);
btnCancel = new JButton ("Cancel");
btnCancel.setBounds (165, 120, 125, 25);
btnCancel.addActionListener (this);
pBook.setLayout (null);
pBook.add (lbBookId);
pBook.add (lbBookName);
pBook.add (lbBookAuthor);
pBook.add (txtBookId);
pBook.add (txtBookName);
pBook.add (txtBookAuthor);
pBook.add (btnOk);
pBook.add (btnCancel);
getContentPane().add (log, BorderLayout.SOUTH);
getContentPane().add (pBook);

try {
st = con.createStatement ();
}
catch (SQLException sqlex) {
JOptionPane.showMessageDialog(this,sqlex.getMessage());
dispose ();
}

104
setVisible (true);}

/*******************************************************************************
*when user clicks on ok button, the code checks to see if the any fields are
empty if so the user is asked to provide the complete book details,if all
fields are completed by user then all fields are inserted into the table using
the unique id which is created in the focuslistener interface.
******************************************************************************/
public void actionPerformed (ActionEvent Event) {
Object obj = Event.getSource();
if (obj == btnOk) { //If OK Button Pressed.

//Validating to Check All Required Information Provided or Not.


if (txtBookId.getText().equals ("")) {
log.setText( "Book's Id not Provided.");
txtBookId.requestFocus ();}

else if (txtBookName.getText().equals ("")) {


log.setText("Book's Name not Provided.");
txtBookName.requestFocus ();
}
else if (txtBookAuthor.getText().equals ("")) {
log.setText("Book's Author Name not Provided.");
txtBookAuthor.requestFocus ();}

else{
try {

int x = 0;
String s = x+"/"+x+"/"+x ;

//have to fill in all the database columns otherwise exception will be thrown
int result = st.executeUpdate ("Insert into Books values("+ newBookId +",'" +
txtBookName.getText() +"','" + txtBookAuthor.getText() +"'," + 0 + ", '"+ s +"'
,'"+ s + "')"); //Running Query.

if (result == 1) { //If Query Successful.


log.setText("Book "+newBookId+" has been Saved.");
txtClear(); //Clearing the TextFields.
}

}catch (SQLException sqlex) {


log.setText(sqlex.getMessage());
}}}

105
if (obj == btnCancel) { //If Cancel Button Pressed Unload the From.
setVisible (false);
dispose();}}

/*******************************************************************************
*when the user clicks on the book id field the focuslistener attached to that
field is activated and the following code is executed,the sql script gets all
columns from each row, but for each row that the next() command goes through
only the first field which contains the id of a book record is saved into
rowcount. at the end of the loop row count will be holding the id of the last
book record, the new book record should have an id which is one number larger
than the last book id, so the rowcount is incremented by 1 and its converted
to string before being set into the id textfield.
******************************************************************************/
public void focusGained (FocusEvent fe) {

try{//selects all columns from the books table


ResultSet getRowCount = st.executeQuery("SELECT * FROM Books");

while (getRowCount.next()) {

rowcount = getRowCount.getInt(1); }

rowcount++;

newBookId = Integer.toString(rowcount);

txtBookId.setText(newBookId);

}catch(SQLException sqlex){
JOptionPane.showMessageDialog(this,sqlex.getMessage());
}
}

public void focusLost (FocusEvent fe) {

log.setText("Enter The Details of Book " + newBookId);}


private void txtClear() {

txtBookId.setText ("");
txtBookName.setText ("");
txtBookAuthor.setText ("");
txtBookId.requestFocus ();
}}

106
/*********************************AddMember.java********************************
*provides gui and interface for creating new member records.
******************************************************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;
import java.text.*;//simpledateformat

public class AddMember extends JInternalFrame implements ActionListener,


FocusListener, KeyListener {

private JPanel pMember = new JPanel ();


private JLabel lbMemberId, lbMemberName, lbRegistrationDate;
private JTextField txtMemberId, txtMemberName,txtRegistrationDate;
private JButton btnOk, btnCancel;
private Statement st;
private String newMemberId;
private int day,month,year;
private String registrationDate;
private int rowcount=0;
private JTextField log;
private java.util.Date currentDate = new java.util.Date ();
private SimpleDateFormat sdf = new SimpleDateFormat ("dd/MM/yyyy");
private String todayDate = sdf.format (currentDate);

public AddMember (Connection con) {

//super (Title, Resizable, Closable, Maximizable, Iconifiable)


super ("Add New Member", false, true, false, true);
setSize (325, 210);
log = new JTextField();
log.setEditable(false);
log.setHorizontalAlignment(JTextField.CENTER);
//Setting the Form's Labels.
lbMemberId = new JLabel ("Member Id:");
lbMemberId.setBounds (15, 15, 100, 20);
lbMemberName = new JLabel ("Member Name:");
lbMemberName.setBounds (15, 45, 100, 20);
lbRegistrationDate = new JLabel ("Entry Date:");
lbRegistrationDate.setBounds (15, 75, 100, 20);
txtMemberId = new JTextField ();
txtMemberId.setHorizontalAlignment (JTextField.RIGHT);
txtMemberId.addFocusListener (this);
txtMemberId.setBounds (120, 15, 175, 25);
txtMemberId.setEditable(false);

107
txtMemberName = new JTextField ();
txtMemberName.setBounds (120, 45, 175, 25);
//keyadapter to prevent users from entering digits as member names
txtMemberName.addKeyListener(this);
txtRegistrationDate=new JTextField();
txtRegistrationDate.setBounds(120, 75, 175, 25);
txtRegistrationDate.setEditable(false);
txtRegistrationDate.setText(todayDate);

btnOk = new JButton ("Add Member");


btnOk.setBounds (25, 120, 125, 25);
btnOk.addActionListener (this);
btnCancel = new JButton ("Cancel");
btnCancel.setBounds (165, 120, 125, 25);
btnCancel.addActionListener (this);
pMember.setLayout (null);
pMember.add (lbMemberId);
pMember.add (lbMemberName);
pMember.add (lbRegistrationDate);
pMember.add (txtMemberId);
pMember.add (txtMemberName);
pMember.add(txtRegistrationDate);
pMember.add (btnOk);
pMember.add (btnCancel);
getContentPane().add (pMember);
getContentPane().add (log, BorderLayout.SOUTH);

try { st = con.createStatement (); //Creating Statement Object.

} catch (SQLException sqlex) { //If Problem then Show the User a Message.

JOptionPane.showMessageDialog(this,(sqlex.getMessage()));
dispose ();}
setVisible (true);}

public void actionPerformed (ActionEvent ae) {


Object obj = ae.getSource();
if (obj == btnOk) { //If OK Button Pressed.

//Validating to Check All Required Information Provided or Not.


if (txtMemberId.getText().equals ("")) {
log.setText( "Member's Id not Provided.");
txtMemberId.requestFocus ();}

else if (txtMemberName.getText().equals ("")) {


log.setText( "Member's Name not Provided.");
txtMemberName.requestFocus ();}

108
else {try { //INSERT Query to Add Member Record in Table.
String q = "INSERT INTO Members" +" VALUES (" + newMemberId + ",'" +
txtMemberName.getText() + "', '" + todayDate + "',"+ 0 + ")";

int result = st.executeUpdate (q); //Running Query.


if (result == 1) { //If Query Successful.
log.setText( "Member "+newMemberId+" has been Saved.");
txtClear (); //Clearing the TextFields.
}
}
catch (SQLException sqlex)
{JOptionPane.showMessageDialog(this,sqlex.getMessage()); }}}

if (obj == btnCancel) { //If Cancel Button Pressed Unload the From.


setVisible (false);
dispose();}}

/*******************************************************************************
*when the user clicks on the member id field the focuslistener attached to that
field is activated and the following code is executed,the sql script gets all
columns from each row, but for each row that the next() command goes through
only the first field which contains the id of a member record is saved into
rowcount. at the end of the loop rowcount will be holding the id of the last
member record, the new member record should have an id which is larger than
the last member id by one, so the rowcount is incremented by 1 and its
converted to string before being set into the id textfield.
******************************************************************************/
public void focusGained (FocusEvent fe) {

try{

ResultSet getRowCount = st.executeQuery("SELECT * FROM Members");


// Get the number of rows from the result set

while (getRowCount.next()) {

rowcount = getRowCount.getInt(1);
System.out.print(rowcount);
}
rowcount++;
newMemberId = Integer.toString(rowcount);
txtMemberId.setText(newMemberId);
}catch(SQLException sqlex){
JOptionPane.showMessageDialog(this,sqlex.getMessage());
}}

109
public void focusLost (FocusEvent fe) {
log.setText("Enter The Name of Member " + newMemberId);}

private void txtClear () {


txtMemberId.setText ("");
txtMemberName.setText ("");
txtMemberId.requestFocus ();

public void keyTyped(KeyEvent ke) {

char c = ke.getKeyChar();
if (! ((Character.isLetter(c)) || (c == KeyEvent.VK_BACK_SPACE)||(c ==
KeyEvent.VK_SPACE))) {
getToolkit().beep();
ke.consume();}

public void keyPressed(KeyEvent ke) {}


public void keyReleased(KeyEvent ke) {}}

110
/*****************************UpdateBook.java***********************************
* provides interface and GUI for updating and changing Book records.
******************************************************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;

public class UpdateBook extends JInternalFrame implements ActionListener,


FocusListener, KeyListener {

private JPanel pBook = new JPanel ();


private JLabel lbBookId, lbBookName, lbBookAuthor;
private JTextField txtBookId, txtBookName, txtBookAuthor;
private JButton btnUpdate, btnCancel;
private Statement st; //Statement for Getting the Required Table.
private ResultSet rs; //For Getting the Records From Table.
private long id = 0,bissued; //To Hold the BookId.
private JTextField log;

//Constructor of Class.
public UpdateBook (Connection con) {

//super (Title, Resizable, Closable, Maximizable, Iconifiable)


super ("Update Book", false, true, false, true);
setSize (325, 205);
log = new JTextField();
log.setEditable(false);
log.setHorizontalAlignment(JTextField.CENTER);
getContentPane().add (log, BorderLayout.SOUTH);
//Setting the Form's Labels.
lbBookId = new JLabel ("Book Id:");
lbBookId.setBounds (15, 15, 100, 20);
lbBookName = new JLabel ("Book Name:");
lbBookName.setBounds (15, 45, 100, 20);
lbBookAuthor = new JLabel ("Book Author:");
lbBookAuthor.setBounds (15, 75, 100, 20);
txtBookId = new JTextField ();
txtBookId.setHorizontalAlignment (JTextField.RIGHT);
txtBookId.addFocusListener (this);
txtBookId.setBounds (120, 15, 175, 25);
txtBookId.addKeyListener(this);
txtBookName = new JTextField ();
txtBookName.setBounds (120, 45, 175, 25);
txtBookAuthor = new JTextField ();
txtBookAuthor.setBounds (120, 75, 175, 25);
btnUpdate = new JButton ("Update Book ");

111
btnUpdate.setBounds (25, 115, 125, 25);
btnUpdate.addActionListener (this);
btnCancel = new JButton ("Cancel");
btnCancel.setBounds (165, 115, 125, 25);
btnCancel.addActionListener(this);

pBook.setLayout (null);
pBook.add (lbBookId);
pBook.add (lbBookName);
pBook.add (lbBookAuthor);
pBook.add (txtBookId);
pBook.add (txtBookName);
pBook.add (txtBookAuthor);
pBook.add (btnUpdate);
pBook.add (btnCancel);

getContentPane().add (pBook);
try {st = con.createStatement (); //Creating Statement Object.
}
catch (SQLException sqlex) { //If Problem occurs Show the Message.
log.setText( "A Problem Has Occured.");
dispose ();} //Closing the Form.

setVisible (true);
}

/*******************************************************************************
if ok button is pressed then check to see if book is issued to a person,if yes
then do not update details, also if an id is not provided do not update details
and ask for ID,after the details have been changed update all fields to
database, except Id field.
******************************************************************************/
public void actionPerformed (ActionEvent ae) {
Object obj = ae.getSource();
if (obj == btnUpdate) { //If Update Button Pressed.
if (txtBookId.getText().equals ("")) {
log.setText("Book's Id not Provided.");
txtBookId.requestFocus ();}

else if(bissued!=0)
{txtClear();
log.setText("Book is held by a member");}

112
else{ try { //Update Query
st.executeUpdate("Update Books Set Book_Name ='"+txtBookName.getText()+"' WHERE
Book_Id ="+id+"");
st.executeUpdate("Update Books Set Book_Author ='"+txtBookAuthor.getText()+"'
WHERE Book_Id ="+id+"");
txtClear (); //Clering All TextFields.
log.setText("Update Complete.");
}catch (SQLException sqlex)
{JOptionPane.showMessageDialog(this,sqlex.getMessage()); }}}

else if (obj == btnCancel) {//If Cancel Button Pressed Unload the From.
setVisible (false);
dispose();}}

/*******************************************************************************
*when the user enters an id number for a book record and clicks outside of the
id textfield the focus is lost and following code is executed. the book id
provided by user is obtained and using sql script it is checked against the id
fields in the books table in the database.when a match is found the other
information which reside alongside the id in the database in the same row are
retrieved and inserted into the apropriate fields of the frame.
******************************************************************************/
public void focusGained (FocusEvent fe) { }
public void focusLost (FocusEvent fe) {
if (txtBookId.getText().equals ("")) {} //If TextField is Empty.
else { //Converting String to Numeric.
id = Integer.parseInt (txtBookId.getText ());
boolean found = false;//To Confirm the Book's Id Existance.
try {
log.setText("");
String q = "SELECT * FROM Books WHERE Book_Id = " + id + "";
ResultSet rs = st.executeQuery (q);
rs.next ();
long bookNo = rs.getLong ("Book_Id");
bissued=rs.getLong("Member_Id");
if (bookNo == id) {found = true;
txtBookId.setText ("" + id);
txtBookName.setText ("" + rs.getString ("Book_Name"));
txtBookAuthor.setText ("" + rs.getString ("Book_Author"));}
else {found = false;}}
catch (SQLException sqlex) {
if (found == false) {
txtClear ();
log.setText( "Book not Found.");
}}}}

113
private void txtClear () {
txtBookId.setText ("");
txtBookName.setText ("");
txtBookAuthor.setText ("");
txtBookId.requestFocus();
}

/*******************************************************************************
*since the book id field only takes numbers so a keylistener/adapter is set to
it which in case of user entering letters will consume the letters and only
allows numbers and backspace keycodes.
******************************************************************************/
public void keyTyped(KeyEvent ke) {

char c = ke.getKeyChar ();


if (! ((Character.isDigit (c)) || (c == KeyEvent.VK_BACK_SPACE))) {
getToolkit().beep ();
ke.consume ();
}}

public void keyPressed(KeyEvent ke) {}


public void keyReleased(KeyEvent ke) {} }

114
/*******************************UpdateMember.java*******************************
*this class provides GUI and interface for updating member details.
******************************************************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;

public class UpdateMember extends JInternalFrame implements ActionListener,


FocusListener, KeyListener {

private JPanel pMember = new JPanel ();


private JLabel lbMemberId, lbMemberName, lbRegistrationDate;
private JTextField txtMemberId, txtMemberName, txtRegistrationDate;
private JButton btnUpdate, btnCancel;
private Statement st; //Statement for Getting the Required Table.
private ResultSet rs; //For Getting the Records From Table.
private long id = 0,heldBooks; //To Hold the MemberId.
private JTextField log;

//Constructor of Class.
public UpdateMember (Connection con) {

//super (Title, Resizable, Closable, Maximizable, Iconifiable)


super ("Update Member", false, true, false, true);
setSize (325, 205);

log = new JTextField();


log.setEditable(false);
log.setHorizontalAlignment(JTextField.CENTER);
getContentPane().add (log, BorderLayout.SOUTH);
lbMemberId = new JLabel ("Member Id:");
lbMemberId.setBounds (15, 15, 100, 20);
lbMemberName = new JLabel ("Member Name:");
lbMemberName.setBounds (15, 45, 100, 20);
lbRegistrationDate = new JLabel ("Entry Date:");
lbRegistrationDate.setBounds (15, 75, 100, 20);
txtMemberId = new JTextField ();
txtMemberId.setHorizontalAlignment (JTextField.RIGHT);
txtMemberId.addFocusListener (this);
txtMemberId.setBounds (120, 15, 175, 25);
txtMemberId.addKeyListener(this);
txtMemberName = new JTextField ();
txtMemberName.setBounds (120, 45, 175, 25);
txtRegistrationDate=new JTextField();
txtRegistrationDate.setBounds(120, 75, 175, 25);
//txtRegistrationDate.setEditable(false);
btnUpdate = new JButton ("Update Member");

115
btnUpdate.setBounds (25, 115, 125, 25);
btnUpdate.addActionListener (this);
btnCancel = new JButton ("Cancel");
btnCancel.setBounds (165, 115, 125, 25);
btnCancel.addActionListener (this);

//Adding All the Controls in Panel.


pMember.setLayout (null);
pMember.add (lbMemberId);
pMember.add (lbMemberName);
pMember.add (lbRegistrationDate);
pMember.add (txtMemberId);
pMember.add (txtMemberName);
pMember.add (txtRegistrationDate);
pMember.add (btnUpdate);
pMember.add (btnCancel);
getContentPane().add (pMember, BorderLayout.CENTER);

try {st = con.createStatement (); } //Creating Statement Object.


catch (SQLException sqlex) { //If Problem then Show the User a Message.
JOptionPane.showMessageDialog (null, sqlex.getMessage());
dispose ();} //Closing the Form.

setVisible (true);}

/*******************************************************************************
*if event is created by ok button or cancel button it is handled in the
following interface.before the following is executed the focuslistener
interface will obtain the details of a current member by searching the members
ID in the database and insert the details of the member into the appropriate
textfields. but after the details are entered in the fields if user chooses ok
button, first will check if the fields are empty.if yes, will ask for details.
if they are not empty then it will check if member is holding books. if member
is not holding any books then sql script will update the fields which the user
has modified into the database using the unique member ID. member IDs are set
in a way so they cannot be updated or changed in order to preserve uniquness.
******************************************************************************/
public void actionPerformed (ActionEvent ae) {
Object obj = ae.getSource();
if (obj == btnUpdate) {
//If Update Button Pressed.
if (txtMemberId.getText().equals ("")) {
log.setText("Member's Id not Provided.");

116
txtMemberId.requestFocus ();}
else if(heldBooks!=0)
{
log.setText("Member is Holding Books..Can't Update Record");
txtClear();}

else{
try {

st.executeUpdate("Update Members Set Member_Name ='"+txtMemberName.getText()+"'


WHERE Member_Id ="+id+"");

st.executeUpdate("Update Members Set Registration_Date


='"+txtRegistrationDate.getText()+"' WHERE Member_Id ="+id+"");

txtClear (); //Clearing the TextFields.


log.setText("Update Complete.");
} //Executing the Query.

catch (SQLException sqlex) { }}}


else if(obj == btnCancel){ //If Cancel Button Pressed Unload the
From.
setVisible (false);
dispose();}}

/*******************************************************************************
*the user clicks on member id field and enters an ID, then he will click on the
next field or anywhere else on the update frame, as the member id field loses
focus the following code is run.first member id entered by user is retrieved
and the details of the member with the provided user ID is retreved form the
database and inserted into the appropriate fields of the update member frame.
******************************************************************************/
public void focusGained (FocusEvent fe) { }
public void focusLost (FocusEvent fe) {
if (txtMemberId.getText().equals ("")) { }
else {
id = Integer.parseInt (txtMemberId.getText ());
boolean found = false;
try {
String q = "SELECT * FROM Members WHERE Member_Id = " + id + "";
ResultSet rs = st.executeQuery (q);
rs.next ();
long memberNo = rs.getLong ("Member_Id");
heldBooks=rs.getLong("Book_Count");
if (memberNo == id) {

txtMemberId.setText (""+id);
txtMemberName.setText ("" + rs.getString ("Member_Name"));
117
txtRegistrationDate.setText(""+rs.getString("Registration_Date"));
}
else {found = false;}}
catch (SQLException sqlex) { if (found == false) {
txtClear ();
log.setText("Record not Found.");
}}}}
private void txtClear () {
txtMemberId.setText ("");
txtMemberName.setText ("");
txtRegistrationDate.setText("");
txtMemberId.requestFocus ();}

/*******************************************************************************
keylistener/adapter is set to only allow numbers and backspace keycodes.
******************************************************************************/
public void keyTyped(KeyEvent ke) {

char c = ke.getKeyChar ();


if (! ((Character.isDigit (c)) || (c == KeyEvent.VK_BACK_SPACE))) {
getToolkit().beep ();
ke.consume ();
}}
public void keyPressed(KeyEvent ke) {}
public void keyReleased(KeyEvent ke) {} }

118
/*****************************DeleteMember.java*********************************
*creates gui and interface for the delete member jinternalframe and allows user
to delete member records from the member table in the database.
******************************************************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;

public class DeleteBook extends JInternalFrame implements ActionListener,


FocusListener, KeyListener {

private JPanel pBook = new JPanel ();


private JLabel lbBookId, lbBookName, lbBookAuthor;
private JTextField txtBookId, txtBookName, txtBookAuthor;
private JButton btnDel, btnCancel;
private Statement st; //Statement for Getting the Required Table.
private ResultSet rs; //For Getting the Records From Table.
private long id = 0,bissued; //To Hold the BookId.
private JTextField log;

public DeleteBook (Connection con) {

//super (Title, Resizable, Closable, Maximizable, Iconifiable)


super ("Delete Book", false, true, false, true);
setSize (325, 205);

//create gui of the frame,using absolute positioning


log = new JTextField();
log.setHorizontalAlignment(JTextField.CENTER);
log.setEditable(false);
lbBookId = new JLabel ("Book Id:");
lbBookId.setBounds (15, 15, 100, 20);
lbBookName = new JLabel ("Book Name:");
lbBookName.setBounds (15, 45, 100, 20);
lbBookAuthor = new JLabel ("Book Author:");
lbBookAuthor.setBounds (15, 75, 100, 20);
txtBookId = new JTextField ();
txtBookId.setHorizontalAlignment (JTextField.RIGHT);
txtBookId.addFocusListener (this);
txtBookId.setBounds (120, 15, 175, 25);
txtBookId.addKeyListener(this);
txtBookName = new JTextField ();
txtBookName.setEditable(false);
txtBookName.setBounds (120, 45, 175, 25);
txtBookAuthor = new JTextField ();

119
txtBookAuthor.setEditable(false);
txtBookAuthor.setBounds (120, 75, 175, 25);
btnDel = new JButton ("Delete Book");
btnDel.setBounds (25, 115, 125, 25);
btnDel.addActionListener (this);
btnCancel = new JButton ("Cancel");
btnCancel.setBounds (165, 115, 125, 25);
btnCancel.addActionListener (this);

pBook.setLayout (null);
pBook.add (lbBookId);
pBook.add (lbBookName);
pBook.add (lbBookAuthor);
pBook.add (txtBookId);
pBook.add (txtBookName);
pBook.add (txtBookAuthor);
pBook.add (btnDel);
pBook.add (btnCancel);
getContentPane().add (log, BorderLayout.SOUTH);
getContentPane().add (pBook);

try {st = con.createStatement (); //Creating Statement Object.


}
catch (SQLException sqlex) { //If Problem occurs Show the Message.
JOptionPane.showMessageDialog(this,(sqlex.getMessage()));
dispose ();} //Closing the Form.

setVisible (true); }

/*******************************************************************************
if user clicks on the delete button check and see that a member id is provided,
if bissued is not zero then whatever number it is, it is corresponding to a
member ID and this means that this book is being held by that member.
so prevent user from deleting the member record, if all checks are ok then
delete the record from database where the Ids match.
*******************************************************************************/

public void actionPerformed (ActionEvent ae) {


Object obj = ae.getSource();
if (obj == btnDel) { //If Delete Button Pressed.
if (txtBookId.getText().equals ("")) {
log.setText("Book's Id not Provided.");
txtBookId.requestFocus ();}
else if(bissued!=0)
{

txtClear();
120
log.setText("Book is held by a member");}
else{
try { //delete record from table.
String q = "DELETE FROM Books WHERE Book_Id = " + id + "";
txtClear (); //clering all textFields.
log.setText("Book "+id+" has been Deleted.");
ResultSet rs = st.executeQuery (q);} //Running Query.
catch (SQLException sqlex) { }}
if (obj == btnCancel) {//If Cancel Button Pressed Unload the From.
setVisible (false);
dispose();}}}

public void focusGained (FocusEvent fe) {}

121
/*******************************************************************************
*get the id entered by user and find a match for the Id in the database by
using sql script if a match is found then get the member_ID from the same row,
if the member_id is not zero,this means the book is held by a member whose id
number has taken the place of zero in that column,this will be used to prevent
user from deleting book records.set the id of the member along with the member
name into the appropriate fields.if a match for the id is not found in the
database then an sqlException is thrown, catch the sql exception and inform
the user that member does not exist in the database.
******************************************************************************/
public void focusLost (FocusEvent fe) {
log.setText("");
id = Integer.parseInt (txtBookId.getText ());
long bookNo; //Use for Comparing the Book's Id.
boolean found = false;//To Confirm the Book's Id Existance.
try { //SELECT Query to Retrieved the Record.

String q = "SELECT * FROM Books WHERE Book_Id = " + id + "";


ResultSet rs = st.executeQuery (q); //Executing the Query.
rs.next (); //Moving towards the Record.
bissued=rs.getLong("Member_Id");
txtBookId.setText ("" + id);
txtBookName.setText ("" + rs.getString ("Book_Name"));
txtBookAuthor.setText ("" + rs.getString ("Book_Author"));}

catch (SQLException sqlex){

txtClear (); //Clearing the TextFields.


log.setText("Book not Found.");
}}

//Function Use to Clear All the TextFields of Form.


private void txtClear () {
txtBookId.setText ("");
txtBookName.setText ("");
txtBookAuthor.setText ("");
txtBookId.requestFocus();
}
public void keyTyped(KeyEvent ke) {
char c = ke.getKeyChar ();
if (! ((Character.isDigit (c)) || (c == KeyEvent.VK_BACK_SPACE))) {
getToolkit().beep ();
ke.consume ();}}
public void keyPressed(KeyEvent ke) {}
public void keyReleased(KeyEvent ke) {} }

122
/******************************DeleteMember.java********************************
creates gui and interface for the delete member jinternalframe and allows user
to delete member records from the member table in the database.
******************************************************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;

public class DeleteBook extends JInternalFrame implements ActionListener,


FocusListener, KeyListener {

private JPanel pBook = new JPanel ();


private JLabel lbBookId, lbBookName, lbBookAuthor;
private JTextField txtBookId, txtBookName, txtBookAuthor;
private JButton btnDel, btnCancel;
private Statement st; //Statement for Getting the Required Table.
private ResultSet rs; //For Getting the Records From Table.
private long id = 0,bissued; //To Hold the BookId.
private JTextField log;
.
public DeleteBook (Connection con) {

//super (Title, Resizable, Closable, Maximizable, Iconifiable)


super ("Delete Book", false, true, false, true);
setSize (325, 205);

//create gui of the frame

log = new JTextField();


log.setHorizontalAlignment(JTextField.CENTER);
log.setEditable(false);
lbBookId = new JLabel ("Book Id:");
lbBookId.setBounds (15, 15, 100, 20);
lbBookName = new JLabel ("Book Name:");
lbBookName.setBounds (15, 45, 100, 20);
lbBookAuthor = new JLabel ("Book Author:");
lbBookAuthor.setBounds (15, 75, 100, 20);
txtBookId = new JTextField ();
txtBookId.setHorizontalAlignment (JTextField.RIGHT);
txtBookId.addFocusListener (this);
txtBookId.setBounds (120, 15, 175, 25);
txtBookId.addKeyListener(this);
txtBookName = new JTextField ();
txtBookName.setEditable(false);
txtBookName.setBounds (120, 45, 175, 25);
txtBookAuthor = new JTextField ();

123
txtBookAuthor.setEditable(false);
txtBookAuthor.setBounds (120, 75, 175, 25);
btnDel = new JButton ("Delete Book");
btnDel.setBounds (25, 115, 125, 25);
btnDel.addActionListener (this);
btnCancel = new JButton ("Cancel");
btnCancel.setBounds (165, 115, 125, 25);
btnCancel.addActionListener (this);
pBook.setLayout (null);
pBook.add (lbBookId);
pBook.add (lbBookName);
pBook.add (lbBookAuthor);
pBook.add (txtBookId);
pBook.add (txtBookName);
pBook.add (txtBookAuthor);
pBook.add (btnDel);
pBook.add (btnCancel);
getContentPane().add (log, BorderLayout.SOUTH);
getContentPane().add (pBook);

try {st = con.createStatement (); //Creating Statement Object.


}
catch (SQLException sqlex) { //If Problem occurs Show the Message.
JOptionPane.showMessageDialog(this,(sqlex.getMessage()));
dispose ();} //Closing the Form.
setVisible (true);}

/*******************************************************************************
if user clicks on the delete button check and see that a member id is provided,
if bissued is not zero then whatever number it is, it is corresponding to a
member ID and this means that this book is being held by that member. so
prevent user from deleting the member record, if all checks are ok then delete
the record from database where the Ids match.
******************************************************************************/

public void actionPerformed (ActionEvent ae) {


Object obj = ae.getSource();
if (obj == btnDel) { //If Delete Button Pressed.
if (txtBookId.getText().equals ("")) {
log.setText("Book's Id not Provided.");
txtBookId.requestFocus ();}
else if(bissued!=0)
{txtClear();
log.setText("Book is held by a member");}
else{
try { //delete record from table.
String q = "DELETE FROM Books WHERE Book_Id = " + id + "";

124
txtClear (); //clering all textFields.
log.setText("Book "+id+" has been Deleted.");
ResultSet rs = st.executeQuery (q);} //Running Query.
catch (SQLException sqlex) { }}
if (obj == btnCancel) {//If Cancel Button Pressed Unload the From.
setVisible (false);
dispose();}}}

public void focusGained (FocusEvent fe) {}

125
/*******************************************************************************
get the id entered by user and find a match for the Id in the database by using
sql script if a match is found then get the member_ID from the same row, if the
member_id is not zero,this means the book is held by a member whose id number
has taken the place of zero in that column, this will be used to prevent user
from deleting book records. set the id of the member along with the member name
into the appropriate fields.if a match for the id is not found in the database
then an sqlException is thrown, catch the sql exception and inform the user
that member does not exist in the database.
******************************************************************************/
public void focusLost (FocusEvent fe) {
log.setText("");
id = Integer.parseInt (txtBookId.getText ());
long bookNo; //Use for Comparing the Book's Id.
boolean found = false;//To Confirm the Book's Id Existance.
try { //SELECT Query to Retrieved the Record.

String q = "SELECT * FROM Books WHERE Book_Id = " + id + "";


ResultSet rs = st.executeQuery (q); //Executing the Query.
rs.next (); //Moving towards the Record.
bissued=rs.getLong("Member_Id");
txtBookId.setText ("" + id);
txtBookName.setText ("" + rs.getString ("Book_Name"));
txtBookAuthor.setText ("" + rs.getString ("Book_Author"));}

catch (SQLException sqlex){

txtClear (); //Clearing the TextFields.


log.setText("Book not Found.");}}
//Function Use to Clear All the TextFields of Form.
private void txtClear () {
txtBookId.setText ("");
txtBookName.setText ("");
txtBookAuthor.setText ("");
txtBookId.requestFocus();
}
//prevent user from entering non digit characters into id field

public void keyTyped(KeyEvent ke) {


char c = ke.getKeyChar ();
if (! ((Character.isDigit (c)) || (c == KeyEvent.VK_BACK_SPACE))) {
getToolkit().beep ();
ke.consume ();
} }
public void keyPressed(KeyEvent ke) {}
public void keyReleased(KeyEvent ke) {} }

126
/*****************************LaonedBooksReport.java****************************
*this file will create a report consisting of a table viewed in a scrollpane,
*the report consists of the books that are currently on loan to members and
*have not been returned yet, the data for creating the report is retrieved from
*the loaned table in database.
******************************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.*;

public class LoanedBooksReport extends JInternalFrame{

private JPanel p = new JPanel ();


private Statement st;
private Object data[][];
public int rowcount=0;
private JScrollPane scroller;
public LoanedBooksReport (Connection con) {

//super (Title, Resizable, Closable, Maximizable, Iconifiable)


super ("Loaned Books Report", true, true, false, true);
setSize (650,350);
p.setLayout (null);
getContentPane().add (p);
try {
st = con.createStatement (); //Creating Statement Object.
// Get the number of rows from the Loaned Table
ResultSet resultSet = st.executeQuery("SELECT COUNT(*) FROM Loaned");

resultSet.next();
//rowcount will hold the number of rows in loaned table
rowcount = resultSet.getInt(1);

}catch(SQLException sqlex) {
JOptionPane.showMessageDialog (this,sqlex.getMessage());}

try{

//2 dimensional array (array of arrays) to store the data from the Loaned table.
data=new Object[rowcount][6];

//these will be set as the jtables column headers


Object[] columnNames={"Book Id","Book Name","Member ID","Member Name","Issue
Date","Status"};

//asterisk is used here to select all columns

127
ResultSet rs=st.executeQuery("Select * from Loaned");
//starts at row 0
for(int row=0;row<rowcount;row++)
{rs.next();
//starts at column 0 and ie.0,1,2,3,4,5
for(int column=0;column<6;column++)
{//gets the column data from table and stores it in the second dimension of the
array
//starts at (column+1)=(0+1)= 1 because in the resultset data is stored at
location 1.

data[row][column]=rs.getString(column+1);}}

//constructor accepts array of objects JTable(Object[][] rowData, Object[]


columnNames);
JTable table=new JTable(data,columnNames);
scroller = new JScrollPane (table); //Adding Table to ScrollPane.
scroller.setBounds (0, 0, 650, 350); //Aligning ScrollPane.
p.add(scroller);}
catch (SQLException sqlex) { //If Problem then Show the
User a Message.
JOptionPane.showMessageDialog (null, "A Problem Occurs While Loading Form.");
dispose ();} //Closing the Form.
setVisible (true);}}

128
/********************************BooksReport.java*******************************
* retreives all records from the books table and creates a table report
* and inserts it inside an scroll pane container for easy viewing.
******************************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.*;

public class BooksReport extends JInternalFrame {

private JPanel p = new JPanel ();


private Statement st;
private Object data[][];
public int rowcount=0;
private JScrollPane scroller;
public BooksReport (Connection con) {

//super (Title, Resizable, Closable, Maximizable, Iconifiable)

super ("All Books Report", true, true, false, true);


setSize (660,280);
p.setLayout (null);
getContentPane().add (p);
try {st = con.createStatement (); //Creating Statement Object.
// Get the number of rows from the result set
ResultSet resultSet = st.executeQuery("SELECT COUNT(*) FROM Books");
resultSet.next();
rowcount = resultSet.getInt(1);
}catch(SQLException sqlex) {
JOptionPane.showMessageDialog (this, sqlex.getMessage());}

try{ data=new Object[rowcount][6];


//these will be set as the jtables column headers
Object[] Colheads={"Book Id","Book Name","Book Author","Member ID","Last Issue
Date","Last Return Date"};
//asterisk is used here to select all columns
ResultSet rs=st.executeQuery("Select * from Books");
//starts at row 0

for(int row=0;row<rowcount;row++)
{ rs.next();
//starts at column 0 and ie.0,1,2,3,4,5
for(int column=0;column<6;column++)
{data[row][column]=rs.getString(column+1);}}
//constructor accepts array of objects JTable(Object[][] rowData, Object[]
columnNames);
129
JTable table=new JTable(data,Colheads);
scroller = new JScrollPane (table); //Adding Table to ScrollPane.
scroller.setBounds (0, 0, 650, 270); //Aligning ScrollPane.
p.add(scroller);
} catch (SQLException sqlex) { //If Problem then Show the
User a Message.
JOptionPane.showMessageDialog (null,sqlex.getMessage());
dispose (); //Closing the Form.
}
setVisible (true);}

130
/********************************MembersReport.java*************************
* retreives all records from the members table and creates a table report
* and inserts it inside an scroll pane container for easy viewing.
**************************************************************************/

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.*;

public class MembersReport extends JInternalFrame{

private JPanel p = new JPanel ();


private Statement st;
private Object data[][];
public int rowcount=0;
private JScrollPane scroller;
public MembersReport (Connection con) {

//super (Title, Resizable, Closable, Maximizable, Iconifiable)


super ("Members Report", true, true, false, true);
setSize (580,280);
p.setLayout (null);
getContentPane().add (p);

try {
st = con.createStatement ();
ResultSet resultSet = st.executeQuery("SELECT COUNT(*) FROM Members");
resultSet.next();
rowcount = resultSet.getInt(1);
}catch(SQLException sqlex) {

JOptionPane.showMessageDialog (this, "Record not Found.");


}
try{
//creates two dimensional array each rowcount will have 4 columns
data=new Object[rowcount][4];
Object[] columnNames={"Member Id","Member Name","Registration Date","Book Count"};
ResultSet rs=st.executeQuery("Select * from Members");
//starts at row 0
for(int row=0;row<rowcount;row++)
{ rs.next();

//starts at column 0 and ie.0,1,2,3


for(int column=0;column<4;column++)
{

131
/*gets the column data from table and stores it in the second dimension of the
array, starts at (colums+1)=(0+1)= 1 because in the resultset data is stored at
location 1.*/

data[row][column]=rs.getString(column+1);}

/*constructor accepts array of objects JTable(Object[][] rowData, Object[]


columnNames);*/

JTable table=new JTable(data,columnNames);


scroller = new JScrollPane (table); //Adding Table to ScrollPane.
scroller.setBounds (0, 0, 570, 270); //Aligning ScrollPane.
p.add(scroller);}

catch (SQLException sqlex) { //If Problem then Show the User a Message.
JOptionPane.showMessageDialog (null, sqlex.getMessage());
dispose (); //Closing the Form.
}

setVisible (true);}}

132
/************************************AddAdmin.java******************************
* allows the user to create new admin accounts.
******************************************************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import javax.swing.filechooser.*;
import java.io.*;

//create the log on window and implement the actionlistener interface


public class AddAdmin extends JInternalFrame implements ActionListener,KeyListener
{

//panel or the background, used to add other components


private JPanel Panel = new JPanel();
//username and password labels
private JLabel noticeLabel, noticeLabel2;
//username and password labels
private JLabel sessionPasslbl,userLabel, passLabel;
private JTextField userName;
private JButton okButton, cancelButton;
private Connection con;
private Statement st;
//to hide password from undesirables
private JPasswordField passText,newPass;
private String sessionPass,sessionUser;
//get the size of the user's screen
public Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();

public AddAdmin (Connection con,String p, String u) {


super("Create New Admin");

sessionPass = p;
sessionUser = u;
setSize (275, 280);
setResizable (false);

//default window, close operation


//exit the program when frame is closed
this.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );

//Setting the Logon Form Position on User's Screen.

133
setLocation (dimension.width/2 - getWidth()/2,dimension.height/3-getHeight()/2);

//Setting the Form's Labels.


noticeLabel = new JLabel (" USER [ "+sessionUser+" ] Verify Your Password:");

noticeLabel.setBounds (20, 10, 220, 25);


noticeLabel2 = new JLabel ("Enter The New Admin's Log In Details :");

noticeLabel2.setBounds (20, 90, 220, 25);

//Setting the Form's TextField & PasswordField.

sessionPasslbl = new JLabel("Password:");


sessionPasslbl.setBounds (20, 45, 150, 25);

passText = new JPasswordField ();


passText.setBounds (100, 45, 150, 25);

//Setting the Form's Labels.


userLabel = new JLabel ("User ID:");

userLabel.setBounds (20, 130, 75, 25);


passLabel = new JLabel ("Password:");

passLabel.setBounds (20, 165, 75, 25);

//Setting the Form's TextField & PasswordField.


userName = new JTextField ();
userName.setBounds (100, 130, 150, 25);
userName.addKeyListener(this);

newPass= new JPasswordField ();


newPass.setBounds (100, 165, 150, 25);

//Setting the Form's Buttons.


okButton = new JButton ("OK");
okButton.setBounds (20, 205, 100, 25);
okButton.addActionListener (this);
cancelButton = new JButton ("Cancel");
cancelButton.setBounds (150, 205, 100, 25);
cancelButton.addActionListener (this);

//to manually layout components, layout manager is set to null

134
Panel.setLayout (null);

//addig components to panel


Panel.add (noticeLabel);
Panel.add(noticeLabel2);
Panel.add(sessionPasslbl);
Panel.add (userLabel);
Panel.add (passLabel);
Panel.add (userName);
Panel.add (passText);
Panel.add (newPass);
Panel.add (okButton);
Panel.add (cancelButton);

/*before executing sql scripts a database connection first needs to be made*/

try {st = con.createStatement ();}


catch (SQLException sqlex) {
JOptionPane.showMessageDialog(this,(sqlex.getMessage()));
dispose (); }

getContentPane().add (Panel);
setVisible (true);

}//end of login()

/*******************************************************************************
in order to allow the user to create new admin accounts, first the user has to
prove his identity.user will write his password inside the frame, and also
would write the new accounts uer id and pass into the appropriate fields,if the
user@s pass is correct then the new account will be created.
******************************************************************************/
public void actionPerformed (ActionEvent ae) {

//get the source of action either cancel or ok buttons


Object Choice = ae.getSource();

if (Choice == cancelButton) { //If Cancel Button Pressed

135
setVisible (false); //Unload the From.
dispose(); }

else if (Choice == okButton) {


String password = new String (passText.getPassword());

//if the users pass matches the pass used to start the system, then
if(password.equals(sessionPass)) {

String NewPassword = new String (newPass.getPassword());


if (userName.getText().equals ("")) {
userName.requestFocus();
JOptionPane.showMessageDialog (this, "Enter the new account's User ID
");}
else if (password.equals ("")) {
newPass.requestFocus();
JOptionPane.showMessageDialog (this, "Enter a Password for the new
account");}
else {try { //INSERT Query to Add Book Record to Table.

String q = "INSERT INTO Admins " +"VALUES ('" + userName.getText() + "', '" +
NewPassword + "', '" + sessionUser+ "')";
int rs = st.executeUpdate (q); //Run Query.
if (rs == 1) { //If Query was Successful.

JOptionPane.showMessageDialog (this, "Admin Account [ "+userName.getText()+"


] Was Created.");

userName.setText ("");
newPass.setText ("");
passText.setText("");
passText.requestFocus ();}

else { //If Query Failed.


JOptionPane.showMessageDialog (this, "Problem while Creating the
Admin.");
userName.setText ("");
newPass.setText ("");
userName.requestFocus ();}}
catch (SQLException sqlex) {
JOptionPane.showMessageDialog(this,sqlex.getMessage());}}}

else {

if(password.equals("")){ JOptionPane.showMessageDialog(this,"Please enter


your password");}

136
else{JOptionPane.showMessageDialog (this, "Wrong Password.");}}

passText.setText ("");
passText.requestFocus ();
}}

/*to prevent the user from entering letters into the username field
*the user names are all integers and have to be digits or numbers*/
public void keyTyped(KeyEvent ke) {

char c = ke.getKeyChar ();


if (! ((Character.isDigit (c)) || (c == KeyEvent.VK_BACK_SPACE))) {
getToolkit().beep ();
ke.consume ();}
}

public void keyPressed(KeyEvent ke) {}


public void keyReleased(KeyEvent ke) {}

137
/*************************************BackUp.java*******************************
this class provides the GUI and interface for creating back up copies of the
database.
******************************************************************************/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import javax.swing.filechooser.*;
import java.io.*;

//create the log on window and implement the actionlistener interface


public class BackUp extends JInternalFrame implements ActionListener {

private JPanel Panel = new JPanel();


private JLabel noticeLabel;
private JButton okButton, cancelButton;
private Connection con; //database connection
private JPasswordField passText;
private String sessionPass,sessionUser;
private JFileChooser fc;
public Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
private JTextField log;

public BackUp (String pass,String user) {


super("Back Up Database");
//have to be assigned and copied to new variables.
sessionPass = pass;
sessionUser = user;
//seting the name and size of the logon window
setSize (260, 180);
setResizable (false);
log = new JTextField ();
log.setEditable(false);
log.setHorizontalAlignment(JTextField.CENTER);
//Create a file chooser and set it to view only directories
fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//default window, close operation
//exit the program when frame is closed
this.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
//Setting the Logon Form Position on User's Screen.
setLocation (dimension.width/2 - getWidth()/2,dimension.height/3-getHeight()/2);
//Setting the Layout of Panel.
Panel.setLayout (null);
//Setting the Form's Labels.
noticeLabel = new JLabel ("User ["+ user+"] Enter Your Password:");

138
noticeLabel.setBounds (15, 15, 220, 25);
//Setting the Form's TextField & PasswordField.
passText = new JPasswordField ();
passText.setBounds (50, 50, 150, 25);
//Setting the Form's Buttons.
okButton = new JButton ("OK");
okButton.setBounds (15, 90, 100, 25);
okButton.addActionListener (this);
cancelButton = new JButton ("Cancel");
cancelButton.setBounds (135, 90, 100, 25);
cancelButton.addActionListener (this);
//Adding All the Controls in Panel.
Panel.add (noticeLabel);
Panel.add (passText);
Panel.add (okButton);
Panel.add (cancelButton);
//Adding Panel to the Form.
getContentPane().add (Panel);
getContentPane().add (log, BorderLayout.SOUTH);
//Show The Logon Form.
setVisible (true);}//end of login()
/*******************************************************************************
above has already created a frame which asks for the administrators password.
when user enters his password then user will either choose ok or cancel,
in case of action events being created by the cancel burron or ok button,
the following will attempt to control these events. if the user clicks on
the OK button, the code will check the password against the password that
has started this session which was passed to this process from mainwidow class.
if correct then a filechooser is made visible. the user chooses a directory
using that file chooser and clicks on save. an input stream is set to the
original database file. an output stream is set to the directory which is
chosen by the user.a loop that has an byte buffer array embeded inside will copy
byte_by_byte the contents of input stream to output stream.
*******************************************************************************/
public void actionPerformed (ActionEvent ae) {
Object Choice = ae.getSource();

if (Choice == cancelButton) { //If Cancel Button Pressed

setVisible (false); //Unload the From.


dispose(); }

else if (Choice == okButton) { //If OK Button Pressed.

String password = new String (passText.getPassword());


String Pass; //To Hold the Password.
String User;

139
if(password.equals("")) {log.setText("Please Provide a Password.");}

else if(password.equals(sessionPass)){

dispose();

//show the file chooser and set the return value rs


int rs = fc.showSaveDialog(this);

//using return value rs check for the users choice, if user chooses save
(code 0) then
if (rs == JFileChooser.APPROVE_OPTION) {

//filechooser was set earlier to view only directories,getselectedfile


will return a directory pathname
File directory = fc.getSelectedFile();

try{
//set the library.mdb file as the input stream
InputStream in = new FileInputStream("Database/Library.mdb");

/*set the users directory of choice and append the original name of the file to
create exact copy*/
OutputStream out = new FileOutputStream(directory+"\\Library.mdb");

//byte buffer
byte[] buf = new byte[1024];

//while there is still a bytes to be read into the buffer


//reads next byte of data from stream into byte array
while (in.read(buf) > 0) {
//write the byte out to the destination
out.write(buf);}

//close streams
in.close();
out.close();

//print out success message of directory+predefined file name and extension


JOptionPane.showMessageDialog(this, "Database Backed Up to:\n\n

140
"+directory+"\\Library.mdb");

//if an error occurs then show the type of error


} catch(Exception e){JOptionPane.showMessageDialog(this,e.getMessage());}
}}

else {
//if password was not right else show message wrong password
log.setText("Wrong Password.");

passText.setText ("");
passText.requestFocus ();
}}}}

141
142
143
144

You might also like