You are on page 1of 16

OPAC SYSTEM USING EVENT DRIVEN AND CONCURRENT PROGRAMMING Aim: Develop a simple OPAC system for library

using even-driven and concurrent programming paradigms of Java. Use JDBC to connect to a back-end database. Algorithm: 1. Create a OPAC library system application using swing and provide a actionListener 2. Create two search categories such as searching by author or book name 3. Also provide methods to edit,update,add and delete records 4. Display the table of contents using JDBC connectivity of an existing database 5. Provide a text field to enter the search items 6. Using the resultset obtain the contents of the database as per the search key 7. Invoke the application by calling the Library class PROGRAM CODING: import java.awt.*; import java.awt.event.*; import java.sql.*; import java.applet.*; import javax.swing.*; //////////////Creates the main window with top Menu toolbar. /////////////This is also the class for the main declaration public class Library extends Frame { public Library() { initComponents(); } public void initComponents() { //Creates menu bar and add it to frame menubar = new MenuBar(); setMenuBar(menubar); //Create File menu with Items Menu file = new Menu("File"); MenuItem item1; file.add(item1 = new MenuItem("Exit")); menubar.add(file); //Creates Records menu with items Menu names = new Menu("Records"); MenuItem item2,item3,item4,item5; names.add(item2 = new MenuItem("Add...")); names.add(item3 = new MenuItem("Edit...")); names.add(item4 = new MenuItem("Delete...")); names.add(item5 = new MenuItem("Search...")); menubar.add(names); //Create an object to handle window events myWindowAdapter adapter = new myWindowAdapter(this); addWindowListener(adapter); //Create an object to handle action and item events myMenuHandler handler = new myMenuHandler(this);

//register it to receive events item1.addActionListener(handler); item2.addActionListener(handler); item3.addActionListener(handler); item4.addActionListener(handler); item5.addActionListener(handler); } //Variable declaration private Menu menu; private MenuBar menubar; /////////// This is the main declaration public static void main(String args[]) { //Creates main window, sets Title, Height and Width and Visibility Library appBook = new Library(); appBook.setTitle("A OPAC LIBRARY SYSTEM"); appBook.setSize(400, 300); appBook.setBackground(Color.WHITE); appBook.setVisible(true); }} //////////This Class handles the event for closing the main program window class myWindowAdapter extends WindowAdapter { Library appbook; public myWindowAdapter(Library appbook) { this.appbook = appbook; } public void windowClosing(WindowEvent we) { appbook.setVisible(false); appbook.dispose(); }} ////////////This creates the Add New Book Dialog for entering new data into the database. class AddDlg extends Dialog implements ActionListener { TextField Name1,Bookno1,Author1,Publication1; Button BtnOK,BtnCn; public AddDlg(Library parent, String title) { //Sets the way that the Dialog will look on screen super(parent, title, true); setLayout(new GridLayout(5,3,10,20)); setSize(300,250); setResizable(false); //Creates new Labels to describe the text boxes. Label Name,Bookno,Author,Publication;

Name = new Label("Name: "); Bookno = new Label("Bookno: "); Author = new Label("Author: "); Publication = new Label("Publication: "); //Creates TextBoxes for the user to enter data into Name1 = new TextField(10); Bookno1 = new TextField(10); Author1 = new TextField(20); Publication1 = new TextField(10); BtnOK = new Button("OK"); BtnCn = new Button("Cancel"); //Creates Listeners for Buttons BtnOK.addActionListener(this); BtnCn.addActionListener(this); //Creates spacer labels for the GridLayout Label space1,space2,space3,space4,space5; space1 = new Label(" "); space2 = new Label(" "); space3 = new Label(" "); space4 = new Label(" "); space5 = new Label(" "); //Adds new Labels, Textboxes and Button add(Name); add(Name1); add(space1); add(Bookno); add(Bookno1); add(space2); add(Author); add(Author1); add(space3); add(Publication); add(Publication1); add(space4); add(space5); add(BtnOK); add(BtnCn); } //////////////This method hales all the events that take place on the dialog public void actionPerformed(ActionEvent e) { String str = e.getActionCommand(); if (str.equals("OK")){ ToDataBase(); } if (str.equals("Cancel")) {

