g_currier
asked on
Adding objects to ArrayLists and inheritance
I have been working diligently on this project and I fell I am now stuck. After remodeling everything to match requirements (and "kind of" getting a blessing on the Person,Friend,Address classes) I started to rewrite the Contact class to perform operations on the ArrayList, including file input for sample data. I'm stuck.
First, I've tried to understand inheritance And I think I have it right between person and Friend. However, Address is another issue. I can add a Friend item to the ArrayList which includes items from Person but I do not know where to start with adding the address to the friend object. I think I have most of it, but I am lost.
Second, I can add objects to the ArrayList but I am not certain that what I have printed out is correct (from running the addContact() method. The print out shows everything prettily but it would be nice for someone to look over it and make sure I did it right before I start to try and build the methods into actionEvents for the GUI.
Thanks.
the code is below
main()
First, I've tried to understand inheritance And I think I have it right between person and Friend. However, Address is another issue. I can add a Friend item to the ArrayList which includes items from Person but I do not know where to start with adding the address to the friend object. I think I have most of it, but I am lost.
Second, I can add objects to the ArrayList but I am not certain that what I have printed out is correct (from running the addContact() method. The print out shows everything prettily but it would be nice for someone to look over it and make sure I did it right before I start to try and build the methods into actionEvents for the GUI.
Thanks.
the code is below
main()
package P4.v2;
public class AddressBook {
public static void main(String[] args) {
Contact c = new Contact();
// if (args.length != 1) {
// System.err.println("usage: java TextScanner2"
// + "file location");
// System.exit(0);
// }
// readFile(args[0]);
c.readFromFile("input.txt");
//new AddressBookGUI();
}
}
Contact class (operations)package P4.v2;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Contact {
ArrayList<Person> contactList = new ArrayList<Person>();
protected int numContacts;
Person person;
Friend friend;
Address address;
public Contact() {
numContacts = 0;
}
public int getNumContacts() {
return numContacts;
}
public void setNumContacts(int numContacts) {
this.numContacts = numContacts;
}
public Object getPerson(int index) {
return contactList.get(index);
}
public int getContactListSize() {
return contactList.size();
}
public void addAnotherPerson(Person person) {
numContacts += getNumContacts();
}
public void addPerson(Person person) {
int size = contactList.size();
if (contactList.indexOf(person) > -1) {
ArrayList newContactList = new ArrayList();
Person person1 = (Person)contactList.get(size - 1);
newContactList.add(person1);
contactList = newContactList;
} else {
contactList.add(person);
}
System.out.println("size: " + contactList.size() + " at Index: "
+ size + "" + " " + contactList.get(contactList.size() - 1));
}
//break the input file down into lines of text using line.separator as a delimiter
public void readFromFile(String inFile) {
try {
Scanner scanner = new Scanner(new File(inFile));
scanner.useDelimiter(System.getProperty("line.separator"));//(";");
while (scanner.hasNext()) {
addLine(scanner.next());
}
System.out.println();
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//break the lines of text down into individual strings using a comma as a delimiter
public void addLine(String line) {
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter(",");
while (lineScanner.hasNext()) {
int index = 0;
//these can be replaced with JTextField<TextFieldName>.getText();
String lName = lineScanner.next();
String mName = lineScanner.next();
String fName = lineScanner.next();
String streetName = lineScanner.next();
String cityName = lineScanner.next();
String stateName = lineScanner.next();
String zipCode = lineScanner.next();
String hPhone = lineScanner.next();
String cPhone = lineScanner.next();
person = new Friend(lName, fName, mName, hPhone, cPhone);
address = new Address(streetName, cityName, stateName, zipCode);
addPerson(person);
//System.out.println(getPerson(index));
index++;
}//end while loop
lineScanner.close();
// for (Person element : contactList) {
// System.out.println(element.toString());
// }
// try{
// System.err.println("\n\nAttempt to print all elements of ArrayList \"contactList\" using a \"for\" loop:");
// for (int i = 0; i<=contactList.size()-1; i++){
// System.out.println(contactList.get(i)+" at index:"+i);
// }
// }catch (Exception e){
// System.out.println("\n\nIndexOutOfBoundsExeption thrown, check addContacts() - \n"
// + "Person objects not being added to the end of the ArrayList.\n");
// System.out.println(e);
// }
// System.out.println(getPerson(index));
// System.out.println();
}//end addContact method
}//end Contact class
Person Classpackage P4.v2;
public class Person{
private String lName,fName,mName;
public Person(){
}
public Person(String lName, String fName, String mName) {
setLName(lName);
setFName(fName);
setMName(mName);
}
public String getFName() {
return fName;
}
public String getLName() {
return lName;
}
public String getMName() {
return mName;
}
public void setFName(String fName) {
this.fName = fName;
}
public void setLName(String lName) {
this.lName = lName;
}
public void setMName(String mName) {
this.mName = mName;
}
public String getPersonToString() {
return lName + " " + fName + " " + mName;
}
public String toString() {
return lName + " " + fName + " " + mName;
}
}
Friend Classpackage P4.v2;
public class Friend extends Person {
private String hPhone, cPhone;
private Address address;
public Friend() {
super();
}
public Friend(String lName, String fName, String mName) {
super(lName, fName, mName);
}
public Friend(String lName, String fName, String mName, String hPhone, String cPhone) {
super(lName, fName, mName);
sethPhone(hPhone);
setcPhone(cPhone);
}
public Friend(String hPhone, String cPhone) {
sethPhone(hPhone);
setcPhone(cPhone);
}
public String getcPhone() {
return cPhone;
}
public void setcPhone(String cPhone) {
this.cPhone = cPhone;
}
public String gethPhone() {
return hPhone;
}
public void sethPhone(String hPhone) {
this.hPhone = hPhone;
}
public Friend getFriend(){
return this;
}
@Override
public String toString() {
return getPersonToString() + " " + hPhone + " " + cPhone;
}
}
Address Classpackage P4.v2;
public class Address extends Friend {
private String streetName, cityName, stateName, zipCode;
private Person person = new Person();
public Address() {
super();
}
public Address(String lName, String fName, String mName, String hPhone, String cPhone){
super(lName, fName, mName,hPhone,cPhone);
}
public Address(String lName, String fName, String mName, String hPhone, String cPhone,
String streetName, String cityName, String stateName, String zipCode){
super(lName, fName, mName,hPhone,cPhone);
setStreetName(streetName);
setCityName(cityName);
setStateName(stateName);
setZipCode(zipCode);
}
public Address(String streetName, String cityName, String stateName, String zipCode){
setStreetName(streetName);
setCityName(cityName);
setStateName(stateName);
setZipCode(zipCode);
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public Address getAddress(){
return this;
}
public String getAddressToString(){
return streetName + " " + cityName + " " + stateName + " " + zipCode;
}
@Override
public String toString() {
return streetName + " " + cityName + " " + stateName + " " + zipCode;
}
}
Firstly, can you post the complete spec for your project?
ASKER
attached.
By the way, this is the output:
By the way, this is the output:
run:
size: 1 at Index: 0 Smith John P (126)598-4580 (321)650-9874
size: 2 at Index: 1 Public John Q (445)896-5023 (326)551-4987
size: 3 at Index: 2 Nobody Jane X (654)613-2987 (985)864-7123
size: 4 at Index: 3 Smythe Gordon P (125)487-4580 (321)616-5974
size: 5 at Index: 4 Xavier Chuck P (659)228-4580 (375)450-9874
size: 6 at Index: 5 Furball Harry P (800)867-5309 (903)576-8008
size: 7 at Index: 6 brody willy f (186)345-2931 (325)457-4523
size: 8 at Index: 7 wright danielle g (284)342-2167 (967)856-7167
size: 9 at Index: 8 sane Not n (853)567-9217 (165)456-7423
size: 10 at Index: 9 toothless Ai m (174)345-9021 (475)342-7321
size: 11 at Index: 10 jobless lane n (724)342-1342 (327)342-2623
BUILD SUCCESSFUL (total time: 0 seconds)
AddressBookProject.pdf
Thanks for that. It's clear that whoever set the spec knows nothing about design - or worse, they know a little.
Shall be back later after further perusal
Shall be back later after further perusal
ASKER
:-/ She's my professor...lol
Here's a tip for inheritance:
think of something inheriting something else as a way of getting more specific. For example: A Person has a name. A Friend is a specific type of person, where you know there phone number and email. That is why Friend inherits Person. Friend IS A Person. But not all Persons are Friends.
Based on this - I see 1 minor problem with your code:
It doesn't make sense for an Address to extend a Person. Addresses don't really have names in the same sense as Persons, nor would they have Friends.
However, a Friend would have an Address associated with them, meaning that a Friend would contain an Address field. That's a HAS A relationship. It also saves you the trouble of trying to associate a Person with an Address inside the Address class. I would drop that field, and save yourself a headache, because having these 2 directionally references (Friend HAS An Address, and Address HAS A Friend) can lead to a lot of problems if the references get out of sync.
To add an address to a Friend, I would suggest adding a couple of methods to the Friend class: a getter and setter.
so, Friend woudl have a setAddress(Address a) method to set the Address field in Friend person to a, and getAddress() method that would return the set address (this isn't really required, but good practice).
Hope this helps,
Shura
think of something inheriting something else as a way of getting more specific. For example: A Person has a name. A Friend is a specific type of person, where you know there phone number and email. That is why Friend inherits Person. Friend IS A Person. But not all Persons are Friends.
Based on this - I see 1 minor problem with your code:
It doesn't make sense for an Address to extend a Person. Addresses don't really have names in the same sense as Persons, nor would they have Friends.
However, a Friend would have an Address associated with them, meaning that a Friend would contain an Address field. That's a HAS A relationship. It also saves you the trouble of trying to associate a Person with an Address inside the Address class. I would drop that field, and save yourself a headache, because having these 2 directionally references (Friend HAS An Address, and Address HAS A Friend) can lead to a lot of problems if the references get out of sync.
To add an address to a Friend, I would suggest adding a couple of methods to the Friend class: a getter and setter.
so, Friend woudl have a setAddress(Address a) method to set the Address field in Friend person to a, and getAddress() method that would return the set address (this isn't really required, but good practice).
Hope this helps,
Shura
ASKER
oops...that was a mistake...Address was supposed to extend friends (i thought i changed it). I'll give it a try and come back.
Glen
Glen
Dont worry - you do not want Address to extend Friend. A Friend HAS An Address (it contains an Address in the object), but does it make sense to say an Address IS A Friend? No. So I would make the class definition like this:
public class Address {
...
}
By the way, the HAS A/IS A relationship can be fairly helpful in determine inheritance v. composition relationships.
Composition means that something contains a reference to something else. Your Friend class is an excellent example of composition. A friend is composed of an address and some other stuff.
If it makes sense to say something IS A something else, then its a good candidate for inheritance. If it makes sense to say something HAS A something else, then its a good candidate for composition.
Composition means that something contains a reference to something else. Your Friend class is an excellent example of composition. A friend is composed of an address and some other stuff.
If it makes sense to say something IS A something else, then its a good candidate for inheritance. If it makes sense to say something HAS A something else, then its a good candidate for composition.
ASKER
Ok,
changes as follows:
Contact class:
Friend Class:
Address Class:
Console output:
changes as follows:
Contact class:
public Friend(String lName, String fName, String mName,
String hPhone, String cPhone,
String streetName, String cityName, String stateName, String zipCode) {
super(lName, fName, mName);
sethPhone(hPhone);
setcPhone(cPhone);
setAddress(streetName,cityName,stateName,zipCode);
}
Friend Class:
package P4.v2;
public class Friend extends Person {
private String hPhone, cPhone;
public Address a = new Address();
public Friend() {
super();
}
public Friend(String lName, String fName, String mName) {
super(lName, fName, mName);
}
public Friend(String lName, String fName, String mName,
String hPhone, String cPhone) {
super(lName, fName, mName);
sethPhone(hPhone);
setcPhone(cPhone);
}
public Friend(String lName, String fName, String mName,
String hPhone, String cPhone,Address address){
super(lName, fName, mName);
sethPhone(hPhone);
setcPhone(cPhone);
setAddress(address);
}
public Friend(String hPhone, String cPhone) {
sethPhone(hPhone);
setcPhone(cPhone);
}
//Address accessors and mutators
public String getAddress() {
return a.getAddressToString();
}
public void setAddress(Address a){
a = new Address(a);
}
public String getcPhone() {
return cPhone;
}
public void setcPhone(String cPhone) {
this.cPhone = cPhone;
}
public String gethPhone() {
return hPhone;
}
public void sethPhone(String hPhone) {
this.hPhone = hPhone;
}
public Friend getFriend(){
return this;
}
@Override
public String toString() {
return getPersonToString() + " " + hPhone + " " + cPhone;
}
}
Address Class:
package P4.v2;
import java.util.ArrayList;
public class Address{
private String streetName, cityName, stateName, zipCode;
public Address() {
}
public Address(Address address){
}
public Address(String streetName, String cityName, String stateName, String zipCode){
setStreetName(streetName);
setCityName(cityName);
setStateName(stateName);
setZipCode(zipCode);
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getAddressToString(){
return streetName +cityName +stateName +zipCode;
}
@Override
public String toString() {
return streetName + " " + cityName + " " + stateName + " " + zipCode;
}
}
Console output:
run:
size: 1 at Index: 0 Smith John P (126)598-4580 (321)650-9874abc 123rd ave nowhere NJ 12548
size: 2 at Index: 1 Public John Q (445)896-5023 (326)551-49875th Ave w smalltown NC 97548
size: 3 at Index: 2 Nobody Jane X (654)613-2987 (985)864-7123123 abc st Somewhere OK 56986
size: 4 at Index: 3 Smythe Gordon P (125)487-4580 (321)616-5974def 133rd ave hoboken NJ 23562
size: 5 at Index: 4 Xavier Chuck P (659)228-4580 (375)450-98743 Private dr. Westchester NY 12548
size: 6 at Index: 5 Furball Harry P (800)867-5309 (903)576-80082 Desert Rd someplace sunny NV 84521
size: 7 at Index: 6 brody willy f (186)345-2931 (325)457-4523123 xyz ave Someplace NE 52387
size: 8 at Index: 7 wright danielle g (284)342-2167 (967)856-7167123 abc st lost WY 65986
size: 9 at Index: 8 sane Not n (853)567-9217 (165)456-7423123 abc st faraway KS 56039
size: 10 at Index: 9 toothless Ai m (174)345-9021 (475)342-7321123 abc st in the woods OR 91827
size: 11 at Index: 10 jobless lane n (724)342-1342 (327)342-2623123 abc st orange grove FL 84573
BUILD SUCCESSFUL (total time: 0 seconds)
ASKER
Correction to contact class
package P4.v2;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Contact {
ArrayList<Person> contactList = new ArrayList<Person>();
protected int numContacts;
Person person;
Friend friend;
Address address;
public Contact() {
numContacts = 0;
}
public int getNumContacts() {
return numContacts;
}
public void setNumContacts(int numContacts) {
this.numContacts = numContacts;
}
public Object getPerson(int index) {
return contactList.get(index);
}
public int getContactListSize() {
return contactList.size();
}
public void addAnotherPerson(Person person) {
numContacts += getNumContacts();
}
public void addPerson(Person person) {
int size = contactList.size();
if (contactList.indexOf(person) > -1) {
ArrayList newContactList = new ArrayList();
Person person1 = (Person)contactList.get(size - 1);
newContactList.add(person1);
contactList = newContactList;
} else {
contactList.add(person);
}
System.out.print("size: " + contactList.size() + " at Index: "
+ size + "" + " " + contactList.get(contactList.size() - 1));
System.out.println(address.toString());
//System.out.println(person.toString());
//System.out.println(friend.toString());
}
//break the input file down into lines of text using line.separator as a delimiter
public void readFromFile(String inFile) {
try {
Scanner scanner = new Scanner(new File(inFile));
scanner.useDelimiter(System.getProperty("line.separator"));//(";");
while (scanner.hasNext()) {
addLine(scanner.next());
}
System.out.println();
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//break the lines of text down into individual strings using a comma as a delimiter
public void addLine(String line) {
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter(",");
while (lineScanner.hasNext()) {
int index = 0;
//these can be replaced with JTextField<TextFieldName>.getText();
String lName = lineScanner.next();
String mName = lineScanner.next();
String fName = lineScanner.next();
String streetName = lineScanner.next();
String cityName = lineScanner.next();
String stateName = lineScanner.next();
String zipCode = lineScanner.next();
String hPhone = lineScanner.next();
String cPhone = lineScanner.next();
//CONSTRUCT OBJECTS
address = new Address(streetName, cityName, stateName, zipCode);
person = new Friend(lName, fName, mName, hPhone, cPhone,
address);
addPerson(person);
//System.out.println(getPerson(index));
index++;
}//end while loop
lineScanner.close();
// for (Person element : contactList) {
// System.out.println(element.toString());
// }
// try{
// System.err.println("\n\nAttempt to print all elements of ArrayList \"contactList\" using a \"for\" loop:");
// for (int i = 0; i<=contactList.size()-1; i++){
// System.out.println(contactList.get(i)+" at index:"+i);
// }
// }catch (Exception e){
// System.out.println("\n\nIndexOutOfBoundsExeption thrown, check addContacts() - \n"
// + "Person objects not being added to the end of the ArrayList.\n");
// System.out.println(e);
// }
// System.out.println(getPerson(index));
// System.out.println();
}//end addContact method
}//end Contact class
That looks great. Most importantly, do you understand it? I'll double the gui stuff tonight
ASKER
I kind of understand it (I actually came across the answer about half by accident and half knowing what I was doing...if that makes any sense)
Still, less of a guess and more knowing what looked right.
Still, less of a guess and more knowing what looked right.
ASKER
The problem still remains however, when I use the GUI to add (or even if I don't) the address doesn't get fed into the arraylist AND the arraylist is reinitialized for each entry (reducing the arraylist size to one element). Without a new Contact() the addContact method from Book Actions throws a nullpointerexcpetion.
I've attached the GUI and the actions class
AddressBookGUI:
and the console output:
input info:
I've attached the GUI and the actions class
AddressBookGUI:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package P4.v2;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
/**
*
* @author gcurrier
*/
public class AddressBookGUI implements ActionListener {
JLabel lName, mName, fName, street, city, state, zip, hPhone, cPhone;
public static JTextField lastName, middleName, firstName, streetName, cityName, stateName, zipCode, homePhone, cellPhone;
JButton add, delete, first, previous, next, last, sort, search, clear, exit;
JPanel dataPanel, buttonPanel, containerPanel;
JMenuBar menuBar = new JMenuBar(); //= new JMenuBar();
JMenu menu; //= new JMenu();
JMenuItem menuItem; //= new JMenuItem();
JFrame frame;
//establish Titled Border font size
Font borderFont = new Font("Sans Serif", Font.TRUETYPE_FONT, 10);
//String data;
AddressBookGUI() {
// lastName.setText(null);
// middleName.setText(null);
// firstName.setText(null);
// streetName.setText(null);
// cityName.setText(null);
// stateName.setText(null);
// zipCode.setText(null);
// homePhone.setText(null);
// cellPhone.setText(null);
frame = new JFrame("Address Book");
//frame.setSize(600, 360);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
addWindowItems();
frame.setResizable(true);
frame.pack();
frame.setVisible(true);
}
/**
*
*/
public void addWindowItems() {
//add a menu to the menu bar
//menuBar.add(menu);
menu = new JMenu("Options");
//"Options" menu items
menuItem = new JMenuItem("Load Sample Data");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Add Contact");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Delete Contact");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Sort");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Search");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Exit");
menu.add(menuItem);
menuItem.addActionListener(this);
//add another menu to the menu bar
menuBar.add(menu);
menu = new JMenu("Help");
//"Help" menu items
menuItem = new JMenuItem("Help...");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("About");
menu.add(menuItem);
menuItem.addActionListener(this);
menuBar.add(menu);
frame.setJMenuBar(menuBar);
/*
* labels and text fields
*/
lName = new JLabel("Last Name:");
lastName = new JTextField(30);
mName = new JLabel("Middle Name:");
middleName = new JTextField(30);
fName = new JLabel("First Name:");
firstName = new JTextField(30);
street = new JLabel("Street Address:");
streetName = new JTextField(30);
city = new JLabel("City:");
cityName = new JTextField(30);
state = new JLabel("State:");
stateName = new JTextField(2);
zip = new JLabel("Zip:");
zipCode = new JTextField(5);
hPhone = new JLabel("Home Phone:");
homePhone = new JTextField(15);
cPhone = new JLabel("Cell Phone:");
cellPhone = new JTextField(15);
/*
* buttons
*/
add = new JButton("Add Contact");
delete = new JButton("Delete Contact");
first = new JButton("First Record");
previous = new JButton("Next Record");
next = new JButton("Previous Record");
last = new JButton("Last Record");
sort = new JButton("Sort");
search = new JButton("Search");
clear = new JButton("Clear");
exit = new JButton("Exit");
/*
* assign action listeners
*/
add.addActionListener(this);
delete.addActionListener(this);
first.addActionListener(this);
previous.addActionListener(this);
next.addActionListener(this);
last.addActionListener(this);
sort.addActionListener(this);
search.addActionListener(this);
clear.addActionListener(this);
exit.addActionListener(this);
// GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill,
// Insets(int top, int left, int bottom, int right), int ipadx, int ipady)
/*
* dataPanel
*/
dataPanel = new JPanel();
dataPanel.setLayout(new GridBagLayout());
dataPanel.setBorder(new TitledBorder(null, "Contact Details", 0, 0, borderFont, Color.BLUE));
GridBagConstraints gbc = null;
//lastName
dataPanel.add(lName, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(lastName, new GridBagConstraints(1, 0, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//middleName
dataPanel.add(fName, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(firstName, new GridBagConstraints(1, 1, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//firstName
dataPanel.add(mName, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(middleName, new GridBagConstraints(1, 2, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//streetAddress
dataPanel.add(street, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(streetName, new GridBagConstraints(1, 3, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//city
dataPanel.add(city, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(cityName, new GridBagConstraints(1, 4, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//state
dataPanel.add(state, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(stateName, new GridBagConstraints(1, 5, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
//zip
dataPanel.add(zip, new GridBagConstraints(2, 5, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(zipCode, new GridBagConstraints(3, 5, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//homePhone
dataPanel.add(hPhone, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 3), 0, 0));
dataPanel.add(homePhone, new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 3), 0, 0));
//cellPhone
dataPanel.add(cPhone, new GridBagConstraints(2, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 3), 0, 0));
dataPanel.add(cellPhone, new GridBagConstraints(3, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
/*
* buttonPanel
*/
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
buttonPanel.setBorder(new TitledBorder(null, "Action Buttons", 0, 0, borderFont, Color.BLUE));
//first button
buttonPanel.add(first, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0));
//previous button
buttonPanel.add(previous, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0));
//next button
buttonPanel.add(next, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0));
//last button
buttonPanel.add(last, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 0), 0, 0));
//add button
buttonPanel.add(add, new GridBagConstraints(0, 1, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0));
//delete button
buttonPanel.add(delete, new GridBagConstraints(2, 1, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 0), 0, 0));
//sort button
buttonPanel.add(sort, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 5), 0, 0));
//search button
buttonPanel.add(search, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 5), 0, 0));
//clear button
buttonPanel.add(clear, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 5), 0, 0));
//exit button
buttonPanel.add(exit, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
/*
* create frame for panels
*/
frame.getContentPane().add(dataPanel, BorderLayout.NORTH);
frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
public static String getCellPhone() {
return cellPhone.getText();
}
public static void setCellPhone(JTextField cellPhone) {
AddressBookGUI.cellPhone = cellPhone;
}
public static String getCityName() {
return cityName.getText();
}
public static void setCityName(JTextField cityName) {
AddressBookGUI.cityName = cityName;
}
public static String getFirstName() {
return firstName.getText();
}
public static void setFirstName(JTextField firstName) {
AddressBookGUI.firstName = firstName;
}
public static String getHomePhone() {
return homePhone.getText();
}
public static void setHomePhone(JTextField homePhone) {
AddressBookGUI.homePhone = homePhone;
}
public static String getLastName() {
return lastName.getText();
}
public static void setLastName(JTextField lastName) {
AddressBookGUI.lastName = lastName;
}
public static String getMiddleName() {
return middleName.getText();
}
public static void setMiddleName(JTextField middleName) {
AddressBookGUI.middleName = middleName;
}
public static String getStateName() {
return stateName.getText();
}
public static void setStateName(JTextField stateName) {
AddressBookGUI.stateName = stateName;
}
public static String getStreetName() {
return streetName.getText();
}
public static void setStreetName(JTextField streetName) {
AddressBookGUI.streetName = streetName;
}
public static String getZipCode() {
return zipCode.getText();
}
public static void setZipCode(JTextField zipCode) {
AddressBookGUI.zipCode = zipCode;
}
public void clearAll() {
lastName.setText("");
middleName.setText("");
firstName.setText("");
streetName.setText("");
cityName.setText("");
stateName.setText("");
zipCode.setText("");
homePhone.setText("");
cellPhone.setText("");
}
public void actionPerformed(ActionEvent e) {
Contact c;
//Person p = new Person();
BookActions ba = new BookActions();
if (e.getActionCommand().equalsIgnoreCase("Load Sample Data")) {
} else if (e.getActionCommand().equalsIgnoreCase("Add Contact")) {
ba.addContact();
} else if (e.getActionCommand().equalsIgnoreCase("First Record")) {
// String data = ba.getFirstContact();
// lastName.setText(data);
// middleName.setText(data);
// firstName.setText(data);
// streetName.setText(data);
// cityName.setText(data);
// stateName.setText(data);
// zipCode.setText(data);
// homePhone.setText(data);
// cellPhone.setText(data);
} else if (e.getActionCommand().equalsIgnoreCase("Previous Record")) {
ba.getPreviousContact();
} else if (e.getActionCommand().equalsIgnoreCase("Next Record")) {
ba.getNextContact();
} else if (e.getActionCommand().equalsIgnoreCase("Last Record")) {
// String data = ba.getLastContact();
// lastName.setText(data);
// middleName.setText((String) data);
// firstName.setText((String) data);
// streetName.setText((String) data);
// cityName.setText((String) data);
// stateName.setText((String) data);
// zipCode.setText((String) data);
// homePhone.setText((String) data);
// cellPhone.setText((String) data);
} else if (e.getActionCommand().equalsIgnoreCase("Delete a Contact")) {
ba.deleteContact();
} else if (e.getActionCommand().equalsIgnoreCase("Clear")) {
clearAll();
} else if (e.getActionCommand().equalsIgnoreCase("Sort")) {
ba.sortContacts();
} else if (e.getActionCommand().equalsIgnoreCase("Search")) {
ba.searchContacts();
} else if (e.getActionCommand().equalsIgnoreCase("Exit")) {
System.exit(0);
} else if (e.getActionCommand().equalsIgnoreCase("Help...")) {
} else if (e.getActionCommand().equalsIgnoreCase("About")) {
JOptionPane.showMessageDialog(frame, "About this application:"
+ "\nVersion 1.0, Created 3/15/2011"
+ "\nBy: "
+ "\nO/S:"
+ "\n Windows 7 Ultimate x64"
+ "\nJAVA:"
+ "\n jdk 1.6.0_24"
+ "\nIDE:"
+ "\n NetBeans v. 6.9.1", "About \"AddressBook\"",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
BookActionspackage P4.v2;
public class BookActions {
AddressBookGUI abg;
Friend f;
Address a;
Contact c = new Contact();
BookActions() {
}
// public void addNewContact() {
// c = new Contact();
//
// //System.out.println(c.contactsSize());
// String lName = abg.lastName.getText();
// String fName = abg.firstName.getText();
// String mName = abg.middleName.getText();
// String hPhone = abg.homePhone.getText();
// String cPhone = abg.cellPhone.getText();
// String streetName = abg.streetName.getText();
// String cityName = abg.cityName.getText();
// String stateName = abg.stateName.getText();
// String zipCode = abg.zipCode.getText();
//
// f = new Friend(lName, fName, mName, hPhone, cPhone);
// a = new Address(streetName, cityName, stateName, zipCode);
// c.addToContactList(f);
// }
public void addContact() {
try {
String lName = abg.getLastName();
String mName = abg.getMiddleName();
String fName = abg.getFirstName();
String streetName = abg.getStreetName();
String cityName = abg.getCityName();
String stateName = abg.getStateName();
String zipCode = abg.getZipCode();
String hPhone = abg.getHomePhone();
String cPhone = abg.getCellPhone();
//CONSTRUCT OBJECTS
a = new Address(streetName, cityName, stateName, zipCode);
f = new Friend(lName, fName, mName, hPhone, cPhone,
a);
c.addPerson(f);
} catch (NullPointerException npe) {
npe.printStackTrace();
} catch (Exception e) {
System.out.println("Error in BookActions.addContact().");
}
}
public void clearAll() {
abg.lastName.setText("");
abg.middleName.setText("");
abg.firstName.setText("");
abg.streetName.setText("");
abg.cityName.setText("");
abg.stateName.setText("");
abg.zipCode.setText("");
abg.homePhone.setText("");
abg.cellPhone.setText("");
}
public void getPreviousContact() {
}
public void getNextContact() {
}
// public String getLastContact() {
// try {
// int listSize = Contact.getContactListSize();
// //System.out.println(listSize);
// int persons = listSize / 9;
// //System.out.println(persons);
// int itemsPerPerson = listSize / persons;
// //System.out.println(itemsPerPerson);
// //System.out.println(Contact_1.getPerson((listSize / listSize) - 1, itemsPerPerson));
// //System.out.println();
// ListIterator firstInList = Contact.getPerson((listSize - 9), listSize).listIterator();
// //String data = null;
// while (firstInList.hasNext()) {
// String data = new String();
// data = firstInList.next().toString();
// System.out.println("\nDataItem from ListIterator:" + data.toString());
// dataItem = data.toString();
// }
// } catch (Exception ioe) {
// ioe.printStackTrace();
// }
// return dataItem;
// }
public void deleteContact() {
}
public void sortContacts() {
}
public void searchContacts() {
}
}
and the console output:
run:
size: 1 at Index: 0 Smith John P (126)598-4580 (321)650-9874
size: 2 at Index: 1 Public John Q (445)896-5023 (326)551-4987
size: 3 at Index: 2 Nobody Jane X (654)613-2987 (985)864-7123
size: 4 at Index: 3 Smythe Gordon P (125)487-4580 (321)616-5974
size: 5 at Index: 4 Xavier Chuck P (659)228-4580 (375)450-9874
size: 6 at Index: 5 Furball Harry P (800)867-5309 (903)576-8008
size: 7 at Index: 6 brody willy f (186)345-2931 (325)457-4523
size: 8 at Index: 7 wright danielle g (284)342-2167 (967)856-7167
size: 9 at Index: 8 sane Not n (853)567-9217 (165)456-7423
size: 10 at Index: 9 toothless Ai m (174)345-9021 (475)342-7321
size: 11 at Index: 10 jobless lane n (724)342-1342 (327)342-2623
size: 1 at Index: 0 test test test test test
size: 1 at Index: 0 Starr Hambone D. (123)456-7856 (123)434-9846
BUILD SUCCESSFUL (total time: 4 minutes 28 seconds)
input info:
Smith,P,John,abc 123rd ave,nowhere,NJ,12548,(126)598-4580,(321)650-9874
Public,Q,John,5th Ave w,smalltown,NC,97548,(445)896-5023,(326)551-4987
Nobody,X,Jane,123 abc st,Somewhere,OK,56986,(654)613-2987,(985)864-7123
Smythe,P,Gordon,def 133rd ave,hoboken,NJ,23562,(125)487-4580,(321)616-5974
Xavier,P,Chuck,3 Private dr.,Westchester,NY,12548,(659)228-4580,(375)450-9874
Furball,P,Harry,2 Desert Rd,someplace sunny,NV,84521,(800)867-5309,(903)576-8008
brody,f,willy,123 xyz ave,Someplace,NE,52387,(186)345-2931,(325)457-4523
wright,g,danielle,123 abc st,lost,WY,65986,(284)342-2167,(967)856-7167
sane,n,Not,123 abc st,faraway,KS,56039,(853)567-9217,(165)456-7423
toothless,m,Ai,123 abc st,in the woods,OR,91827,(174)345-9021,(475)342-7321
jobless,n,lane,123 abc st,orange grove,FL,84573,(724)342-1342,(327)342-2623
ASKER
crap...I was wrong. the address object is not being added. I was just printing it out with the contactList...(in Contact.addPerson() )
I apologize for not having time to review the code in detail, but the Contact.addPerson() method did catch my eye. I think the reason you are seeing a new ArrayList every time you add a Person/Address from the GUI is because you are creating a new list if the added Person is already in the current list. If you try to do an update and call that method, it will create a new list. You may want to revisit that or see if that is actually the problem.
ASKER
it isn't I think. I made the arrayList public and changed the addPerson() method to just contactList.add(person). The input file works all right I think, but the GUI input throws a NullPointerException at BookActions line 28 (addPerson(person)).
Console Output (after attempting to add from GUI)
Console Output (after attempting to add from GUI)
run:
contactList.size(): 1 at contactList.indexOf(): 0 Smith John P (126)598-4580 (321)650-9874 abc 123rd ave nowhere NJ 12548
contactList.size(): 2 at contactList.indexOf(): 1 Public John Q (445)896-5023 (326)551-4987 5th Ave w smalltown NC 97548
contactList.size(): 3 at contactList.indexOf(): 2 Nobody Jane X (654)613-2987 (985)864-7123 123 abc st Somewhere OK 56986
contactList.size(): 4 at contactList.indexOf(): 3 Smythe Gordon P (125)487-4580 (321)616-5974 def 133rd ave hoboken NJ 23562
contactList.size(): 5 at contactList.indexOf(): 4 Xavier Chuck P (659)228-4580 (375)450-9874 3 Private dr. Westchester NY 12548
contactList.size(): 6 at contactList.indexOf(): 5 Furball Harry P (800)867-5309 (903)576-8008 2 Desert Rd someplace sunny NV 84521
contactList.size(): 7 at contactList.indexOf(): 6 brody willy f (186)345-2931 (325)457-4523 123 xyz ave Someplace NE 52387
contactList.size(): 8 at contactList.indexOf(): 7 wright danielle g (284)342-2167 (967)856-7167 123 abc st lost WY 65986
contactList.size(): 9 at contactList.indexOf(): 8 sane Not n (853)567-9217 (165)456-7423 123 abc st faraway KS 56039
contactList.size(): 10 at contactList.indexOf(): 9 toothless Ai m (174)345-9021 (475)342-7321 123 abc st in the woods OR 91827
contactList.size(): 11 at contactList.indexOf(): 10 jobless lane n (724)342-1342 (327)342-2623 123 abc st orange grove FL 84573
java.lang.NullPointerException
at P4.v2.BookActions.addContact(BookActions.java:28)
at P4.v2.AddressBookGUI.actionPerformed(AddressBookGUI.java:335)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6267)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6032)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
BUILD SUCCESSFUL (total time: 24 seconds)
Apologies too - got locked out of the site last night. You will probably need to change the ArrayList<Person> in the Contact class to an ArrayList<Friend>. Since Person doesn't have addresses, this coudl lead to a problem. While this is not the cause of the error you just got, it may lead to problems in the future.
Also, you really don't need to create a new ArrayList at anytime in the addContact method. ArrayLists are dynamic, so if you have 10 spaces, and you try to add an 11 person, the ArrayList automatically resizes. Save yourself the effort.
Also, you really don't need to create a new ArrayList at anytime in the addContact method. ArrayLists are dynamic, so if you have 10 spaces, and you try to add an 11 person, the ArrayList automatically resizes. Save yourself the effort.
ASKER
OK, so I think I've removed all the "new ArrayList();" lines - I came to the same realization that of course the list goes back to zero because I'm creating a new list with the same name. So yes, create it once and use it.
The problem is, I still can't add to it. Any action coming from an BookActions as a result of an action performed throws a NullPointerException. That is, any reference to the ArrayList gives an error.
I do not know why nor have I been able to figure it out.
In short, the problems I started this post with, I still have.
I have included the code
AddressBook (main)
The input file as posted in a previous post
I'm out of ideas (I'm at the limit of what I understand at the moment).
The problem is, I still can't add to it. Any action coming from an BookActions as a result of an action performed throws a NullPointerException. That is, any reference to the ArrayList gives an error.
I do not know why nor have I been able to figure it out.
In short, the problems I started this post with, I still have.
I have included the code
AddressBook (main)
package P4.v2;
public class AddressBook {
public static void main(String[] args) {
//ContactBook c = new ContactBook();
AddressBookGUI abg = new AddressBookGUI();
}
}
ContactBook
package P4.v2;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ContactBook {
public ArrayList<Friend> contactList = new ArrayList<Friend>();
protected int numContacts;
public AddressBookGUI abg;
public Person person = new Person();
public Friend friend = new Friend();
public Address address = new Address();
public ContactBook() {
numContacts = 0;
readFromFile("input.txt");
}
public int getNumContacts() {
return numContacts;
}
public void setNumContacts(int numContacts) {
this.numContacts = numContacts;
}
public ArrayList<Friend> getContactList() {
return contactList;
}
public Object getPerson(int index) {
return contactList.get(index);
}
public int getContactListSize() {
return contactList.size();
}
public void addAnotherPerson(Person person) {
numContacts += getNumContacts();
}
public void addToList(Friend friend) {
this.contactList.add(friend);
System.out.println("contactList.size(): " + contactList.size() + " at contactList.indexOf(): "
+ contactList.size() + " " + contactList.get(contactList.size() - 1));
}
//break the input file down into lines of text using line.separator as a delimiter
public void readFromFile(String inFile) {
try {
Scanner scanner = new Scanner(new File(inFile));
scanner.useDelimiter(System.getProperty("line.separator"));//(";");
while (scanner.hasNext()) {
addLine(scanner.next());
}
System.out.println();
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//break the lines of text down into individual strings using a comma as a delimiter
public void addLine(String line) {
Scanner scan = new Scanner(line);
scan.useDelimiter(",");
while (scan.hasNext()) {
int index = 0;
String lName = scan.next();
String mName = scan.next();
String fName = scan.next();
String streetName = scan.next();
String cityName = scan.next();
String stateName = scan.next();
String zipCode = scan.next();
String hPhone = scan.next();
String cPhone = scan.next();
//CONSTRUCT OBJECTS
address = new Address(streetName, cityName, stateName, zipCode);
person = new Person(lName, fName, mName);
friend = new Friend(lName, fName, mName, hPhone, cPhone, streetName, cityName, stateName, zipCode);
try {
addToList(friend);
} catch (Exception e) {
System.out.println(e);
}
index++;
}//end while loop
scan.close();
}//end addContact method
}//end ContactBook class
BookActions
package P4.v2;
import java.util.ListIterator;
import java.util.Scanner;
public class BookActions{
public ContactBook c;
public AddressBookGUI abg;
public Person person = new Person();
public Friend friend = new Friend();
public Address address = new Address();
BookActions() {
}
public void addContact() {
try {
String lName = abg.getLastName();
String mName = abg.getMiddleName();
String fName = abg.getFirstName();
String streetName = abg.getStreetName();
String cityName = abg.getCityName();
String stateName = abg.getStateName();
String zipCode = abg.getZipCode();
String hPhone = abg.getHomePhone();
String cPhone = abg.getCellPhone();
//CONSTRUCT OBJECTS
address = new Address(streetName, cityName, stateName, zipCode);
friend = new Friend(lName, fName, mName, hPhone, cPhone, streetName, cityName, stateName, zipCode);
try{
c.addToList(friend);
}catch(Exception e){
System.out.println(e);
}
} catch (NullPointerException npe) {
npe.printStackTrace();
} catch (Exception e) {
System.out.println("Error in BookActions.addContact().");
}
}
public void getFirstContact() {
ListIterator cli = c.getContactList().listIterator(0);
Scanner scan = new Scanner(cli.toString());
scan.useDelimiter("-");
while (scan.hasNext()) {
abg.setLastName(scan.next());
abg.setFirstName(scan.next());
abg.setMiddleName(scan.next());
abg.setHomePhone(scan.next());
abg.setCellPhone(scan.next());
abg.setStreetName(scan.next());
abg.setCityName(scan.next());
abg.setStateName(scan.next());
abg.setZipCode(scan.next());
}
scan.close();
}
public void getPreviousContact() {
}
public void getNextContact() {
}
public void getLastContact() {
}
public void clearAll() {
// abg.lastName.setText("");
// abg.middleName.setText("");
// abg.firstName.setText("");
// abg.streetName.setText("");
// abg.cityName.setText("");
// abg.stateName.setText("");
// abg.zipCode.setText("");
// abg.homePhone.setText("");
// abg.cellPhone.setText("");
abg.setLastName("testlastName");
abg.setMiddleName("testMiddleName");
abg.setFirstName("testFirstname");
abg.setStreetName("testStreetname");
abg.setCityName("testStreetName");
abg.setStateName("testStateName");
abg.setZipCode("testZipCode");
abg.setHomePhone("(###)###-####");
abg.setCellPhone("(###)###-####");
}
public void deleteContact() {
}
public void sortContacts() {
}
public void searchContacts() {
}
}
Person
package P4.v2;
public class Person{
public String lName,fName,mName;
public Person(){
}
public Person(Person person){
}
public Person(String lName, String fName, String mName) {
setLName(lName);
setFName(fName);
setMName(mName);
}
public String getFName() {
return fName;
}
public String getLName() {
return lName;
}
public String getMName() {
return mName;
}
public void setFName(String fName) {
this.fName = fName;
}
public void setLName(String lName) {
this.lName = lName;
}
public void setMName(String mName) {
this.mName = mName;
}
public String getPersonToString() {
return lName + "-" + fName + "-" + mName;
}
@Override
public String toString() {
return lName + "-" + fName + "-" + mName;
}
}
Friend
package P4.v2;
public class Friend extends Person {
public String hPhone, cPhone;
public Address a = new Address();
public Friend() {
super();
}
public Friend(String lName, String fName, String mName) {
super(lName, fName, mName);
}
public Friend(String lName, String fName, String mName, String hPhone, String cPhone,
String streetName, String cityName, String stateName, String zipCode) {
super(lName, fName, mName);
sethPhone(hPhone);
setcPhone(cPhone);
a.setStreetName(streetName);
a.setCityName(cityName);
a.setStateName(stateName);
a.setZipCode(zipCode);
}
public Friend(String hPhone, String cPhone) {
sethPhone(hPhone);
setcPhone(cPhone);
}
public Object getAddress() {
return a.getAddressToString();
}
public String getcPhone() {
return cPhone;
}
public void setcPhone(String cPhone) {
this.cPhone = cPhone;
}
public String gethPhone() {
return hPhone;
}
public void sethPhone(String hPhone) {
this.hPhone = hPhone;
}
public Friend getFriend() {
return this;
}
@Override
public String toString() {
return getPersonToString()+ "-" + hPhone + "-" + cPhone + "-" + a.toString();
}
}
Address
package P4.v2;
import java.util.ArrayList;
public class Address {
public String streetName, cityName, stateName, zipCode;
public Address() {
}
public Address(Address address) {
}
public Address(String streetName, String cityName, String stateName, String zipCode) {
setStreetName(streetName);
setCityName(cityName);
setStateName(stateName);
setZipCode(zipCode);
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getAddressToString() {
return streetName + cityName + stateName + zipCode;
}
@Override
public String toString() {
return streetName + "-" + cityName + "-" + stateName + "-" + zipCode;
}
}
AddressBookGUI
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package P4.v2;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
/**
*
* @author gcurrier
*/
public class AddressBookGUI implements ActionListener {
ContactBook c = new ContactBook();
JLabel lName, mName, fName, street, city, state, zip, hPhone, cPhone;
public JTextField lastName, middleName, firstName, streetName, cityName, stateName, zipCode, homePhone, cellPhone;
JButton add, delete, first, previous, next, last, sort, search, clear, exit;
JPanel dataPanel, buttonPanel, containerPanel;
JMenuBar menuBar = new JMenuBar(); //= new JMenuBar();
JMenu menu; //= new JMenu();
JMenuItem menuItem; //= new JMenuItem();
JFrame frame;
//establish Titled Border font size
Font borderFont = new Font("Sans Serif", Font.TRUETYPE_FONT, 10);
//String data;
AddressBookGUI() {
// lastName.setText(null);
// middleName.setText(null);
// firstName.setText(null);
// streetName.setText(null);
// cityName.setText(null);
// stateName.setText(null);
// zipCode.setText(null);
// homePhone.setText(null);
// cellPhone.setText(null);
frame = new JFrame("Address Book");
//frame.setSize(600, 360);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
addWindowItems();
frame.setResizable(true);
frame.pack();
frame.setVisible(true);
}
/**
*
*/
public void addWindowItems() {
//add a menu to the menu bar
//menuBar.add(menu);
menu = new JMenu("Options");
//"Options" menu items
menuItem = new JMenuItem("Load Sample Data");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Add Contact");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Delete Contact");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Sort");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Search");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Exit");
menu.add(menuItem);
menuItem.addActionListener(this);
//add another menu to the menu bar
menuBar.add(menu);
menu = new JMenu("Help");
//"Help" menu items
menuItem = new JMenuItem("Help...");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("About");
menu.add(menuItem);
menuItem.addActionListener(this);
menuBar.add(menu);
frame.setJMenuBar(menuBar);
/*
* labels and text fields
*/
lName = new JLabel("Last Name:");
lastName = new JTextField(30);
mName = new JLabel("Middle Name:");
middleName = new JTextField(30);
fName = new JLabel("First Name:");
firstName = new JTextField(30);
street = new JLabel("Street Address:");
streetName = new JTextField(30);
city = new JLabel("City:");
cityName = new JTextField(30);
state = new JLabel("State:");
stateName = new JTextField(2);
zip = new JLabel("Zip:");
zipCode = new JTextField(5);
hPhone = new JLabel("Home Phone:");
homePhone = new JTextField(15);
cPhone = new JLabel("Cell Phone:");
cellPhone = new JTextField(15);
/*
* buttons
*/
add = new JButton("Add Contact");
delete = new JButton("Delete Contact");
first = new JButton("First Record");
previous = new JButton("Next Record");
next = new JButton("Previous Record");
last = new JButton("Last Record");
sort = new JButton("Sort");
search = new JButton("Search");
clear = new JButton("Clear");
exit = new JButton("Exit");
/*
* assign action listeners
*/
add.addActionListener(this);
delete.addActionListener(this);
first.addActionListener(this);
previous.addActionListener(this);
next.addActionListener(this);
last.addActionListener(this);
sort.addActionListener(this);
search.addActionListener(this);
clear.addActionListener(this);
exit.addActionListener(this);
// GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill,
// Insets(int top, int left, int bottom, int right), int ipadx, int ipady)
/*
* dataPanel
*/
dataPanel = new JPanel();
dataPanel.setLayout(new GridBagLayout());
dataPanel.setBorder(new TitledBorder(null, "Contact Details", 0, 0, borderFont, Color.BLUE));
GridBagConstraints gbc = null;
//lastName
dataPanel.add(lName, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(lastName, new GridBagConstraints(1, 0, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//middleName
dataPanel.add(fName, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(firstName, new GridBagConstraints(1, 1, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//firstName
dataPanel.add(mName, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(middleName, new GridBagConstraints(1, 2, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//streetAddress
dataPanel.add(street, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(streetName, new GridBagConstraints(1, 3, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//city
dataPanel.add(city, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(cityName, new GridBagConstraints(1, 4, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//state
dataPanel.add(state, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(stateName, new GridBagConstraints(1, 5, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
//zip
dataPanel.add(zip, new GridBagConstraints(2, 5, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(zipCode, new GridBagConstraints(3, 5, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//homePhone
dataPanel.add(hPhone, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 3), 0, 0));
dataPanel.add(homePhone, new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 3), 0, 0));
//cellPhone
dataPanel.add(cPhone, new GridBagConstraints(2, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 3), 0, 0));
dataPanel.add(cellPhone, new GridBagConstraints(3, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
/*
* buttonPanel
*/
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
buttonPanel.setBorder(new TitledBorder(null, "Action Buttons", 0, 0, borderFont, Color.BLUE));
//first button
buttonPanel.add(first, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0));
//previous button
buttonPanel.add(previous, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0));
//next button
buttonPanel.add(next, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0));
//last button
buttonPanel.add(last, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 0), 0, 0));
//add button
buttonPanel.add(add, new GridBagConstraints(0, 1, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0));
//delete button
buttonPanel.add(delete, new GridBagConstraints(2, 1, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 0), 0, 0));
//sort button
buttonPanel.add(sort, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 5), 0, 0));
//search button
buttonPanel.add(search, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 5), 0, 0));
//clear button
buttonPanel.add(clear, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 5), 0, 0));
//exit button
buttonPanel.add(exit, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
/*
* create frame for panels
*/
frame.getContentPane().add(dataPanel, BorderLayout.NORTH);
frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
public String getCellPhone() {
return cellPhone.getText();
}
public void setCellPhone(String cPhone) {
this.cellPhone.setText(cPhone);
}
public String getCityName() {
return cityName.getText();
}
public void setCityName(String cityName) {
this.cityName.setText(cityName);
}
public String getFirstName() {
return firstName.getText();
}
public void setFirstName(String fName) {
this.firstName.setText(fName);
}
public String getHomePhone() {
return homePhone.getText();
}
public void setHomePhone(String hPhone) {
this.homePhone.setText(hPhone);
}
public String getLastName() {
return lastName.getText();
}
public void setLastName(String lName) {
this.lastName.setText(lName);
}
public String getMiddleName() {
return middleName.getText();
}
public void setMiddleName(String mName) {
this.middleName.setText(mName);
}
public String getStateName() {
return stateName.getText();
}
public void setStateName(String stateName) {
this.stateName.setText(stateName);
}
public String getStreetName() {
return streetName.getText();
}
public void setStreetName(String street) {
this.streetName.setText(street);
}
public String getZipCode() {
return zipCode.getText();
}
public void setZipCode(String zipCode) {
this.zipCode.setText(zipCode);
}
public void actionPerformed(ActionEvent e) {
//Person p = new Person();
BookActions ba = new BookActions();
if (e.getActionCommand().equalsIgnoreCase("Load Sample Data")) {
} else if (e.getActionCommand().equalsIgnoreCase("Add Contact")) {
ba.addContact();
} else if (e.getActionCommand().equalsIgnoreCase("First Record")) {
ba.getFirstContact();
} else if (e.getActionCommand().equalsIgnoreCase("Previous Record")) {
ba.getPreviousContact();
} else if (e.getActionCommand().equalsIgnoreCase("Next Record")) {
ba.getNextContact();
} else if (e.getActionCommand().equalsIgnoreCase("Last Record")) {
} else if (e.getActionCommand().equalsIgnoreCase("Delete a Contact")) {
ba.deleteContact();
} else if (e.getActionCommand().equalsIgnoreCase("Clear")) {
ba.clearAll();
} else if (e.getActionCommand().equalsIgnoreCase("Sort")) {
ba.sortContacts();
} else if (e.getActionCommand().equalsIgnoreCase("Search")) {
ba.searchContacts();
} else if (e.getActionCommand().equalsIgnoreCase("Exit")) {
System.exit(0);
} else if (e.getActionCommand().equalsIgnoreCase("Help...")) {
} else if (e.getActionCommand().equalsIgnoreCase("About")) {
JOptionPane.showMessageDialog(frame, "About this application:"
+ "\nVersion 1.0, Created 3/15/2011"
+ "\nBy: "
+ "\nO/S:"
+ "\n Windows 7 Ultimate x64"
+ "\nJAVA:"
+ "\n jdk 1.6.0_24"
+ "\nIDE:"
+ "\n NetBeans v. 6.9.1", "About \"AddressBook\"",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
The input file as posted in a previous post
I'm out of ideas (I'm at the limit of what I understand at the moment).
Okay, the problem is not actually with your ArrayList.
When you create a new BookActions, the constructor is empty. However, you have a variable AddressBookGUI abg. This never gets set, so it is null. Then, when you try to get the lName and other parameters for creating a new Friend in the BookActions class, you reference abg. Since abg is null, the virtual machine can't access it, and throws an error.
So, to fix it, in your constructor for BookActions, take an AddressBookGUI paramter, and set abg to that. You will also need to initialize ContactBook c in this constructor.
When you create a new BookActions, the constructor is empty. However, you have a variable AddressBookGUI abg. This never gets set, so it is null. Then, when you try to get the lName and other parameters for creating a new Friend in the BookActions class, you reference abg. Since abg is null, the virtual machine can't access it, and throws an error.
So, to fix it, in your constructor for BookActions, take an AddressBookGUI paramter, and set abg to that. You will also need to initialize ContactBook c in this constructor.
ASKER
If I follow you correctly, then this is what you mean:
However, in order to use the ActionListener in the GUI, the constructor now has to pass (new AddressBookGUI) which in turn reinitializes COntract and the input file is loaded 2 more times. This means that I need to keep the Empty constructor :
So then a summary of changes:
created another constructor in BookActions
removed ContactBook constructor from AddressBookGUI
added coding to load sample data in menubar (bar to actionlistener to bookactions to contactbook.readFromFile)
The problem is the same (NullPointerException) which means I obviously did something wrong again...
public class BookActions{
public ContactBook c;
public AddressBookGUI abg;
public Person person = new Person();
public Friend friend = new Friend();
public Address address = new Address();
BookActions(AddressBookGUI addressBookGui) {
abg = addressBookGui;
ContactBook c = new ContactBook();
}
Is that correct?However, in order to use the ActionListener in the GUI, the constructor now has to pass (new AddressBookGUI) which in turn reinitializes COntract and the input file is loaded 2 more times. This means that I need to keep the Empty constructor :
BookActions(AddressBookGUI addressBookGui) {
abg = addressBookGui;
ContactBook c = new ContactBook();
}
BookActions() {
}
...in order to utilize the action listener (and BookAction's methods) without making any changes to "everything else". Am I correct?So then a summary of changes:
created another constructor in BookActions
removed ContactBook constructor from AddressBookGUI
added coding to load sample data in menubar (bar to actionlistener to bookactions to contactbook.readFromFile)
//(In AddressBookGUI)
BookActions ba = new BookActions();
if (e.getActionCommand().equalsIgnoreCase("Load Sample Data")) {
ba.loadInputFile();
}
//(in BookActions)
public void loadInputFile(){
c.readFromFile("input.txt");
}
//(In ContactBook)
public void readFromFile(String inFile) {
try {
Scanner scanner = new Scanner(new File(inFile));
scanner.useDelimiter(System.getProperty("line.separator"));//(";");
while (scanner.hasNext()) {
addLine(scanner.next());
}
System.out.println();
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//break the lines of text down into individual strings using a comma as a delimiter
public void addLine(String line) {
Scanner scan = new Scanner(line);
scan.useDelimiter(",");
while (scan.hasNext()) {
int index = 0;
String lName = scan.next();
String mName = scan.next();
String fName = scan.next();
String streetName = scan.next();
String cityName = scan.next();
String stateName = scan.next();
String zipCode = scan.next();
String hPhone = scan.next();
String cPhone = scan.next();
//CONSTRUCT OBJECTS
address = new Address(streetName, cityName, stateName, zipCode);
person = new Person(lName, fName, mName);
friend = new Friend(lName, fName, mName, hPhone, cPhone, streetName, cityName, stateName, zipCode);
try {
addToList(friend);
} catch (Exception e) {
System.out.println(e);
}
index++;
}//end while loop
scan.close();
}
The problem is the same (NullPointerException) which means I obviously did something wrong again...
The code modifications to BookActions are great.
In the AdressBookGUI class, you don't need to create a new AddressBookGUI when you create the BookActions object - instead just pass the calling instance. Also, you create a new instance of BookActions every time an action is performed - save yourself some time and pointer references, and put the instantiation of the BookActions object as a global variable, rather than a local variable in the actionPerformed method.
So, in the AddressBookGUI class, you would have this instead:
You also really don't want to store the ContactBook in more than one place - so either put it in the AddressBookGUI class or the BookActions class. You actually don't use the reference in the AddressBookGUI class, so go ahead and delete that (it keeps the code cleaner and easier to read, as well as not forcing the JVM to store an extra unused instance).
Does this make sense? The most important thing here is that you understand what is happening in your code :D
However, in order to use the ActionListener in the GUI, the constructor now has to pass (new AddressBookGUI) which in turn reinitializes COntract and the input file is loaded 2 more times. This means that I need to keep the Empty constructor :
In the AdressBookGUI class, you don't need to create a new AddressBookGUI when you create the BookActions object - instead just pass the calling instance. Also, you create a new instance of BookActions every time an action is performed - save yourself some time and pointer references, and put the instantiation of the BookActions object as a global variable, rather than a local variable in the actionPerformed method.
So, in the AddressBookGUI class, you would have this instead:
public class AddressBookGUI implements ActionListener {
// new instance variable
BookActions ba;
//AddressBookGUI constructor
public AddressBookGUI() {
frame = new JFrame("Address Book");
//frame.setSize(600, 360);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
addWindowItems();
frame.setResizable(true);
frame.pack();
frame.setVisible(true);
//THE BIG IMPORTANT NEW LINE
ba = new BookActions(this);
}
// other methods in this class
// new actionPerformed method is really the same as the old
public void actionPerformed(ActionEvent e) {
// notice we are not instantiating BookActions here.
if (e.getActioncommand().equalsIgnoreCase("Load Sample Data")) {
// rest of the if elses - nothing is changed about them because ba still exists, just as an
// instance variable instead of a variable local to this method.
}
}
}
You also really don't want to store the ContactBook in more than one place - so either put it in the AddressBookGUI class or the BookActions class. You actually don't use the reference in the AddressBookGUI class, so go ahead and delete that (it keeps the code cleaner and easier to read, as well as not forcing the JVM to store an extra unused instance).
Does this make sense? The most important thing here is that you understand what is happening in your code :D
Still working on the NullPointerException - don't worry, haven't forgotten that bit.
ASKER
I had already removed the Contacts constructor. It exists only where you suggested - in the BookActions class. And yes, I understand what's going on when I trace the flow (mentally, anyway). The confusing part is what is happening to the ArrayList that pickups up the NullPointerException...I'm still hunting for it as well. Once I have that, I'm pretty sure the rest of the methods will fall into place.
ASKER
I've been adding try-catch blocks as I go, looking for the problem...
Okay, thing I nabbed the problem. Take a look at the BookActions class:
You have an instance variable ContactBook c2;
but in the construction, you instantiate ContactBook c = new ContactBook();
this makes it a brand new lContactBook, that is local to the constructor, so it disappears as soon as the constructor has completed. You never actually instantiate the instance variable ContactBook.
Then, in the addContact method, you call c.addToList(friend), but recall that c was never instantiated.
So, get rid of the line ContactBook c = new ContactBook(); and change it to c = new ContactBook();
Then, make sure to rename the instance variable to ContactBook c; (I'm assuming that you didn't rename the instances of ContactBook refrerenced throughout the class, and in the addContact method to c2, but if you did, make sure you instantiate c2 in the constructor instead of c).
public class BookActions{
public ContactBook c;
public AddressBookGUI abg;
public Person person = new Person();
public Friend friend = new Friend();
public Address address = new Address();
BookActions(AddressBookGUI addressBookGui) {
abg = addressBookGui;
ContactBook c = new ContactBook();
}
You have an instance variable ContactBook c2;
but in the construction, you instantiate ContactBook c = new ContactBook();
this makes it a brand new lContactBook, that is local to the constructor, so it disappears as soon as the constructor has completed. You never actually instantiate the instance variable ContactBook.
Then, in the addContact method, you call c.addToList(friend), but recall that c was never instantiated.
So, get rid of the line ContactBook c = new ContactBook(); and change it to c = new ContactBook();
Then, make sure to rename the instance variable to ContactBook c; (I'm assuming that you didn't rename the instances of ContactBook refrerenced throughout the class, and in the addContact method to c2, but if you did, make sure you instantiate c2 in the constructor instead of c).
ASKER
there is no c2 throughout the classes. and I have removed the instantiation from the bookactions constructor. Same null pointer with BookActions.clearAll() and loadSampleData(). I'm still trying to pinpoint it as well
Can you post the latest versions of BookActions and AddressBookGUI. Think our versions are out of synch, since i don't get an error.
ASKER
ok
AddressBookGUI
AddressBookGUI
package P4.v2;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
public class AddressBookGUI implements ActionListener {
BookActions ba;
JLabel lName, mName, fName, street, city, state, zip, hPhone, cPhone;
public JTextField lastName, middleName, firstName, streetName, cityName, stateName, zipCode, homePhone, cellPhone;
JButton add, delete, first, previous, next, last, sort, search, clear, exit;
JPanel dataPanel, buttonPanel, containerPanel;
JMenuBar menuBar = new JMenuBar(); //= new JMenuBar();
JMenu menu; //= new JMenu();
JMenuItem menuItem; //= new JMenuItem();
JFrame frame;
//establish Titled Border font size
Font borderFont = new Font("Sans Serif", Font.TRUETYPE_FONT, 10);
//String data;
public AddressBookGUI() {
frame = new JFrame("Address Book");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
addWindowItems();
frame.setResizable(true);
frame.pack();
frame.setVisible(true);
}
public void addWindowItems() {
//add a menu to the menu bar
//menuBar.add(menu);
menu = new JMenu("Options");
//"Options" menu items
menuItem = new JMenuItem("Load Sample Data");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Add Contact");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Delete Contact");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Sort");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Search");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("Exit");
menu.add(menuItem);
menuItem.addActionListener(this);
//add another menu to the menu bar
menuBar.add(menu);
menu = new JMenu("Help");
//"Help" menu items
menuItem = new JMenuItem("Help...");
menu.add(menuItem);
menuItem.addActionListener(this);
menuItem = new JMenuItem("About");
menu.add(menuItem);
menuItem.addActionListener(this);
menuBar.add(menu);
frame.setJMenuBar(menuBar);
/*
* labels and text fields
*/
lName = new JLabel("Last Name:");
lastName = new JTextField(30);
mName = new JLabel("Middle Name:");
middleName = new JTextField(30);
fName = new JLabel("First Name:");
firstName = new JTextField(30);
street = new JLabel("Street Address:");
streetName = new JTextField(30);
city = new JLabel("City:");
cityName = new JTextField(30);
state = new JLabel("State:");
stateName = new JTextField(2);
zip = new JLabel("Zip:");
zipCode = new JTextField(5);
hPhone = new JLabel("Home Phone:");
homePhone = new JTextField(15);
cPhone = new JLabel("Cell Phone:");
cellPhone = new JTextField(15);
/*
* buttons
*/
add = new JButton("Add Contact");
delete = new JButton("Delete Contact");
first = new JButton("First Record");
previous = new JButton("Next Record");
next = new JButton("Previous Record");
last = new JButton("Last Record");
sort = new JButton("Sort");
search = new JButton("Search");
clear = new JButton("Clear");
exit = new JButton("Exit");
/*
* assign action listeners
*/
add.addActionListener(this);
delete.addActionListener(this);
first.addActionListener(this);
previous.addActionListener(this);
next.addActionListener(this);
last.addActionListener(this);
sort.addActionListener(this);
search.addActionListener(this);
clear.addActionListener(this);
exit.addActionListener(this);
// GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill,
// Insets(int top, int left, int bottom, int right), int ipadx, int ipady)
/*
* dataPanel
*/
dataPanel = new JPanel();
dataPanel.setLayout(new GridBagLayout());
dataPanel.setBorder(new TitledBorder(null, "Contact Details", 0, 0, borderFont, Color.BLUE));
GridBagConstraints gbc = null;
//lastName
dataPanel.add(lName, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(lastName, new GridBagConstraints(1, 0, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//middleName
dataPanel.add(fName, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(firstName, new GridBagConstraints(1, 1, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//firstName
dataPanel.add(mName, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(middleName, new GridBagConstraints(1, 2, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//streetAddress
dataPanel.add(street, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(streetName, new GridBagConstraints(1, 3, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//city
dataPanel.add(city, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(cityName, new GridBagConstraints(1, 4, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//state
dataPanel.add(state, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(stateName, new GridBagConstraints(1, 5, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
//zip
dataPanel.add(zip, new GridBagConstraints(2, 5, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 3), 0, 0));
dataPanel.add(zipCode, new GridBagConstraints(3, 5, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 3, 0), 0, 0));
//homePhone
dataPanel.add(hPhone, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 3), 0, 0));
dataPanel.add(homePhone, new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 3), 0, 0));
//cellPhone
dataPanel.add(cPhone, new GridBagConstraints(2, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 3), 0, 0));
dataPanel.add(cellPhone, new GridBagConstraints(3, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
/*
* buttonPanel
*/
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
buttonPanel.setBorder(new TitledBorder(null, "Action Buttons", 0, 0, borderFont, Color.BLUE));
//first button
buttonPanel.add(first, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0));
//previous button
buttonPanel.add(previous, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0));
//next button
buttonPanel.add(next, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0));
//last button
buttonPanel.add(last, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 0), 0, 0));
//add button
buttonPanel.add(add, new GridBagConstraints(0, 1, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 5), 0, 0));
//delete button
buttonPanel.add(delete, new GridBagConstraints(2, 1, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 0), 0, 0));
//sort button
buttonPanel.add(sort, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 5), 0, 0));
//search button
buttonPanel.add(search, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 5), 0, 0));
//clear button
buttonPanel.add(clear, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 5), 0, 0));
//exit button
buttonPanel.add(exit, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
/*
* create frame for panels
*/
frame.getContentPane().add(dataPanel, BorderLayout.NORTH);
frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
public String getCellPhone() {
return cellPhone.getText();
}
public void setCellPhone(String cPhone) {
this.cellPhone.setText(cPhone);
}
public String getCityName() {
return cityName.getText();
}
public void setCityName(String cityName) {
this.cityName.setText(cityName);
}
public String getFirstName() {
return firstName.getText();
}
public void setFirstName(String fName) {
this.firstName.setText(fName);
}
public String getHomePhone() {
return homePhone.getText();
}
public void setHomePhone(String hPhone) {
this.homePhone.setText(hPhone);
}
public String getLastName() {
return lastName.getText();
}
public void setLastName(String lName) {
this.lastName.setText(lName);
}
public String getMiddleName() {
return middleName.getText();
}
public void setMiddleName(String mName) {
this.middleName.setText(mName);
}
public String getStateName() {
return stateName.getText();
}
public void setStateName(String stateName) {
this.stateName.setText(stateName);
}
public String getStreetName() {
return streetName.getText();
}
public void setStreetName(String street) {
this.streetName.setText(street);
}
public String getZipCode() {
return zipCode.getText();
}
public void setZipCode(String zipCode) {
this.zipCode.setText(zipCode);
}
public void actionPerformed(ActionEvent e) {
//Person p = new Person();
if (e.getActionCommand().equalsIgnoreCase("Load Sample Data")) {
try {
ba.loadInputFile();
} catch (Exception ex) {
System.out.println(ex +" in AddressBookGUI.actionPerformed() \"Load Sample Data\".");
ex.printStackTrace();
}
} else if (e.getActionCommand().equalsIgnoreCase("Add Contact")) {
ba.addContact();
} else if (e.getActionCommand().equalsIgnoreCase("First Record")) {
ba.getFirstContact();
} else if (e.getActionCommand().equalsIgnoreCase("Previous Record")) {
ba.getPreviousContact();
} else if (e.getActionCommand().equalsIgnoreCase("Next Record")) {
ba.getNextContact();
} else if (e.getActionCommand().equalsIgnoreCase("Last Record")) {
} else if (e.getActionCommand().equalsIgnoreCase("Delete a Contact")) {
ba.deleteContact();
} else if (e.getActionCommand().equalsIgnoreCase("Clear")) {
try{
ba.clearAll();
}catch(Exception ex){
System.out.println(ex+" in AddressBookGUI.actionPerformed() \"Clear\".");
}
} else if (e.getActionCommand().equalsIgnoreCase("Sort")) {
ba.sortContacts();
} else if (e.getActionCommand().equalsIgnoreCase("Search")) {
ba.searchContacts();
} else if (e.getActionCommand().equalsIgnoreCase("Exit")) {
System.exit(0);
} else if (e.getActionCommand().equalsIgnoreCase("Help...")) {
} else if (e.getActionCommand().equalsIgnoreCase("About")) {
JOptionPane.showMessageDialog(frame, "About this application:"
+ "\nVersion 1.0, Created 3/15/2011"
+ "\nBy: "
+ "\nO/S:"
+ "\n Windows 7 Ultimate x64"
+ "\nJAVA:"
+ "\n jdk 1.6.0_24"
+ "\nIDE:"
+ "\n NetBeans v. 6.9.1", "About \"AddressBook\"",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
BookActions
package P4.v2;
import java.io.File;
import java.io.IOException;
import java.util.ListIterator;
import java.util.Scanner;
public class BookActions {
public ContactBook c;
public AddressBookGUI abg;
public Person person = new Person();
public Friend friend = new Friend();
public Address address = new Address();
public BookActions(AddressBookGUI addressBookGui) {
abg = addressBookGui;
//ContactBook c = new ContactBook();
}
public BookActions() {
}
public void addContact() {
try {
String lName = abg.getLastName();
String mName = abg.getMiddleName();
String fName = abg.getFirstName();
String streetName = abg.getStreetName();
String cityName = abg.getCityName();
String stateName = abg.getStateName();
String zipCode = abg.getZipCode();
String hPhone = abg.getHomePhone();
String cPhone = abg.getCellPhone();
//CONSTRUCT OBJECTS
address = new Address(streetName, cityName, stateName, zipCode);
friend = new Friend(lName, fName, mName, hPhone, cPhone, streetName, cityName, stateName, zipCode);
try {
c.addToList(friend);
} catch (Exception e) {
System.out.println(e);
}
} catch (NullPointerException npe) {
System.out.println(npe + " while adding a contact in BookActions.addContact() method.");
npe.printStackTrace();
} catch (Exception e) {
System.out.println("Error in BookActions.addContact().");
e.printStackTrace();
}
}
public void getFirstContact() {
try{
ListIterator cli = c.getContactList().listIterator(0);
Scanner scan = new Scanner(cli.toString());
scan.useDelimiter("-");
while (scan.hasNext()) {
abg.setLastName(scan.next());
abg.setFirstName(scan.next());
abg.setMiddleName(scan.next());
abg.setHomePhone(scan.next());
abg.setCellPhone(scan.next());
abg.setStreetName(scan.next());
abg.setCityName(scan.next());
abg.setStateName(scan.next());
abg.setZipCode(scan.next());
}
scan.close();
}catch (Exception e){
System.out.println(e +" in BookActions.getFirstContact() method.");
e.printStackTrace();
}
}
public void getPreviousContact() {
}
public void getNextContact() {
}
public void getLastContact() {
}
public void clearAll() {
try {
// abg.lastName.setText("");
// abg.middleName.setText("");
// abg.firstName.setText("");
// abg.streetName.setText("");
// abg.cityName.setText("");
// abg.stateName.setText("");
// abg.zipCode.setText("");
// abg.homePhone.setText("");
// abg.cellPhone.setText("");
abg.setLastName("testlastName");
abg.setMiddleName("testMiddleName");
abg.setFirstName("testFirstname");
abg.setStreetName("testStreetname");
abg.setCityName("testStreetName");
abg.setStateName("testStateName");
abg.setZipCode("testZipCode");
abg.setHomePhone("(###)###-####");
abg.setCellPhone("(###)###-####");
} catch (Exception e) {
// System.out.println();
System.out.println(e + " while trying to clear all textfields in BookAction.clearAll() method.");
e.printStackTrace();
}
}
public void deleteContact() {
}
public void sortContacts() {
}
public void searchContacts() {
}
public void loadInputFile() throws Exception {
String inFile = "input.txt";
try {
File file = new File(inFile);
file.getAbsolutePath();
System.out.println(file.getAbsolutePath());
c.readFromFile(file.getAbsolutePath());
} catch (Exception e) {
System.out.println(e + " in BookActions.loadInputFile() method.");
e.printStackTrace();
}
}
}
Alright, its just 2 quick fixes.
1st, in BookActions
2nd, in AddressBookGUI, ba never got instantiated. make sure the folloiwng line appears somewhere in the constructor:
ba = new BookActions(this);
1st, in BookActions
public BookActions(AddressBookGUI addressBookGui) {
abg = addressBookGui;
c = new ContactBook();
}
2nd, in AddressBookGUI, ba never got instantiated. make sure the folloiwng line appears somewhere in the constructor:
ba = new BookActions(this);
ASKER
you're going to hate me...
I did that, of course (I see it now)...but...it's still throwing the error.
at least now in a different place:
I did that, of course (I see it now)...but...it's still throwing the error.
at least now in a different place:
c.readFromFile(file.getAbsolutePath());
in loadInputFile();
ASKER
changed that line to
c.readFromFile(inFile);
same result
This is all part of the coding (and learning to code) process. Definitely not hate...good experience for both of us.
Make sure that your input file is in the top level of the directory structure, and named input.txt.
It looks like you are using eclipse - no? In which case, you would have your source folder, then your input.txt file on the same level as that source folder.
Make sure that your input file is in the top level of the directory structure, and named input.txt.
It looks like you are using eclipse - no? In which case, you would have your source folder, then your input.txt file on the same level as that source folder.
ASKER
using netbeans the input file is there, same as Eclipse structure. (I got paranoid and checked to see if it was indeed there- it is)
hmmm...can you post the stackTrace from the error?
ASKER
java.lang.NullPointerExcep tion
java.lang.NullPointerExcep tion in BookActions.loadInputFile( ) method.
at P4.v2.BookActions.loadInpu tFile(Book Actions.ja va:127)
at P4.v2.AddressBookGUI.actio nPerformed (AddressBo okGUI.java :303)
at javax.swing.AbstractButton .fireActio nPerformed (AbstractB utton.java :1995)
at javax.swing.AbstractButton $Handler.a ctionPerfo rmed(Abstr actButton. java:2318)
at javax.swing.DefaultButtonM odel.fireA ctionPerfo rmed(Defau ltButtonMo del.java:3 87)
at javax.swing.DefaultButtonM odel.setPr essed(Defa ultButtonM odel.java: 242)
at javax.swing.AbstractButton .doClick(A bstractBut ton.java:3 57)
at javax.swing.plaf.basic.Bas icMenuItem UI.doClick (BasicMenu ItemUI.jav a:809)
at javax.swing.plaf.basic.Bas icMenuItem UI$Handler .mouseRele ased(Basic MenuItemUI .java:850)
at java.awt.Component.process MouseEvent (Component .java:6267 )
at javax.swing.JComponent.pro cessMouseE vent(JComp onent.java :3267)
at java.awt.Component.process Event(Comp onent.java :6032)
at java.awt.Container.process Event(Cont ainer.java :2041)
at java.awt.Component.dispatc hEventImpl (Component .java:4630 )
at java.awt.Container.dispatc hEventImpl (Container .java:2099 )
at java.awt.Component.dispatc hEvent(Com ponent.jav a:4460)
at java.awt.LightweightDispat cher.retar getMouseEv ent(Contai ner.java:4 577)
at java.awt.LightweightDispat cher.proce ssMouseEve nt(Contain er.java:42 38)
at java.awt.LightweightDispat cher.dispa tchEvent(C ontainer.j ava:4168)
at java.awt.Container.dispatc hEventImpl (Container .java:2085 )
at java.awt.Window.dispatchEv entImpl(Wi ndow.java: 2478)
at java.awt.Component.dispatc hEvent(Com ponent.jav a:4460)
at java.awt.EventQueue.dispat chEvent(Ev entQueue.j ava:599)
at java.awt.EventDispatchThre ad.pumpOne EventForFi lters(Even tDispatchT hread.java :269)
at java.awt.EventDispatchThre ad.pumpEve ntsForFilt er(EventDi spatchThre ad.java:18 4)
at java.awt.EventDispatchThre ad.pumpEve ntsForHier archy(Even tDispatchT hread.java :174)
at java.awt.EventDispatchThre ad.pumpEve nts(EventD ispatchThr ead.java:1 69)
at java.awt.EventDispatchThre ad.pumpEve nts(EventD ispatchThr ead.java:1 61)
at java.awt.EventDispatchThre ad.run(Eve ntDispatch Thread.jav a:122)
BUILD SUCCESSFUL (total time: 9 seconds)
java.lang.NullPointerExcep
at P4.v2.BookActions.loadInpu
at P4.v2.AddressBookGUI.actio
at javax.swing.AbstractButton
at javax.swing.AbstractButton
at javax.swing.DefaultButtonM
at javax.swing.DefaultButtonM
at javax.swing.AbstractButton
at javax.swing.plaf.basic.Bas
at javax.swing.plaf.basic.Bas
at java.awt.Component.process
at javax.swing.JComponent.pro
at java.awt.Component.process
at java.awt.Container.process
at java.awt.Component.dispatc
at java.awt.Container.dispatc
at java.awt.Component.dispatc
at java.awt.LightweightDispat
at java.awt.LightweightDispat
at java.awt.LightweightDispat
at java.awt.Container.dispatc
at java.awt.Window.dispatchEv
at java.awt.Component.dispatc
at java.awt.EventQueue.dispat
at java.awt.EventDispatchThre
at java.awt.EventDispatchThre
at java.awt.EventDispatchThre
at java.awt.EventDispatchThre
at java.awt.EventDispatchThre
at java.awt.EventDispatchThre
BUILD SUCCESSFUL (total time: 9 seconds)
ASKER
Well, I know the file is in the right place because of this result:
package P4.v2;
public class AddressBook {
public static void main(String[] args) {
ContactBook c = new ContactBook();
c.readFromFile();
// new AddressBookGUI();
}
}
and this console output:run:
contactList.size(): 1 at contactList.indexOf(): 1 Smith-John-P-(126)598-4580-(321)650-9874-abc 123rd ave-nowhere-NJ-12548
contactList.size(): 2 at contactList.indexOf(): 2 Public-John-Q-(445)896-5023-(326)551-4987-5th Ave w-smalltown-NC-97548
contactList.size(): 3 at contactList.indexOf(): 3 Nobody-Jane-X-(654)613-2987-(985)864-7123-123 abc st-Somewhere-OK-56986
contactList.size(): 4 at contactList.indexOf(): 4 Smythe-Gordon-P-(125)487-4580-(321)616-5974-def 133rd ave-hoboken-NJ-23562
contactList.size(): 5 at contactList.indexOf(): 5 Xavier-Chuck-P-(659)228-4580-(375)450-9874-3 Private dr.-Westchester-NY-12548
contactList.size(): 6 at contactList.indexOf(): 6 Furball-Harry-P-(800)867-5309-(903)576-8008-2 Desert Rd-someplace sunny-NV-84521
contactList.size(): 7 at contactList.indexOf(): 7 brody-willy-f-(186)345-2931-(325)457-4523-123 xyz ave-Someplace-NE-52387
contactList.size(): 8 at contactList.indexOf(): 8 wright-danielle-g-(284)342-2167-(967)856-7167-123 abc st-lost-WY-65986
contactList.size(): 9 at contactList.indexOf(): 9 sane-Not-n-(853)567-9217-(165)456-7423-123 abc st-faraway-KS-56039
contactList.size(): 10 at contactList.indexOf(): 10 toothless-Ai-m-(174)345-9021-(475)342-7321-123 abc st-in the woods-OR-91827
contactList.size(): 11 at contactList.indexOf(): 11 jobless-lane-n-(724)342-1342-(327)342-2623-123 abc st-orange grove-FL-84573
BUILD SUCCESSFUL (total time: 0 seconds)
I'm not seeing where the readFromFile() method (no parameters) is in ContactBook - old version? THere is only a version with the parameter (which we are trying to fix).
ASKER
sorry, I removed the parameter the read from file is now this (simple change)
it just seemed to make more sense this way using the actual method to do the most work
public void readFromFile() {
String inFile = "input.txt";
try {
Scanner scanner = new Scanner(new File(inFile));
scanner.useDelimiter(System.getProperty("line.separator"));//(";");
while (scanner.hasNext()) {
addLine(scanner.next());
}
System.out.println();
scanner.close();
} catch (Exception e) {
System.out.println(e + " in ContactBook.readFromFile() method.");
e.printStackTrace();
}
}
it just seemed to make more sense this way using the actual method to do the most work
ASKER
it seems that if the method is accessed directly it works but sending it through the middle men -the action listener and BookAction class, a disconnect is created. Would extending the Contact class to BookActions fix this?
That shouldn't make a difference. However, I can also not reproduce the error. Can you post the method in the BookActions class.
ASKER
public void loadInputFile(){
try {
c.readFromFile();
} catch (NullPointerException e) {
System.out.println(e + " in BookActions.loadInputFile() method.");
e.printStackTrace();
}
}
Still not throwing an error for me. Can you attach the whole class? You can just upload the file.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
got it. I'm stiull a bit shaky on using the "this" keyword and in this sense especially. I believe it calls the instance variable, right?
In any case this issue is solved and I will be moving on to putting arraylist objects into a string then splitting them apart with a delimiter (BookActions.getFirstConta ct()) - new post, related question.
In any case this issue is solved and I will be moving on to putting arraylist objects into a string then splitting them apart with a delimiter (BookActions.getFirstConta
the this keyword refers to the instance of the class calling it. So, in this context, "this" means the AddressBookGUI object you are creating in that constructor. Its a means of referencing self.
ASKER
In effect then, using the constructor in BookActions, passing "this" AddressBookGUI as a parameter.
Thanks
Thanks