Results 1 to 5 of 5
  1. #1
    Allexxy is offline Member
    Join Date
    Feb 2012
    Location
    Lagos, Nigeria
    Posts
    7
    Rep Power
    0

    Default Problem with updating ListModel

    Hi all,

    I have a problem with my program. Its an Address book that adds, edits, deletes and sorts persons by last name and by zip code. My problem is with the "add method". When I click the add button on the GUI, a dialog comes up for user input and then when 'ok' is clicked the person's details is displayed on the GUI. But when I click to add another person, it overwrites the previous person with the new person's details, recording it in duplicate. I have no clue what is causing this.
    In a normal, System.out....situation you create new objects like so.

    Java Code:
    AddressBook person1 = new AddressBook("Dave", "Jackson", "2 Mimic Drive", "Pelham", 
    "Alabama", "2334","923-348958")
    So the addbutton, should behave like it were creating such instances with user input, but it replaces after the first input and records the name twice or three times with each new input.

    Here's my Person class code:
    Java Code:
    /** 
     *  An object of this class maintains information about a single individual  
     *  in the address book.
     */
    public class Person extends java.lang.Object implements java.io.Serializable
    {
    	/**
    	 *  Auto-generated serial ID used during deserialization to verify that the sender 
             *  and receiver of a 
    	 *  serialized object have loaded classes for that object that are compatible 
    	 *  with respect to serialization
    	 */
    	private static final long serialVersionUID = 7944773775195637943L;
    
    	/**
    	 *  Person fields
    	 */
    	 private String firstName;
    
         private String lastName;
    
         private String address;
    
         private String city;
    
         private String state;
    
         private String zip;
    
         private String phone;
         
         /** 
          *  Constructor for Person.
          */
          public Person( String firstName, String lastName, String address, String city, 
    String state, String zip, String phone )
          {
              this.firstName = firstName;
              this.lastName  = lastName;
              this.address   = address;
              this.city      = city;
              this.state     = state;
              this.zip       = zip;
              this.phone     = phone ;
          }
          
          /** 
           *  @return the person's first name
           */
           public String getFirstName()
           {
               return firstName;
           }
         
          /** 
           *  @return the person's last name
           */
           public String getLastName()
           {
               return lastName;
           }
         
          /** 
           *  @return the person's address
           */
           public String getAddress()
           {
              return address;
           }
         
          /** 
           *  @return the person's city
           */
           public String getCity()
           {
              return city;
           }
         
          /** 
           *  @return the person's state
           */
           public String getState()
           {
              return state;
           }
         
          /** 
           *  @return the person's zip code
           */
           public String getZip()
           {
              return zip;
           }
         
          /** 
           *  @return the person's phone number
           */
           public String getPhone()
           {
              return phone;
           }
    
          /** 
           *  Set the person's first name
           */
           public void setFirstName(String firstName)
           {
               this.firstName = firstName;
           }
        
          /** 
           *  Set the person's last name
           */
           public void setLastName(String lastName)
           {
         	  this.lastName = lastName;
           }
    
          /** 
           *  Set the person's address
           */
           public void setAddress(String address)
           {
               this.address = address;
           }
    
          /** 
           *  Set the person's city
           */
           public void setCity(String city)
           {
         	  this.city = city;
           }
    
          /** 
           *  Set the person's state
           */
           public void setState(String state)
           {
         	  this.state = state;
           }
    
          /** 
           *  Set the person's zip code
           */
           public void setZip(String zip)
           {
         	  this.zip = zip;
           }
    
          /**  
           *  Set the person's phone number
           */
           public void setPhone(String phone)
           {
         	  this.phone = phone;
           }
           
           /** 
            *  Update the person with new information.
            *  Note that the name cannot be changed, but the other information can be
            */
            public void update(String address, String city, String state, String zip,
     String phone)
            {
            	setAddress(address);
            	setCity(city);
            	setState(state);
            	setZip(zip);
            	setPhone(phone);
            }
    }
    Here's the add method code in my AddressBook class

    Java Code:
    import java.io.File;
    import java.util.List;
    import java.util.Vector;
    
    /** 
     *  An object of this class maintains the collection of Person objects 
     *  that constitute an address book
     */
    public class AddressBook extends java.util.Observable implements java.io.Serializable
    {
    
    private static final long serialVersionUID = 6094697971638342871L;
    private Person person; // From a Person class
    private List < Person > collection = new Vector < Person > ();
    
    public AddressBook( )     {     }
    
    public void addPerson( String firstName, String lastName, String address, String city, 
    String state, String zip, String phone )
         {
        	   	
            // A person has the following details
       	    person = new Person( firstName, lastName, address, city, state, zip, phone );
       	    
       	    // Add person to end of collection of persons
    	    collection.add( person );
       	    
       	  }
    /** 
          *  @return numberOfPersons in the address book 
          */
          public int getNumberOfPersons()
          {
              int numberOfPersons = 0;
        	  
        	  numberOfPersons     = collection.size();
        	 
        	  System.out.println( "No of persons in address book: " + numberOfPersons );
        	  
        	  return numberOfPersons;
        	  
          }
          
          /** 
           *  Get the person's full name
           *  @param getFirstName at position index
           *  @param getLastName at position index
           *  @return the person's full name at position index
           */
           public String getFullNameOfPerson( int index )
           {   
        	   String fullNameOfPerson = " "; //initialize
               
         	   fullNameOfPerson        = person.getFirstName() + " " + person.getLastName();
         	   
         	   System.out.print( "Full name: "+ fullNameOfPerson + "			" );
         	        	   
         	   return fullNameOfPerson;
        	   
           }
           
    
           /** 
            *  Provide the rest of the current information about a person
            *  @return an array of Strings,
            *  each containing one piece of stored information about this person.
            *  The person's name is _not_ included, since this is not changeable
            */
            public String[ ] getOtherPersonInformation( int index )
            { 
            	String address = person.getAddress();
                String city    = person.getCity();
                String state   = person.getState();
                String zip     = person.getZip();
                String phone   = person.getPhone();
                
                String[] otherPersonInformation = { address, city, state, zip, phone };
                
                for(int i = 0; i < otherPersonInformation.length; i++)
                	
                	System.out.print( otherPersonInformation[i] + ", " );
                	          	
                return otherPersonInformation;
            	
            }
    }
    Here is my AddressBookGUI class that is responsible for displaying the GUI with the address book data:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Observer;
    import java.util.Observable;
    
    /**	An object of this class allows interaction between the program 
     *     and the human user.
     */
    public class AddressBookGUI extends JFrame implements Observer
    {
    	/** Auto-generated serial ID used during deserialization to verify that the sender 
             *   and receiver of a 
    	 *  serialized object have loaded classes for that object that are compatible 
    	 *  with respect to serialization
    	 */
    	private static final long serialVersionUID = -2788112499712465126L; 
        
    	
      /** Constructor
        *
        *	@param controller the controller which performs operations in
        *		   response to user gestures on this GUI
        *	@param addressBook the AddressBook this GUI displays
        */
    
       @SuppressWarnings({ "unchecked", "rawtypes" }) 
    public AddressBookGUI(final AddressBookController controller,
       					  AddressBook addressBook)
       {
    	this.controller = controller;
    		
            // Create and add file menu
           
           JMenuBar menuBar = new JMenuBar();
           JMenu fileMenu = new JMenu("File");
           newItem = new JMenuItem("New", 'N');
           fileMenu.add(newItem);
           openItem = new JMenuItem("Open...", 'O');
           fileMenu.add(openItem);
           fileMenu.addSeparator();
           saveItem = new JMenuItem("Save", 'S');
           fileMenu.add(saveItem);
           saveAsItem = new JMenuItem("Save As...");
           fileMenu.add(saveAsItem);
           fileMenu.addSeparator();
           printItem = new JMenuItem("Print", 'P');
           fileMenu.add(printItem);
           fileMenu.addSeparator();
           quitItem = new JMenuItem("Quit", 'Q');
           fileMenu.add(quitItem);
           menuBar.add(fileMenu);
           setJMenuBar(menuBar);
           
    	   // The displayed list of names gets its information from the
    	   // address book
    		
    	   nameListModel = new NameListModel();
    				
    	   // The nameListModel and saveItem objects must exist before this is done;
    	   // but this must be done before the nameList is created
    		
    	   setAddressBook(addressBook);	
    		
           // Create and add components for the main window
           nameList = new JList(nameListModel);
           
           JScrollPane listPane = new JScrollPane(nameList);
           nameList.setVisibleRowCount(10);
           listPane.setBorder(BorderFactory.createCompoundBorder(
               BorderFactory.createEmptyBorder(10, 10, 10, 10), 
               BorderFactory.createLineBorder(Color.gray, 1)));
           getContentPane().add(listPane, BorderLayout.CENTER);
           JPanel buttonPanel = new JPanel();
           addButton = new JButton("     Add    ");
           buttonPanel.add(addButton);
           editButton = new JButton("    Edit    ");
           buttonPanel.add(editButton);
           deleteButton = new JButton("   Delete   ");
           buttonPanel.add(deleteButton);
           sortByNameButton = new JButton("Sort by name");
           buttonPanel.add(sortByNameButton);
           sortByZipButton = new JButton("Sort by ZIP ");
           buttonPanel.add(sortByZipButton);
           buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 10,
     10, 10));
           
           // Create and add search menu
           
           JMenu searchMenu = new JMenu("Search");
           findItem = new JMenuItem("Find", 'F');
           searchMenu.add(findItem);
           findAgainItem = new JMenuItem("Find Again");
           searchMenu.add(findAgainItem);
           menuBar.add(searchMenu);
           setJMenuBar(menuBar);
           
           getContentPane().add(buttonPanel, BorderLayout.SOUTH);
           
           // Add the action listeners for the buttons, menu items, and close box,
           // and for double-clicking the list
           
           addButton.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e)
               {
               	controller.doAdd(AddressBookGUI.this);
               	int index = getAddressBook().getNumberOfPersons() - 1;
               	
               	nameListModel.addElement(index);	
               	
                // This will ensure that the person just added is visible in list
               	nameList.ensureIndexIsVisible(index);
               	
               }
           });
          
    	setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
           addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent e)
               { 
    		try
    		{
    		     if (getAddressBook().getChangedSinceLastSave())
    			controller.doOfferSaveChanges(AddressBookGUI.this);
    
    			dispose();
    					
    			if (Frame.getFrames().length == 0)
    			AddressBookApplication.quitApplication();
    				}
                	catch(SecurityException exception)
    		{
    		// Thrown if security manager disallows the operation -
    		// will always happen in an applet
    					
    			reportError("Operation disallowed: " + exception);
    		}
    				
               }
           });
           
           
    		// The following is adapted from an example in the documentation
    		// for class JList.  It invokes the controller's doEdit method
    		// if the user double clicks a name.
    		
    		nameList.addMouseListener(new MouseAdapter() {
    			public void mouseClicked(MouseEvent e) 
    			{
    				if (e.getClickCount() == 2) 
    				{
    				  int index = nameList.locationToIndex(e.getPoint());
    			          controller.doEdit(AddressBookGUI.this, index);
    				}
    			}
    		});
    		
    		
    		pack();     
       }
       
    	/** Accessor for the address book this GUI displays
    	 *
    	 *	@return the current address book for this GUI
    	 */
    	public AddressBook getAddressBook()
    	{
    		
    		return addressBook;
    	}
    	
    	/** Mutator to change the address book this GUI displays
    	 *
    	 *	@param addressBook the new address book for this GUI
    	 */
    	public void setAddressBook(AddressBook addressBook)
    	{
    		if (this.addressBook != null)
    			this.addressBook.deleteObserver(this);
    			
    		this.addressBook = addressBook;
    		addressBook.addObserver(this);
    		update(addressBook, null);
    	}
    	
       /** Report an error to the user
        *
        *  @param message the message to display
        */
       public void reportError(String message)
       {
           JOptionPane.showMessageDialog(this, message, "Error message",
                              JOptionPane.ERROR_MESSAGE);
       }
       
    	/** Method required by the Observer interface - update the display
    	 *	in response to any change in the address book
    	 */
    	public void update(Observable o, Object arg)
    	{
    		//String displayName;
    		
    		if (o == addressBook)
    		{
    			setTitle(addressBook.getTitle());
    			saveItem.setEnabled(addressBook.
                                  getChangedSinceLastSave());
    			nameListModel.contentsChanged();
    			
    		}
    	}
    			
       // GUI components and menu items
       
       private NameListModel nameListModel;
       @SuppressWarnings("rawtypes")
       private JList nameList; 
       private JButton addButton, editButton, deleteButton, sortByNameButton, sortByZipButton;
       private JMenuItem newItem, openItem, saveItem, saveAsItem, printItem, quitItem;
       
       JMenuItem findItem, findAgainItem; 
       	  
       // The controller that performs operations in response to user gestures
    	
    	@SuppressWarnings("unused")
    	private AddressBookController controller;
    	
    	// The address book this GUI displays / operates on
    	
    	private AddressBook addressBook;
    	
    	/** 
    	 *  Class used for the model for the list of persons in the address book
    	 */
    	private class NameListModel extends AbstractListModel<Object> 
    	{
    	    /** 
    	     *  Auto-generated serial ID used during deserialization to verify that the sender and receiver of a 
    	     *  serialized object have loaded classes for that object that are compatible 
    	     *  with respect to serialization
    	     */
    		private static final long serialVersionUID = 4248634640032284749L;
    
    	   /** 
    	    *  Report that the contents of the list have changed
    	    */
    		void contentsChanged()
    		{
    			super.fireContentsChanged(this, 0, 0);
    		}
    	 
    	   /** 
    	    *  Report that an element has been removed from the index
    	    */
    	    void removeElement(int index) 
    	    {
    		   super.fireIntervalRemoved(this, index, index);
    	    }
    	 
    	   /** 
    	    *  Report that an element has been added to the index 
    	    */
    	     void addElement(int index) 
    	    {
    		super.fireIntervalAdded(this, index, index);
    
    	    }
    		
    			   
    		// Implementation of abstract methods of the base class
    		
    		/** Get the person's complete details
    		 *  @ return full of person and other personal information
    		 */
    		public Object getElementAt(int index)
    		{   		
    			String gap = "         				";
    			String comma = ", 					";
    			
    			return getAddressBook().getFullNameOfPerson(index) 
    +  gap  + getAddressBook().getOtherPersonInformation(index)[0]	                                              
    + comma + getAddressBook().getOtherPersonInformation(index)[1]
    + comma + getAddressBook().getOtherPersonInformation(index)[2]
    + comma + getAddressBook().getOtherPersonInformation(index)[3]
    + comma + getAddressBook().getOtherPersonInformation(index)[4];
    		}
    
    		/** Get the size of the Address book
    		 *  @return number of persons in the address book
    		 */
    		public int getSize()
    		{
    			return getAddressBook().getNumberOfPersons();
    		}
    	}
    
    }
    In my AddressBookController class, the doAdd code is written like below:

    Java Code:
    /** 
     *  An object of this class performs operations on the address book in response 
     *  to user gestures on the GUI 
     */
    
    public class AddressBookController extends java.lang.Object {
    	
        /** 
         *  Constructor to create object of FileSystem to interact with the file system
         */
        public AddressBookController( FileSystem fileSystem )
        {
          	fileSystem = new FileSystem();
        }
       public void doAdd( AddressBookGUI gui )
        {
        	// The title of this dialog frame     	   	
        	String title_Of_Dialog  = ( "New Person" );
        	
        	// Create fields for user input
        	String dialog_prompts[] = {
        			"Enter First name",
        	    	"Enter Last name",
        	    	"Enter address",
        	    	"Enter city",
        	    	"Enter state",
        	    	"Enter zip code",
        	    	"Enter phone" 
        	    	};
        	
        	// Prompt for Person details
        	String dialog [] = MultiInputPane.showMultiInputDialog
                             ( gui, dialog_prompts, title_Of_Dialog );
        	
        	// Store dialog_prompts details of the user
        	String firstName = dialog [0];
        	String lastName  = dialog [1];
        	String address   = dialog [2];
        	String city      = dialog [3];
        	String state     = dialog [4];
        	String zip       = dialog [5];
        	String phone     = dialog [6];
        	
        	// Show added person in main window
        	
        	gui.getAddressBook().addPerson( firstName, lastName, 
                                 address, city, state, zip, phone );
        	
        }
    }
    The main class runs with this code:

    Java Code:
    import java.awt.Frame;
    import java.awt.event.WindowEvent;
    public class AddressBookApplication {
    
    public static void main(String [] args)
        {
    	FileSystem fileSystem = new FileSystem();
    	AddressBookController controller = new AddressBookController
    (fileSystem);
    	AddressBookGUI gui = new AddressBookGUI(controller, 
    new AddressBook());
    	gui.setVisible(true); 
    				
        Frame openedWindow = new Frame();
    		openedWindow.addWindowListener
                       ( new java.awt.event.WindowAdapter() 
    		{
    		    public void windowClosing( WindowEvent winEvt ) 
    		    {
    		    	winEvt.equals(false);
    		        quitApplication(); 
    		    }
    		} );
    		
        }
        
        /** Terminate the application (unless cancelled by the user)
         */
        public static void quitApplication()
        {
    		// When the user requests to quit the application, any open
    		// windows must be closed
    		Frame [] openWindows = Frame.getFrames();
    		for (int i = 0; i < openWindows.length; i ++)
    		{
    			// Attempt to close any window that belongs to this program
    			
    			if (openWindows[i] instanceof AddressBookGUI)
    			{
    				openWindows[i].dispatchEvent(new WindowEvent(
    								 openWindows[i], 
    								 WindowEvent.WINDOW_CLOSING));
    								 
                    // If the window is still showing, this means that this attempt 
                    // to close the window was cancelled by the user - so abort the
                    // quit operation
                    
     				if (openWindows[i].isShowing())
                        return;
    			}
    		}
    
    		// If we get here, all open windows have been successfully closed 
    		// (i.e. the user has not cancelled an offer to save any of them).
    		// Thus, the application can terminate.
    		
    		System.exit(0);
    	}
    }
    Please help!
    Last edited by Allexxy; 02-03-2012 at 11:31 PM. Reason: code tags added

  2. #2
    tnrh1 is offline Senior Member
    Join Date
    Aug 2011
    Posts
    251
    Rep Power
    4

    Default Re: Problem with updating ListModel

    Use the code tag, it's not readable.

  3. #3
    Allexxy is offline Member
    Join Date
    Feb 2012
    Location
    Lagos, Nigeria
    Posts
    7
    Rep Power
    0

    Default Re: Problem with updating ListModel

    Sorry about the no code tags...just registered. Hope everything's clearer now. Thanks

  4. #4
    Allexxy is offline Member
    Join Date
    Feb 2012
    Location
    Lagos, Nigeria
    Posts
    7
    Rep Power
    0

    Default Re: Problem with updating ListModel

    Right...

    So, I've tried to isolate the problem by looking at only the Addressbook class. I tweaked it a little like below
    Java Code:
    public class AddressBook extends java.util.Observable implements java.io.Serializable
    {
    	/**
    	 *  Auto-generated serial ID used during deserialization to verify that the sender and receiver of a 
    	 *  serialized object have loaded classes for that object that are compatible 
    	 *  with respect to serialization
    	 */
    	 private static final long serialVersionUID = 6094697971638342871L;
    
    	 /**
    	  *  Declare a global change flag that tells us the address book has been updated
    	  */
    	 private boolean changedSinceLastSave;
    
    	/** 
    	 *  Declare a variable of type Person
         */
         private static Person person;
         
         
        /** 
         *  Create a collection of persons for the address book
         *  Constructs a global list of persons in a collection.
         *  
         *  @element-type Person
         */
         private List <Person> collection; 
       
    
         //private int currentPersonIndex;
         
        /** 
         *  Create a new, empty address book 
         */
         public AddressBook( )
         {
        	 // No initial changes to address book 
        	 changedSinceLastSave = false;
        	 
        	 // Here, a Vector of type Person object is created and 
        	 // the resulting handle is immediately assigned to the global List
        	 collection = new Vector < Person > ();
        	 
         }
                   
        /** 
         *  Add a new person to the collection
         *  
         *  @param addElement person to collection
         */
         public void addPerson( String firstName, String lastName, String address, String city, String state, String zip, String phone )
         {
        	// Create a new person with the following details
        	person = new Person( firstName, lastName, address, city, state, zip, phone );
        	    	 
            // Then add person to end of collection of persons
    		collection.add(person);
    						
    		// Changes have been made to the address book
    		setChangedSinceLastSave(true);
    	 }
         
        /** 
         *  @return numberOfPersons in the address book 
         */
         public int getNumberOfPersons()
          {
              int numberOfPersons = 0;
        	  
              numberOfPersons     = collection.size();
        	 
        	  return numberOfPersons;
          }
          
          /** 
           *  Get the person's full name
           *  @param getFirstName at position index
           *  @param getLastName at position index
           *  @return the person's full name at position index
           */
           public String getFullNameOfPerson( int index )
           {   
        	   index = collection.lastIndexOf(person);
        	   
        	   String fullNameOfPerson = collection.get(index).fullName();
         	     	   
           	   return fullNameOfPerson;
           }
           
           /** 
            *  Provide the rest of the current information about a person
            *  @return an array of Strings,
            *  each containing one piece of stored information about this person.
            *  The person's name is _not_ included, since this is not changeable
            */
            public String[ ] getOtherPersonInformation( int index )
            { 
            	index = collection.indexOf(person);
            	
            	String address = collection.get(index).getAddress();
                String city    = collection.get(index).getCity();
                String state   = collection.get(index).getState();
                String zip     = collection.get(index).getZip();
                String phone   = collection.get(index).getPhone();
                        	           
                String[] otherPersonInformation = { address, city, state, zip, phone };
                
                return otherPersonInformation;
            	
            }
            
            /** 
             *  Update stored information about a person
             *  @param index  - the position of the desired person
             *  @param address - the person's new address
             *  @param city - the person's new city
             *  @param state - the person's new state
             *  @param zip - the person's new zip
             *  @param phone - the person's new phone
             */
             public void updatePerson( int index, String address, String city, String state, String zip, String phone )
             {
            	 index = getNumberOfPersons() - 1;
            	         	 
            	 //getOtherPersonInformation( index );
            	 
            	 collection.get(index).update(address, city, state, zip, phone);
                 
            	// Changes have been made to the address book
            	 setChangedSinceLastSave(true);
             }
            
            /** 
             *  Print the collection of persons in order
             */
    public void printAll( )
             {
    			Iterator <Person> it = collection.iterator();
    			
    			if(collection.isEmpty())
           	   {
           		   System.out.println( "There are no names in the addressBook" );
           		   return;
           	   }
           	   else
           		   while( it.hasNext() )
           			
           			  System.out.println(it.next() + "");
               
           			  return;
           			  
           	}
    }
    Then I test with the following class

    Java Code:
    public class AddressBookTest {
    
    	//http://www.roseindia.net/answers/viewqa/Java-Beginners/18323-Java-Method-with-arrays.html
    	
    	public static void main (String args [])
    	{
    		// An instance of Addressbook
    		AddressBook addressbook = new AddressBook();
    		
    		// Declare three new instances of Person for the AddressBook
    		Person person1 = new Person("Lily", "Prescott", "23 Hillside", "Pel", "Ala", "37833", "02086786889");
    		Person person2 = new Person("David", "Hill", "2 Benson", "Sel", "NY", "90671", "02086786889");
    		Person person3 = new Person("Sally", "Fields", "5 Love Street", "Miami", "Fl", "43321", "020987868676");
    			
    		// Add persons
    		// Print out Full name and Other information
    		addressbook.addPerson( person1.getFirstName(), person1.getLastName(), person1.getAddress(), person1.getCity(), person1.getState(), person1.getZip(), person1.getPhone() );
    		addressbook.addPerson( person2.getFirstName(), person2.getLastName(), person2.getAddress(), person2.getCity(), person2.getState(), person2.getZip(), person2.getPhone() );
    		addressbook.addPerson( person3.getFirstName(), person3.getLastName(), person3.getAddress(), person3.getCity(), person3.getState(), person3.getZip(), person3.getPhone() );
    		System.out.println("********************************************************************");
    		System.out.println("--How many persons are in the addressbook?--");
    		System.out.println();
    		System.out.println("No of persons in the Address Book is: " + addressbook.getNumberOfPersons());
    		System.out.println("********************************************************************");
    		System.out.println("--Print just the full names of persons in the addressbook--");
    		
    		// No of persons in address book
    		int index = addressbook.getNumberOfPersons();
    		for(int i = 0; i < index; i++){
    			index = 1;
    			System.out.println("Full name: " + addressbook.getFullNameOfPerson(i));
    		
    			index++;
    		}
    		//System.out.println("Full name: " + person1.fullName());
    		//System.out.println("Full name: " + person2.fullName());
    		//System.out.println("Full name: " + person3.fullName());
    		//System.out.println();
    		
    				
    		// Update second person's address and print it out
    		System.out.println("********************************************************************");
    		System.out.println();
    		System.out.println("--Update David Hill's address--");
    		System.out.println();
    		
    		String address = person2.getAddress();
    		String city    = person2.getCity();
    		String state   = person2.getState();
    		String zip     = person2.getZip();
    		String phone   = person2.getPhone();
    		
    		System.out.println("David Hill's old address was: " + person2.getAddress());
    		// Set new address
    		address = "9 Pry Lane";
    		person2.update(address, city, state, zip, phone);
    		System.out.println();
    		System.out.println("David Hill's new address is: " + person2.getAddress());
    		System.out.println();
    		System.out.print("His complete details are: ");
    		String [] OtherInformation1 = person2.otherPersonalInformation();
    		
    		for(int i = 0; i < OtherInformation1.length; i++){
    			
    			System.out.print( OtherInformation1[i] + ", " );
    		}
    		// update second person's details in the address book
    		addressbook.updatePerson(index, address, city, state, zip, phone);
    		
    		// Print all the names in the addressbook
    		System.out.println();
    		System.out.println("********************************************************************");
    		System.out.println("--Print all the names in the address book--");
    		
                    addressbook.printAll();
    		
    	}
    }
    This is the output:

    ************************************************** ******************
    --How many persons are in the addressbook?--

    No of persons in the Address Book is: 3
    ************************************************** ******************
    --Print just the full names of persons in the addressbook--
    Full name: Sally Fields
    Full name: Sally Fields
    ************************************************** ******************

    --Update David Hill's address--

    David Hill's old address was: 2 Benson

    David Hill's new address is: 9 Pry Lane

    His complete details are: 9 Pry Lane, Sel, NY, 90671, 02086786889,
    ************************************************** ******************
    --Print all the names in the address book--
    Lily Prescott 23 Hillside, Pel, Ala, 37833, 02086786889
    David Hill 2 Benson, Sel, NY, 90671, 02086786889
    Sally Fields 9 Pry Lane, Sel, NY, 90671, 02086786889


    1. If you notice where it is supposed to print out just full names...it duplicates the last person
    2. After updating the second person's details (David Hill)...when its to print all names in the address book...you find its updated the last name instead (Sally Fields).

    Help...please
    Last edited by Allexxy; 02-17-2012 at 12:24 AM.

  5. #5
    Allexxy is offline Member
    Join Date
    Feb 2012
    Location
    Lagos, Nigeria
    Posts
    7
    Rep Power
    0

    Default Re: Problem with updating ListModel

    o.k...i solved problem 1...it was caused by the following code in the Addressbook class, inside the getFullNameOfPerson( int index ) method.

    Java Code:
     index = collection.lastIndexOf(person);
    when I commented it out, it worked.

    I believe this the same reason why problem 2, the update of person 2 is not perfected. Its not able to access the address details properly. Have a look at this method.

    Java Code:
    /**
            *  Provide the rest of the current information about a person
            *  @return an array of Strings,
            *  each containing one piece of stored information about this person.
            *  The person's name is _not_ included, since this is not changeable
            */
            public String[ ] getOtherPersonInformation( int index )
            {
                index = collection.indexOf(person);
                 
                String address = collection.get(index).getAddress();
                String city    = collection.get(index).getCity();
                String state   = collection.get(index).getState();
                String zip     = collection.get(index).getZip();
                String phone   = collection.get(index).getPhone();
                                        
                String[] otherPersonInformation = { address, city, state, zip, phone };
                 
                return otherPersonInformation;
                 
            }
    In the test class, I have

    Java Code:
    // Print Other personal information
    		String [] OtherInformation = addressbook.getOtherPersonInformation(index);
    		System.out.println();
    		System.out.println("OtherInformation: ");
    		for(int i = 0; i < index; i++){
    			index = 2;
    			for(int j = 0; j < OtherInformation.length; j++)
    			{
    				System.out.println( OtherInformation[j] + ", " );
    				
    			}
    			System.out.println();
    			index++;
    		}
    This is the output

    OtherInformation:
    5 Love Street,
    Miami,
    Fl,
    43321,
    020987868676,

    5 Love Street,
    Miami,
    Fl,
    43321,
    020987868676,

    5 Love Street,
    Miami,
    Fl,
    43321,
    020987868676,

    I know the problem is the 'index' in the method. It needs to loop through the collection and allow to print all the person objects. But, no matter what you try...it allows one object at a time.

    I have tried
    Java Code:
     index = 0; // Prints only the first person three times
    Also
    Java Code:
     index = 0;
                               index++; // Will print only the second person three times
    I have tried different kinds of for loop...no success.

    Any one with ideas, will be greatly appreciated...thanks

Similar Threads

  1. problem updating a drawnString
    By liluma in forum New To Java
    Replies: 3
    Last Post: 06-07-2011, 07:26 PM
  2. Problem updating access database from jsp
    By Penhexy in forum JavaServer Pages (JSP) and JSTL
    Replies: 1
    Last Post: 03-17-2011, 09:50 AM
  3. Problem with method updating node I don't want it to...
    By sonofshirt in forum New To Java
    Replies: 6
    Last Post: 09-26-2010, 08:14 PM
  4. Problem with updating empty JTable
    By byubi in forum AWT / Swing
    Replies: 1
    Last Post: 05-15-2010, 09:31 AM
  5. Problem with updating JTable
    By kwaspl in forum New To Java
    Replies: 2
    Last Post: 12-20-2009, 11:41 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •