Lectura y escritura de Java tipo ArrayList Contacto a GUI

EDITAR

I've made several corrections and am now able to compile. When attempting to add a contact to the file I receive a null pointer exception at line 13 of the ContactsCollection class:

for (int i = 0; i < contactList.size(); i++)

and line 93 of the Contacts (GUI) class:

contactList.add(contact);

Contacts class:

import java.util.*;
import java.io.*;

public class Contact implements Serializable
{
public static final long serialVersionUID = 42L;
public String name, number;

Contact()
{
    name = "No name";
    number = "No number";
}

Contact (String theName, String theNumber)
{
    this.name = theName;
    this.number = theNumber;
}

public void setName(String aName)
{
    this.name = aName;
}

public void setNumber(String aNumber)
{
    this.number =aNumber;
}

public String getName()
{
    return name;
}

public String getNumber()
{
    return number;
}

public String toString()
{
    return name + ": " + number;
}

public boolean equals(Contact other)
{
   if (name.equals(other.getName()) && number.equals(other.getNumber()))
   {
      return(true);
   }
   else
   {
      return(false);
   }
}   
}

Contacts Collection class

import java.io.*;
import java.util.*;

class ContactsCollection
{
public static ArrayList<Contact> contactList;

public static void write()
{
    try 
    {
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("contactList.dat"));
        for (int i = 0; i < contactList.size(); i++)
        {
            out.writeObject(contactList.get(i));
        }
        out.close();
    } 
    catch(IOException e)
    {
        e.printStackTrace();
    }
}

public static void read()
{
contactList = new ArrayList<Contact>();
try
{
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("contactList.dat"));
    Contact temp;
    while (in.available()!=0)
    {
        temp = (Contact)in.readObject();
        contactList.add(temp);
    }
    in.close();
}
catch(FileNotFoundException e)
{
    e.printStackTrace();
}
catch(IOException e)
{
    e.printStackTrace();
}
catch(ClassNotFoundException e)
{
    e.printStackTrace();
}       

}
}

Contacts (GUI) class

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.Timer;
import java.util.*;

class Contacts extends JFrame implements ActionListener, WindowListener
{
public static final int WIDTH = 400;
    public static final int HEIGHT = 600;
    public static final int SMALL_WIDTH = 200;
    public static final int SMALL_HEIGHT = 100;

private static final Dimension stdBtn = new Dimension(150, 50);    

    JPanel centerPanel, northPanel, southPanel;
ImageIcon icon;
JLabel picture;
JButton addContact, displayContacts;
JScrollPane scroll;
JTextArea textArea;
Clock clock;
Background background;
Contact contact;
ArrayList<Contact> contactList;


public Contacts()
{
    super("Contacts");
    this.setLayout(new BorderLayout());
    this.setSize(WIDTH, HEIGHT);
    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    addWindowListener(this);
    this.setLocationRelativeTo(null);

    centerPanel = new JPanel();
    northPanel = new JPanel();
    southPanel = new JPanel();

    centerPanel.setBackground(Color.BLACK);
    southPanel.setBackground(Color.BLACK);      

    clock = new Clock();
    northPanel.add(clock);

    icon = new ImageIcon("ContactsBackground.jpg");
    picture = new JLabel(icon);
    centerPanel.add(picture);

    textArea = new JTextArea("", 10, 30);
    textArea.setEditable(false);
    JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);    
    centerPanel.add(scroll);    

    JButton displayContacts = new JButton("Display contacts");
    displayContacts.addActionListener(this);
    southPanel.add(displayContacts);

    JButton addContact = new JButton("Add contact");
    addContact.addActionListener(this);
    southPanel.add(addContact);

    this.add(northPanel, BorderLayout.NORTH);
    this.add(centerPanel, BorderLayout.CENTER);
    this.add(southPanel, BorderLayout.SOUTH);       

    setResizable(false);        
}

public void actionPerformed(ActionEvent e)
{
    contactList = new ArrayList<Contact>();
    JButton source = (JButton)e.getSource();
    String contactInput = source.getText();

    if (contactInput == "Display contacts")
    {
        ContactsCollection.read();
        for (int i = 0; i < contactList.size(); i++)
        {
            contact = (Contact)contactList.get(i);
            textArea.setText(contact.getName() + "," + contact.getNumber() + "\n");
        }
    }
    if (contactInput == "Add contact")
    {
        String name = JOptionPane.showInputDialog(null, "Enter Name");
        String number = JOptionPane.showInputDialog(null, "Enter Number");
        contact = new Contact(name, number);
        contactList.add(contact);
        ContactsCollection.write();
    }
}

public void windowOpened(WindowEvent e)
{}

public void windowClosing(WindowEvent e)
{
    this.setVisible(false);
    background = new Background();
    background.setVisible(true);        
}

public void windowClosed(WindowEvent e)
{}

public void windowIconified(WindowEvent e)
{}

public void windowDeiconified(WindowEvent e)
{}

public void windowActivated(WindowEvent e)
{}

public void windowDeactivated(WindowEvent e)
{}      
}

preguntado el 15 de mayo de 13 a las 03:05

1 Respuestas

Con respecto a

The first error I'm running into is "cannot find symbol method read()" and "cannot find symbol method write()".

You're calling a method on ArrayList, read(), that just doesn't exist. You need to call this method on one of the contenido of the ArrayList, not the ArrayList itself. It's like trying to make an omelette with an egg crate -- won't work. You need to use an egg or two instead. Same thing for write().

Con respecto a

The second error is in the action listener for display contacts stating that "an array is required but a Contact was found".

You should tell us which line causes this error.


Editar
Mostrar:

for (int i = 0; i < contactList.size(); i++)
{
    textArea.setText(contact[i].getName() + "," + contact [i].getNumber() + "\n");
}

That code makes no sense. You need to use your list variable, contactList and get its item via the ArrayList get(...) método.


Your code suggests that you're blindly adding a bunch of code regardless of errors, and that won't work. If you can't use an IDE, you should compile often, after each 1-3 lines and fix all compilation errors before trying to add any more code. Else you'll end up with a rat's nest of errors. Also, read the manual/book. Don't guess at this stuff.

contestado el 15 de mayo de 13 a las 04:05

Thank you for the quick response. I've specified the second question at the top of my post as you asked. For the first question, I was under the impression that the read() method read in objects of type Contact from the file into an ArrayList. Now that I have an ArrayList of Contacts, would I need to loop through the array and read in each object? - user2380220

Thanks mate. I'll rewrite it so that contactList.get(i) returns the Contact objects. Then work on displaying the Contact objects instance variables into the GUI. - user2380220

I've made a few modifications and am now able to compile. I am getting null pointer exceptions with my arrayList. I think it has to do with the ContactsCollection class. Are you still available to help? I will update the code at the top. - user2380220

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.