dispose(); }} ///////////////Open a connection to the LibraryBook database and update it with the data that the user has entered into the textfields. public void ToDataBase() { //Retrieve info from the Textfields in die Dialog. String Name = Name1.getText(); String Bookno = Bookno1.getText(); String Author = Author1.getText(); String Publication = Publication1.getText(); //Parameters for the creation of the database. String dbuser = ""; String dbpasswd = ""; String DriverPrefix = "jdbc:odbc:"; String DataSource ="Library"; //The SQL String String SQLString = "INSERT INTO Book(Name,Bookno,Author,Publication)VALUES('" +Name+ "','"+Bookno+"','"+Author+"','"+Publication+"')"; //Loads JDBC/ODBC driver try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(Exception e) { //Uses the JFC Swing to display warning message in Option Pane with //relevant information about the error. JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE); return; } Statement stmt = null; Connection con = null; //Creates connection to database try { con = DriverManager.getConnection(DriverPrefix+DataSource, dbuser, dbpasswd); stmt = con.createStatement(); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE); } //Updates the database with data try { stmt.executeUpdate(SQLString); con.close(); this.dispose(); }catch (Exception e) {

JOptionPane.showMessageDialog(null,"Check that all TextFields have been completed.\n"+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE); }}} ////////////////This class will create a Dialog fo the editing of existing records. class EditDlg extends Dialog implements ActionListener, ItemListener { //Sets the textfields that goes to the Dialog box TextField BooknoField, AuthorField, PublicationField; //Creates the pop uplist on the dialog Choice NameList; public EditDlg(Library parent, String title) { //Sets the dimensions for the Edit dialog box. super(parent, title, true); setLayout (new GridLayout(5,3,10,20)); setSize(300, 250); setResizable(false); //Sets the labels that goes onto the Dialog box Label Name, Bookno, Author, Publication; Name = new Label("Name: "); Bookno = new Label("Bookno: "); Author = new Label ("Author: "); Publication = new Label("Publication: "); //Adds a pop up list to the dialog with names from the database NameList = new Choice(); //Sets the sizes of the textfields BooknoField = new TextField(10); AuthorField = new TextField(20); PublicationField = new TextField(10); //Creates the buttons on the dialog box Button BtnUpdate, BtnCn; BtnUpdate = new Button("Update"); BtnCn = new Button("Cancel"); //Adds listeners to the buttons BtnUpdate.addActionListener(this); BtnCn.addActionListener(this); NameList.addItemListener(this); //Creates space labels to fill up the space in the GridLayout Label space1, space2, space3, space4, space5; space1 = new Label(" "); space2 = new Label(" "); space3 = new Label(" "); space4 = new Label(" "); space5 = new Label(" "); //Add all the controls to the Dialog. add(Name); add(NameList); add(space1);

add(Bookno); add(BooknoField); add(space2); add(Author); add(AuthorField); add(space3); add(Publication); add(PublicationField); add(space4); add(space5); add(BtnUpdate); add(BtnCn); GetData(); } ///////////////////Handles all the events happeing on the dialog box public void actionPerformed(ActionEvent e) { String str = e.getActionCommand(); if (str.equals("Update")){ DataUpdate(); } if (str.equals("Cancel")) { dispose(); }} /////////////This method handles the Event action that take place on the Choide Drop Down List public void itemStateChanged(ItemEvent ie) { String dbuser = " "; String dbpasswd = " "; String DriverPrefix = "jdbc:odbc:"; String DataSource = "Library"; //This will hold the currently selected name in the list in myChoice String myChoice = NameList.getSelectedItem(); String SQL = "SELECT Name,Bookno,Author,Publication FROM Book WHERE Name ='" +myChoice+ "'"; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE); } Statement stmt = null; Connection con = null; try { con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser,dbpasswd); stmt = con.createStatement(); } catch (Exception e) {

JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE); } ResultSet rs = null; try { rs = stmt.executeQuery(SQL); rs.next(); BooknoField.setText(rs.getString(2)); AuthorField.setText(rs.getString(3)); PublicationField.setText(rs.getString(4)); con.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE); }} //This method will populate the pop up list with names from the database. public void GetData() { String dbuser = " "; String dbpasswd = " "; String DriverPrefix = "jdbc:odbc:"; String DataSource = "Library"; String SQL = "SELECT Name FROM Book" ; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE); } Statement stmt = null; Connection con = null; try { con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser,dbpasswd); stmt = con.createStatement(); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE); } ResultSet rs = null; try { rs = stmt.executeQuery(SQL); //This will populate the drop down list with all the names of people entered into the database. while (rs.next()) { NameList.add(rs.getString("Name")); } } catch(Exception e) {

JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE); } //This try - catch sequence will close the database after the drop down list has been populated try { con.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"Warning",JOptionPane.WARNING_ MESSAGE); }} ////This will update the change data from the TextFields to the database. public void DataUpdate() { String dbuser = " "; String dbpasswd = " "; String DriverPrefix = "jdbc:odbc:"; String DataSource = "Library"; //Loads the database driver try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE); } Statement stmt = null; Connection con = null; //Creates connection to database try { con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser,dbpasswd); stmt = con.createStatement(); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE); } //These String variables will hold the updated data retrieved from the TextFields. String upBookno = BooknoField.getText(); String upAuthor = AuthorField.getText(); String upPublication = PublicationField.getText(); //This is the SQL String that updates the data from the TextFields to the database String SQL = "UPDATE Author SET Bookno = '"+upBookno+"', Author = '"+upAuthor+"', Publication = '"+upPublication+"' WHERE Name = '"+NameList.getSelectedItem()+"'"; //Communicates with database try { stmt.executeUpdate(SQL); con.close(); dispose();

} catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE); }}} //This class will delete data from the database class DelRec extends Dialog implements ActionListener, ItemListener { //Declaration of TextFields TextField BooknoField, AuthorField, PublicationField; //Declaration of drop down list Choice NameList; public DelRec (Library parent, String title) { super (parent, title, true); setLayout(new GridLayout(5,3,10,20)); setSize(300, 250); setResizable(false); //Declaration of labels that will describe the TextFields Label Name, Bookno, Author, Publication; //Creates the Labels Name = new Label("Name"); Bookno = new Label("Bookno"); Author = new Label("Author"); Publication = new Label("Publication"); //Declaration of labels that will be used as spacers in the GridLayout Label space1, space2, space3, space4, space5; //Creates the spacer labels. space1 = new Label(" "); space2 = new Label(" "); space3 = new Label(" "); space4 = new Label(" "); space5 = new Label(" "); //Creates the button on the dialog Button BtnDel = new Button("Delete"); Button BtnCn = new Button("Cancel"); //Creates the drop down list NameList = new Choice(); //Adds listeners to buttons and drop down list BtnDel.addActionListener(this); BtnCn.addActionListener(this); NameList.addItemListener(this); //Creates the TextFields BooknoField = new TextField(10); AuthorField = new TextField(20); PublicationField = new TextField(10); //Adds the components to the dialog add(Name); add(NameList);

add(space1); add(Bookno); add(BooknoField); add(space2); add(Author); add(AuthorField); add(space3); add(Publication); add(PublicationField); add(space4); add(space5); add(BtnDel); add(BtnCn); GetData(); } //This method handles all the action events from the Delete and Cancel buttons . public void actionPerformed(ActionEvent e) { String str = e.getActionCommand(); if (str.equals("Delete")) { DelCurRec(); } if (str.equals("Cancel")) { dispose(); }} //Updates the TextFields with the rest of the data when selection is made. public void itemStateChanged(ItemEvent e) { String dbuser = " "; String dbpasswd = " "; String DriverPrefix = "jdbc:odbc:"; String DataSource = "Library"; //This will hold the currently selected name in the list in myChoice String myChoice = NameList.getSelectedItem(); //This is the SQL query for extracting data from the database. String SQL = "SELECT Name,Bookno,Author,Publication FROM Book WHERE Name ='" +myChoice+ "'"; //Loads the driver for communicating with database try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (Exception ex) { JOptionPane.showMessageDialog(null,""+ex.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE); } Statement stmt = null; Connection con = null; //Creates a connection to the database try {

con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser,dbpasswd); stmt = con.createStatement(); } catch (Exception ex) { JOptionPane.showMessageDialog(null,""+ex.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE); } ResultSet rs = null; //Executes the Sl query on the database. try { rs = stmt.executeQuery(SQL); rs.next(); BooknoField.setText(rs.getString(2)); AuthorField.setText(rs.getString(3)); PublicationField.setText(rs.getString(4)); con.close(); } catch (Exception ex) { JOptionPane.showMessageDialog(null,""+ex.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE); }} //This method will populate the drop downlist with data from the database. public void GetData() { String dbuser = " "; String dbpasswd = " "; String DriverPrefix = "jdbc:odbc:"; String DataSource = "Library"; String SQL = "SELECT Name FROM Book"; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE); } Statement stmt = null; Connection con = null; try { con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser, dbpasswd); stmt = con.createStatement(); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE); } ResultSet rs = null; try { rs = stmt.executeQuery(SQL); while (rs.next()) { NameList.add(rs.getString("name"));

} } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Problem",JOptionPane.WARNING_MESSAGE); }} //This method wil delete the currently selected record. public void DelCurRec() { String dbuser = " "; String dbpasswd = " "; String DriverPrefix = "jdbc:odbc:"; String DataSource = "Library"; //MyChoice will hold the value for the currently selected item String myChoice = NameList.getSelectedItem(); //This is the SQL string String SQL = "DELETE FROM Book WHERE Name = '" +myChoice+ "'"; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE); } Statement stmt = null; Connection con = null; //Creates connection to database try { con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser,dbpasswd); stmt = con.createStatement(); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE); } //Execute the SQL statment for deleting records try { stmt.executeUpdate(SQL); //This closes the connection to the database con.close(); //This closes the dialog dispose(); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE); }}} /////////This class will create the Search Dialog. class SearchDlg extends Dialog implements ActionListener, ItemListener { //This declares a TextField that will be put on the dialog TextField Name;

