[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

AddresBook Modification 28.7

Posted on 2011-10-21
10
Medium Priority
?
230 Views
Last Modified: 2012-05-12
This program is an AddressBook Modification: Update an Existing Entry:  I must modify the program in Figs 28.30-Fig28.32 to provide a JButton that allows the user to call a method updatePerson in PersonQueries class to update the current entry in the AddressBook database. I cannot connect to the address database.  The program compiles without errors but I do not know what happens when the program runs.  Can someone help me?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.util.List;
import javax.swing.JButton;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.BoxLayout;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;

public class AddressBookDisplay extends JFrame
{
   private Person currentEntry;
   private PersonQueries personQueries;
   private List< Person > results;  
   private int numberOfEntries = 0;
   private int currentEntryIndex;

   private JButton browseButton;
   private JLabel emailLabel;
   private JTextField emailTextField;
   private JLabel firstNameLabel;
   private JTextField firstNameTextField;
   private JLabel idLabel;
   private JTextField idTextField;
   private JTextField indexTextField;
   private JLabel lastNameLabel;
   private JTextField lastNameTextField;
   private JTextField maxTextField;
   private JButton nextButton;
   private JLabel ofLabel;
   private JLabel phoneLabel;
   private JTextField phoneTextField;
   private JButton previousButton;
   private JButton queryButton;
   private JLabel queryLabel;
   private JPanel queryPanel;
   private JPanel navigatePanel;
   private JPanel displayPanel;
   private JTextField queryTextField;
   private JButton insertButton;
      private JButton updateButton;
   
   // no-argument constructor
   public AddressBookDisplay()
   {
      super( "Address Book" );
     
      // establish database connection and set up PreparedStatements
      personQueries = new PersonQueries();
     
      // create GUI
      navigatePanel = new JPanel();
      previousButton = new JButton();
      indexTextField = new JTextField( 2 );
      ofLabel = new JLabel();
      maxTextField = new JTextField( 2 );
      nextButton = new JButton();
      displayPanel = new JPanel();
      idLabel = new JLabel();
      idTextField = new JTextField( 10 );
      firstNameLabel = new JLabel();
      firstNameTextField = new JTextField( 10 );
      lastNameLabel = new JLabel();
      lastNameTextField = new JTextField( 10 );
      emailLabel = new JLabel();
      emailTextField = new JTextField( 10 );
      phoneLabel = new JLabel();
      phoneTextField = new JTextField( 10 );
      queryPanel = new JPanel();
      queryLabel = new JLabel();
      queryTextField = new JTextField( 10 );
      queryButton = new JButton();
      browseButton = new JButton();
      insertButton = new JButton();
            updateButton = new JButton();

      setLayout( new FlowLayout( FlowLayout.CENTER, 10, 10 ) );
      setSize( 400, 300 );
      setResizable( false );

      navigatePanel.setLayout(
         new BoxLayout( navigatePanel, BoxLayout.X_AXIS ) );

      previousButton.setText( "Previous" );
      previousButton.setEnabled( false );
      previousButton.addActionListener(
         new ActionListener()
         {
            public void actionPerformed( ActionEvent evt )
            {
               previousButtonActionPerformed( evt );
            } // end method actionPerformed
         } // end anonymous inner class
      ); // end call to addActionListener

      navigatePanel.add( previousButton );
      navigatePanel.add( Box.createHorizontalStrut( 10 ) );

      indexTextField.setHorizontalAlignment(
         JTextField.CENTER );
      indexTextField.addActionListener(
         new ActionListener()
         {
            public void actionPerformed( ActionEvent evt )
            {
               indexTextFieldActionPerformed( evt );
            } // end method actionPerformed
         } // end anonymous inner class
      ); // end call to addActionListener

      navigatePanel.add( indexTextField );
      navigatePanel.add( Box.createHorizontalStrut( 10 ) );

      ofLabel.setText( "of" );
      navigatePanel.add( ofLabel );
      navigatePanel.add( Box.createHorizontalStrut( 10 ) );

      maxTextField.setHorizontalAlignment(
         JTextField.CENTER );
      maxTextField.setEditable( false );
      navigatePanel.add( maxTextField );
      navigatePanel.add( Box.createHorizontalStrut( 10 ) );

      nextButton.setText( "Next" );
      nextButton.setEnabled( false );
      nextButton.addActionListener(
         new ActionListener()
         {
            public void actionPerformed( ActionEvent evt )
            {
               nextButtonActionPerformed( evt );
            } // end method actionPerformed
         } // end anonymous inner class
      ); // end call to addActionListener

      navigatePanel.add( nextButton );
      add( navigatePanel );

      displayPanel.setLayout( new GridLayout( 5, 2, 4, 4 ) );

      idLabel.setText( "Address ID:" );
      displayPanel.add( idLabel );

      idTextField.setEditable( false );
      displayPanel.add( idTextField );

      firstNameLabel.setText( "First Name:" );
      displayPanel.add( firstNameLabel );
      displayPanel.add( firstNameTextField );

      lastNameLabel.setText( "Last Name:" );
      displayPanel.add( lastNameLabel );
      displayPanel.add( lastNameTextField );

      emailLabel.setText( "Email:" );
      displayPanel.add( emailLabel );
      displayPanel.add( emailTextField );

      phoneLabel.setText( "Phone Number:" );
      displayPanel.add( phoneLabel );
      displayPanel.add( phoneTextField );
      add( displayPanel );

      queryPanel.setLayout(
         new BoxLayout( queryPanel, BoxLayout.X_AXIS) );

      queryPanel.setBorder( BorderFactory.createTitledBorder(
         "Find an entry by last name" ) );
      queryLabel.setText( "Last Name:" );
      queryPanel.add( Box.createHorizontalStrut( 5 ) );
      queryPanel.add( queryLabel );
      queryPanel.add( Box.createHorizontalStrut( 10 ) );
      queryPanel.add( queryTextField );
      queryPanel.add( Box.createHorizontalStrut( 10 ) );

      queryButton.setText( "Find" );
      queryButton.addActionListener(
         new ActionListener()
         {
            public void actionPerformed( ActionEvent evt )
            {
               queryButtonActionPerformed( evt );
            } // end method actionPerformed
         } // end anonymous inner class
      ); // end call to addActionListener

      queryPanel.add( queryButton );
      queryPanel.add( Box.createHorizontalStrut( 5 ) );
      add( queryPanel );

      browseButton.setText( "Browse All Entries" );
      browseButton.addActionListener(
         new ActionListener()
         {
            public void actionPerformed( ActionEvent evt )
            {
               browseButtonActionPerformed( evt );
            } // end method actionPerformed
         } // end anonymous inner class
      ); // end call to addActionListener

      add( browseButton );

      insertButton.setText( "Insert New Entry" );
      insertButton.addActionListener(
         new ActionListener()
         {
            public void actionPerformed( ActionEvent evt )
            {
               insertButtonActionPerformed( evt );
            } // end method actionPerformed
         } // end anonymous inner class
      ); // end call to addActionListener

         add( insertButton );      
            
            updateButton.setText( "Update Current Entry" );
            updateButton.addActionListener(
                  new ActionListener()
                  {
                        public void actionPerformed( ActionEvent evt )
                        {
                              updateButtonActionPerformed( evt );
                        } // end method actionPerformed
                  } // end anonymous inner class
                  );// end call to ActionListener
            
            add( updateButton );
      addWindowListener(
         new WindowAdapter()
         {  
            public void windowClosing( WindowEvent evt )
            {
               personQueries.close(); // close database connection
               System.exit( 0 );
            } // end method windowClosing
         } // end anonymous inner class
      ); // end call to addWindowListener
      
      setVisible( true );
   } // end no-argument constructor

   // handles call when previousButton is clicked
   private void previousButtonActionPerformed( ActionEvent evt )
   {
      currentEntryIndex--;
     
      if ( currentEntryIndex < 0 )
         currentEntryIndex = numberOfEntries - 1;
     
      indexTextField.setText( "" + ( currentEntryIndex + 1 ) );
      indexTextFieldActionPerformed( evt );  
   } // end method previousButtonActionPerformed

   // handles call when nextButton is clicked
   private void nextButtonActionPerformed( ActionEvent evt )
   {
      currentEntryIndex++;
     
      if ( currentEntryIndex >= numberOfEntries )
         currentEntryIndex = 0;
     
      indexTextField.setText( "" + ( currentEntryIndex + 1 ) );
      indexTextFieldActionPerformed( evt );
   } // end method nextButtonActionPerformed

   // handles call when queryButton is clicked
   private void queryButtonActionPerformed( ActionEvent evt )
   {
      results =
         personQueries.getPeopleByLastName( queryTextField.getText() );
      numberOfEntries = results.size();
     
      if ( numberOfEntries != 0 )
      {
         currentEntryIndex = 0;
         currentEntry = results.get( currentEntryIndex );
         idTextField.setText("" + currentEntry.getAddressID() );
         firstNameTextField.setText( currentEntry.getFirstName() );
         lastNameTextField.setText( currentEntry.getLastName() );
         emailTextField.setText( currentEntry.getEmail() );
         phoneTextField.setText( currentEntry.getPhoneNumber() );
         maxTextField.setText( "" + numberOfEntries );
         indexTextField.setText( "" + ( currentEntryIndex + 1 ) );
         nextButton.setEnabled( true );
         previousButton.setEnabled( true );
      } // end if
      else
         browseButtonActionPerformed( evt );
   } // end method queryButtonActionPerformed

   // handles call when a new value is entered in indexTextField
   private void indexTextFieldActionPerformed( ActionEvent evt )
   {
      currentEntryIndex =
         ( Integer.parseInt( indexTextField.getText() ) - 1 );
     
      if ( numberOfEntries != 0 && currentEntryIndex < numberOfEntries )
      {
         currentEntry = results.get( currentEntryIndex );
         idTextField.setText("" + currentEntry.getAddressID() );
         firstNameTextField.setText( currentEntry.getFirstName() );
         lastNameTextField.setText( currentEntry.getLastName() );
         emailTextField.setText( currentEntry.getEmail() );
         phoneTextField.setText( currentEntry.getPhoneNumber() );
         maxTextField.setText( "" + numberOfEntries );
         indexTextField.setText( "" + ( currentEntryIndex + 1 ) );
      } // end if
    } // end method indexTextFieldActionPerformed

   // handles call when browseButton is clicked
   private void browseButtonActionPerformed( ActionEvent evt )
   {
      try
      {
         results = personQueries.getAllPeople();
         numberOfEntries = results.size();
     
         if ( numberOfEntries != 0 )
         {
            currentEntryIndex = 0;
            currentEntry = results.get( currentEntryIndex );
            idTextField.setText("" + currentEntry.getAddressID() );
            firstNameTextField.setText( currentEntry.getFirstName() );
            lastNameTextField.setText( currentEntry.getLastName() );
            emailTextField.setText( currentEntry.getEmail() );
            phoneTextField.setText( currentEntry.getPhoneNumber() );
            maxTextField.setText( "" + numberOfEntries );
            indexTextField.setText( "" + ( currentEntryIndex + 1 ) );
            nextButton.setEnabled( true );
            previousButton.setEnabled( true );
         } // end if
      } // end try
      catch ( Exception e )
      {
         e.printStackTrace();
      } // end catch
   } // end method browseButtonActionPerformed

   // handles call when insertButton is clicked
   private void insertButtonActionPerformed( ActionEvent evt )
   {
      int result = personQueries.addPerson( firstNameTextField.getText(),
         lastNameTextField.getText(), emailTextField.getText(),
         phoneTextField.getText() );
     
      if ( result == 1 )
         JOptionPane.showMessageDialog( this, "Person added!",
            "Person added", JOptionPane.PLAIN_MESSAGE );
      else
         JOptionPane.showMessageDialog( this, "Person not added!",
            "Error", JOptionPane.PLAIN_MESSAGE );
         
      browseButtonActionPerformed( evt );
   } // end method insertButtonActionPerformed
   
      private void updateButtonActionPerformed( ActionEvent evt )
      {
            int result = personQueries.addPerson( firstNameTextField.getText(),
         lastNameTextField.getText(), emailTextField.getText(),
         phoneTextField.getText() );
            if ( result == 1 )
                  JOptionPane.showMessageDialog( this, "Person updated!",
                        "Person updated", JOptionPane.PLAIN_MESSAGE );
            else
                  JOptionPane.showMessageDialog( this, "Person not updated!",
                        "Person not updated", JOptionPane.PLAIN_MESSAGE );
                        
            updateButtonActionPerformed( evt );
      } // end method updateButtonActionPerformed
   // main method
   public static void main( String args[] )
   {
      new AddressBookDisplay();
   } // end method main
} // end class AddressBookDisplay

public class Person
{
   private int addressID;
   private String firstName;
   private String lastName;
   private String email;
   private String phoneNumber;

   // no-argument constructor
   public Person()
   {
   } // end no-argument Person constructor

   // constructor
   public Person( int id, String first, String last,
      String emailAddress, String phone )
   {
      setAddressID( id );
      setFirstName( first );
      setLastName( last );
      setEmail( emailAddress );
      setPhoneNumber( phone );
   } // end five-argument Person constructor

   // sets the addressID
   public void setAddressID( int id )
   {
      addressID = id;
   } // end method setAddressID

   // returns the addressID
   public int getAddressID()
   {
      return addressID;
   } // end method getAddressID
   
   // sets the firstName
   public void setFirstName( String first )
   {
      firstName = first;
   } // end method setFirstName

   // returns the first name
   public String getFirstName()
   {
      return firstName;
   } // end method getFirstName
   
   // sets the lastName
   public void setLastName( String last )
   {
      lastName = last;
   } // end method setLastName

   // returns the last name
   public String getLastName()
   {
      return lastName;
   } // end method getLastName
   
   // sets the email address
   public void setEmail( String emailAddress )
   {
      email = emailAddress;
   } // end method setEmail

   // returns the email address
   public String getEmail()
   {
      return email;
   } // end method getEmail
   
   // sets the phone number
   public void setPhoneNumber( String phone )
   {
      phoneNumber = phone;
   } // end method setPhoneNumber

   // returns the phone number
   public String getPhoneNumber()
   {
      return phoneNumber;
   } // end method getPhoneNumber
} // end class Person

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;

public class PersonQueries
{
   private static final String URL = "jdbc:derby:AddressBook";
   private static final String USERNAME = "deitel";
   private static final String PASSWORD = "deitel";

   private Connection connection = null; // manages connection
   private PreparedStatement selectAllPeople = null;
   private PreparedStatement selectPeopleByLastName = null;
   private PreparedStatement insertNewPerson = null;
   
   // constructor
   public PersonQueries()
   {
      try
      {
         connection =
            DriverManager.getConnection( URL, USERNAME, PASSWORD );

         // create query that selects all entries in the AddressBook
         selectAllPeople =
            connection.prepareStatement( "SELECT * FROM Addresses" );
         
         // create query that selects entries with a specific last name
         selectPeopleByLastName = connection.prepareStatement(
            "SELECT * FROM Addresses WHERE LastName = ?" );
         
         // create insert that adds a new entry into the database
         insertNewPerson = connection.prepareStatement(
            "INSERT INTO Addresses " +
            "( FirstName, LastName, Email, PhoneNumber ) " +
            "VALUES ( ?, ?, ?, ? )" );
      } // end try
      catch ( SQLException sqlException )
      {
         sqlException.printStackTrace();
         System.exit( 1 );
      } // end catch
   } // end PersonQueries constructor
   
   // select all of the addresses in the database
   public List< Person > getAllPeople()
   {
      List< Person > results = null;
      ResultSet resultSet = null;
     
      try
      {
         // executeQuery returns ResultSet containing matching entries
         resultSet = selectAllPeople.executeQuery();
         results = new ArrayList< Person >();
         
         while ( resultSet.next() )
         {
            results.add( new Person(
               resultSet.getInt( "addressID" ),
               resultSet.getString( "firstName" ),
               resultSet.getString( "lastName" ),
               resultSet.getString( "email" ),
               resultSet.getString( "phoneNumber" ) ) );
         } // end while
      } // end try
      catch ( SQLException sqlException )
      {
         sqlException.printStackTrace();        
      } // end catch
      finally
      {
         try
         {
            resultSet.close();
         } // end try
         catch ( SQLException sqlException )
         {
            sqlException.printStackTrace();        
            close();
         } // end catch
      } // end finally
     
      return results;
   } // end method getAllPeople
   
   // select person by last name  
   public List< Person > getPeopleByLastName( String name )
   {
      List< Person > results = null;
      ResultSet resultSet = null;

      try
      {
         selectPeopleByLastName.setString( 1, name ); // specify last name

         // executeQuery returns ResultSet containing matching entries
         resultSet = selectPeopleByLastName.executeQuery();

         results = new ArrayList< Person >();

         while ( resultSet.next() )
         {
            results.add( new Person( resultSet.getInt( "addressID" ),
               resultSet.getString( "firstName" ),
               resultSet.getString( "lastName" ),
               resultSet.getString( "email" ),
               resultSet.getString( "phoneNumber" ) ) );
         } // end while
      } // end try
      catch ( SQLException sqlException )
      {
         sqlException.printStackTrace();
      } // end catch
      finally
      {
         try
         {
            resultSet.close();
         } // end try
         catch ( SQLException sqlException )
         {
            sqlException.printStackTrace();        
            close();
         } // end catch
      } // end finally
     
      return results;
   } // end method getPeopleByName
   
   // add an entry
   public int addPerson(
      String fname, String lname, String email, String num )
   {
      int result = 0;
     
      // set parameters, then execute insertNewPerson
      try
      {
         insertNewPerson.setString( 1, fname );
         insertNewPerson.setString( 2, lname );
         insertNewPerson.setString( 3, email );
         insertNewPerson.setString( 4, num );

         // insert the new entry; returns # of rows updated
         result = insertNewPerson.executeUpdate();
      } // end try
      catch ( SQLException sqlException )
      {
         sqlException.printStackTrace();
         close();
      } // end catch
     
      return result;
   } // end method addPerson
      
      public void updatePerson( Person person )
                  throws Exception
      {
      String sql = "UPDATE persons SET firstName = ?, lastName = ?,email = ?, phoneNumber = ?, email = ? WHERE id = ?";
      Object[] parameters = new Object[] {
                  person.getAddressID(), person.getFirstName(),
                  person.getLastName(), person.getEmail(),
                  person.getPhoneNumber()
      };
     
   }  
   // close the database connection
   public void close()
   {
      try
      {
         connection.close();
      } // end try
      catch ( SQLException sqlException )
      {
         sqlException.printStackTrace();
      } // end catch
   } // end method close
} // end class PersonQueries



address.sql
AddressBookDisplay.java
Person.java
PersonQueries.java
0
Comment
Question by:assaultkitty
  • 7
  • 3
10 Comments
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 37010337
What is your sepcific question?

There was one compilation error in PersonQueries:

       while ( resultSet.next() )
         {
            results.add( new Person(
                 resultSet.getInt( "addressID" ),  //<----- I added this line
               resultSet.getString( "firstName" ),
               resultSet.getString( "lastName" ),
               resultSet.getString( "email" ),
               resultSet.getString( "phoneNumber" ) ) );
         } // end while

Open in new window


I added one line and it now all compiles.

But I don't have derby driver and  I cannot exeucte it of course.
If you have specifc questions let me know but in general wiithout executing with  such
big programs is difficult to understand
0
 

Author Comment

by:assaultkitty
ID: 37010351
0
 

Author Comment

by:assaultkitty
ID: 37010352
I put up the derby.  Can you execute the program now?
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 2000 total points
ID: 37010359
No this is just file with two strange  lines in there.

Have you  derby instaled and working ?
0
 

Author Comment

by:assaultkitty
ID: 37010361
The derby is new to me.  Can you help me with this as far as the connection to the database and can you explain what it is and what is used for?  
0
 

Author Comment

by:assaultkitty
ID: 37010368
i have never installed a derby before now.
0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 2000 total points
ID: 37010376
No, I didn't use Derby.

If you have Eclipse ,  i think they give a pretty goo outline ghow to get strated with Derby for Eclipse project:
http://db.apache.org/derby/integrate/plugin_help/derby_app.html

But it is of course not something just for an hour or eve two.. Will take some time.
0
 

Author Comment

by:assaultkitty
ID: 37010799
Can I get a little help the driver I have for the derby is

public String driver = "org.apache.derby.jdbc.EmbeddedDriver";

It is not working can you help me set up the driver for program.  I get a runtime error stating


Exception in thread "main" java.lang.ClassNotFoundException: org.apache.derby.jdbc.EmbeddedDriver
      at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
      at java.lang.Class.forName0(Native Method)
      at java.lang.Class.forName(Class.java:169)
      at PersonQueries.<init>(PersonQueries.java:34)
      at AddressBookDisplay.<init>(AddressBookDisplay.java:66)
      at AddressBookDisplay.main(AddressBookDisplay.java:391)

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.
0
 

Author Comment

by:assaultkitty
ID: 37010848
I have fixed the error with the Derby and the connection.  I have added a JButton in the AddressBookDisplay.  It is not showing up when I run the program.  Can someone help me with this problem.  Also, I want to know if I called the update person properly in my AddressBookDisplay program.  I am not getting the JButton called update to show up in my AddressBookDisplay.

0
 

Author Closing Comment

by:assaultkitty
ID: 37268361
I really appreciated your help.  Mr. Yan was very patient.
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month18 days, 22 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question