//This creates a Search and Cancel button on the dialog Button BtnGo, BtnCn; //This creates checkboxes for different search queries Checkbox option1 = new Checkbox("By Name"); public SearchDlg (Library parent, String title) { super(parent,title,false); setSize(300, 100); setLayout(new GridLayout(3,2,8,5)); setResizable(false); setLocation(300,50); //This creates a label for the search dialog describing the TextField Label Srch = new Label("Search For :"); //This creates a Textfield for the user input Name = new TextField(10); //Creates button for Search and Cancel on the dialog BtnGo = new Button("Search"); BtnCn = new Button("Cancel"); //Disables the Search button unitl a selection is made from the CheckBoxes BtnGo.setEnabled(false); //Adds event listeners to the Button. BtnGo.addActionListener(this); BtnCn.addActionListener(this); //Adds Item Listeners to the checkboxes option1.addItemListener(this); //This will create spacer labels for the GridLayout Label space1, space2, space3; space1 = new Label(" "); space2 = new Label(" "); space3 = new Label(" "); //Add Controls to the dialog. add(Srch); add(Name); add(space1); add(option1); add(space2); add(space3); add(BtnGo); add(BtnCn); } //////This method handles all the events that take place on the dialog public void actionPerformed(ActionEvent e) { String str = e.getActionCommand(); if (str.equals("Search")) { GoSrch(); } if (str.equals("Cancel")) {

dispose(); }} ////////This will handle the events from clicking the ChecBoxes on the dialog the Search button will also be enable when a selection is made. public void itemStateChanged(ItemEvent e) { if (option1.getState() == true) { BtnGo.setEnabled(true); }} ///////This method will search for the selected record in the database public void GoSrch() { if (option1.getState() == true) { Srch1(); }} /////This method will search the database by the name that is input into the TextField public void Srch1() { String dbuser = " "; String dbpasswd = " "; String DriverPrefix = "jdbc:odbc:"; String DataSource = "Library"; String mySearch = Name.getText(); //This is the SQL String for retrieving data by name from the database. String SQL = "SELECT Name,Bookno,Author,Publication FROM Book WHERE Name = '" +mySearch+"'"; //This loads the driver for the database try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (Exception e) { JOptionPane.showMessageDialog(null,""+e.getMessage(),"Database Driver Error", JOptionPane.WARNING_MESSAGE); } Statement stmt = null; Connection con = null; //Creates connection to the database. try { con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser, dbpasswd); stmt = con.createStatement(); } catch (Exception e) { JOptionPane.showMessageDialog(null, " "+e.getMessage(),"Cannot Connect to Database",JOptionPane.WARNING_MESSAGE); } ResultSet rs = null; //Executes the SQL query on the database and displays the result in a JFC OptionPane try { rs = stmt.executeQuery(SQL); rs.next();

String Result = rs.getString(1) + " " + rs.getString(2) + "\n" + rs.getString(3) + "\n" + rs.getString(4); //Makes use of a swing OptionPane to display information of the successful search. JOptionPane.showMessageDialog(null,Result,"Record Found", JOptionPane.INFORMATION_MESSAGE); //Close the connection to the database. con.close(); this.dispose(); } catch (Exception e) { //Makes use of the JFC Swing OptionPane to display error message JOptionPane.showMessageDialog(null ,"Record not Found","Warning", JOptionPane.INFORMATION_MESSAGE); }}} //////////////This class handles the menubar events class myMenuHandler implements ActionListener { Library appbook; public myMenuHandler(Library appbook) { this.appbook = appbook; } //This code will display an Dialog Boxes for the different Menu Selections public void actionPerformed(ActionEvent ae) { String arg = (String)ae.getActionCommand(); //This code executed when Exit is selected on the Menu Bar if (arg.equals("Exit")) { appbook.dispose(); } //This will start the creation of the Add Dialog if (arg.equals("Add...")) { AddDlg Adlg = new AddDlg(appbook, "Add New Book"); Adlg.setVisible(true); } //This will start the creation of the Edit Dialog if (arg.equals("Edit...")) { EditDlg Edlg = new EditDlg(appbook, "Edit Records"); Edlg.setVisible(true); } //This will start the creation of the Delete Dialog if (arg.equals("Delete...")) { DelRec dlg = new DelRec(appbook, "Delete Records"); dlg.setVisible(true); } //This will start the creation of the Search Dialog if (arg.equals("Search...")) { SearchDlg schDlg = new SearchDlg(appbook, "Search Records"); schDlg.setVisible(true); }}}

You might also like