Error Writing Object's Attributes to File from GUI java - java

I have a problem with my GUI code that I just can't get my head around it and it concerns file writing with GUI Frames.
You see with my code below, I can Add, Remove and Display person Objects with a JTable. The problem I have is writing each attribute of each object to a file named "PersonList.txt".
The annoying thing about this is that supposing I manually put values into the file, my code is able to read each line and create person objects with the values from the files. But if I wanted to add more person objects to the file, the data in the file is overriden and the file will be empty.
My Code follows.
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class GUIstoringObjects extends JFrame implements ActionListener{
private JFrame frame;
private JButton button1, button2, button3, button4, button5, button6;
private JTextField box1, box2, box3;
private JLabel label1, label2, label3;
private JTable table;
private ArrayList<Person> pList = new ArrayList<Person>();
private ArrayList<Object[]> list;
private File f1, f2;
private PrintWriter pWriter;
private Scanner pReader;
public static void main(String[] args) throws FileNotFoundException{
// TODO Auto-generated method stub
GUIstoringObjects gui = new GUIstoringObjects();
gui.frame.setVisible(true);
}
public GUIstoringObjects()
{
initialize();
}
public void initialize()
{
frame = new JFrame("Adding and Saving Person Objects");
frame.setBounds(75,75,813,408);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
label1 = new JLabel("First Name:");
label1.setBounds(32,27,60,25);
frame.getContentPane().add(label1);
label2 = new JLabel("Last Name:");
label2.setBounds(264,27,82,25);
frame.getContentPane().add(label2);
label3 = new JLabel("Phone Number:");
label3.setBounds(504,27,89,25);
frame.getContentPane().add(label3);
box1 = new JTextField();
box1.setBounds(102,26,140,27);
frame.getContentPane().add(box1);
box2 = new JTextField();
box2.setBounds(354,26,140,27);
frame.getContentPane().add(box2);
box3 = new JTextField();
box3.setBounds(599,26,140,27);
frame.getContentPane().add(box3);
button1 = new JButton("Add Person");
button1.addActionListener(this);
button1.setBounds(120,76,122,33);
frame.getContentPane().add(button1);
button2 = new JButton("Remove Person");
button2.addActionListener(this);
button2.setBounds(120,121,122,33);
frame.getContentPane().add(button2);
button3 = new JButton("Display Person List");
button3.addActionListener(this);
button3.setBounds(252,76,154,33);
frame.getContentPane().add(button3);
button4 = new JButton("Save Person List");
button4.addActionListener(this);
button4.setBounds(416,76,154,33);
frame.getContentPane().add(button4);
button5 = new JButton("Load Person List");
button5.addActionListener(this);
button5.setBounds(416,121,154,33);
frame.getContentPane().add(button5);
button6 = new JButton("Quit Program");
button6.addActionListener(this);
button6.setBounds(599,76,140,33);
frame.getContentPane().add(button6);
table = new JTable();
table.setBounds(0,176,797,194);
frame.getContentPane().add(table);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String action = (((JButton) e.getSource()).getActionCommand());
if(action.equals("Add Person"))
{
String fName = box1.getText();
String lName = box2.getText();
String pNo = box3.getText();
Person p = new Person(fName,lName,pNo);
pList.add(p);
JOptionPane.showMessageDialog(null, fName+" has been Added!");
box1.setText("");
box2.setText("");
box3.setText("");
}
if(action.equals("Remove Person"))
{
String nameChecker = box1.getText();
for(int i = 0; i<pList.size(); i++)
{
if(nameChecker.equals(pList.get(i).getFName()))
{
pList.remove(i);
JOptionPane.showMessageDialog(null, nameChecker+" has been deleted!");
}
}
}
if(action.equals("Display Person List"))
{
list = new ArrayList<Object[]>();
for (int i = 0; i < pList.size(); i++) {
list.add(new Object[] {
pList.get(i).getFName(),
pList.get(i).getLName(),
pList.get(i).getPNo()
});
}
table.setModel(new DefaultTableModel(list.toArray(new Object[][] {}),
new String[] {"First Name", "Surname", "Phone Number"}));
}
if(action.equals("Save Person List"))
{
f1 = new File("PersonList.txt");
try {
pWriter = new PrintWriter(f1);
for(Person p: pList)
{
pWriter.println(p.getFName());
pWriter.println(p.getLName());
pWriter.println(p.getPNo());
}
JOptionPane.showMessageDialog(null, "Person List Stored in File 'PersonList.txt'");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(action.equals("Load Person List"))
{
f2 = new File("PersonList.txt");
try {
pReader = new Scanner(f2);
while (pReader.hasNext())
{
String fName = pReader.nextLine();
String lName = pReader.nextLine();
String pNo = pReader.nextLine();
Person p = new Person(fName,lName,pNo);
pList.add(p);
}
JOptionPane.showMessageDialog(null, "Person List Loaded from 'PersonList.txt'");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(action.equals("Quit Program"))
{
System.exit(0);
}
}
}
And This is my person object below
public class Person {
private String fName, lName, pNo;
public Person(String fName, String lName, String pNo)
{
setFName(fName);
setLName(lName);
setPNo(pNo);
}
public void setFName(String fName)
{
this.fName = fName;
}
public void setLName(String lName)
{
this.lName = lName;
}
public void setPNo(String pNo)
{
this.pNo = pNo;
}
public String getFName()
{
return fName;
}
public String getLName()
{
return lName;
}
public String getPNo()
{
return pNo;
}
public String toString()
{
return getFName()+" "+getLName()+" "+getPNo();
}
public void print()
{
System.out.println(toString());
}
}
As I already said above, for argument sake we had
Bill
Gates
088491038
Cristiano
Ronaldo
0048103874
The Code would be able to read from the file, but once I tried to add more people from the arraylist, it just wouldn't work, can someone help me out?

But if i wanted to add more person objects to the file, the data in the file is overriden and the file will be empty.
Whenever you create an object of PrintWriter, it clear the data of the existing file.
pWriter = new PrintWriter(f1);
You should use append mode property of FileWriter to append the data in the existing file.
FileWriter fileWriter = new FileWriter(f1, true);
^--------- Append Mode
pWriter = new PrintWriter(fileWriter, true);
^----------- Auto Flush
You should close to stream after finishing all the read/writer operation. Better use auto flush property of PrintWriter to avoid manually calling flush() method.
Handle the resources carefully using Java 7- The try-with-resources Statement or finally block.

Related

Gui and binary files

I'm currently working on a project for a class I have, where we have to create a GUI that asks for a number, then read a binary files of 10,000 customers and return the other information on the one with the customer number entered. We also have to have an error that pops up as a JOptionPane when a number outside of 1-10,000 is entered. I'm having some problems with the error message, and my professor also said we need to have a method with this signature:
private Customer getCustomer(long custNumber) throws IOException
that searches the file and returns a customer object. I'm also not sure where exactly to do that. So I started with what I already know, and here's what I have:
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class CustomerLocator extends JFrame
{
private JPanel panel;
private JLabel custNumLabel;
private JLabel custNameLabel;
private JLabel custDisLabel;
private JLabel custBalLabel;
private JLabel custPrefLabel;
private JTextField custNumField;
private JTextField custNameField;
private JTextField custDisField;
private JTextField custBalField;
private JTextField custPrefField;
private JButton findCustBut;
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 500;
public CustomerLocator()
{
setTitle("Customer Locator");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel()
{
custNumLabel = new JLabel("Enter a valid Customer Number: ");
custNumField = new JTextField(10);
custNameLabel = new JLabel("Customer Name: ");
custNameField = new JTextField(10);
custNameField.setEditable(false);
custDisLabel = new JLabel("Customer Discount: ");
custDisField = new JTextField(10);
custDisField.setEditable(false);
custBalLabel = new JLabel("Customer Balance: ");
custBalField = new JTextField(10);
custBalField.setEditable(false);
custPrefLabel = new JLabel("Preferred? ");
custPrefField = new JTextField(10);
custPrefField.setEditable(false);
findCustBut = new JButton("Find this Customer!");
panel = new JPanel();
findCustBut.addActionListener(new ListenerToFindCustomer());
panel.add(custNumLabel);
panel.add(custNumField);
panel.add(findCustBut);
panel.add(custNameLabel);
panel.add(custNameField);
panel.add(custDisLabel);
panel.add(custDisField);
panel.add(custBalLabel);
panel.add(custBalField);
panel.add(custPrefLabel);
panel.add(custPrefField);
}
private class ListenerToFindCustomer implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String numEnteredStr;
long custNumEntered;
String custName;
boolean preferred;
String preferredDisplay;
double acctBal;
String acctBalDisplay;
double discount;
String discountDisplay;
numEnteredStr = custNumField.getText();
custNumEntered = Long.parseLong(numEnteredStr);
int ct=0;
try
{
FileInputStream inStream =
new FileInputStream("c:\\cps\\CustomerObjects.dat");
// DataInputStream inputFile = new DataInputStream(inStream);
ObjectInputStream objectInputFile =
new ObjectInputStream(inStream);
while(true)
{
ct++;
Customer obj = (Customer)objectInputFile.readObject();
//System.out.println(obj.getCustName());
if (custNumEntered == obj.getCustNum())
{
custName = obj.getCustName();
acctBal = obj.getBalance();
acctBalDisplay = Double.toString(acctBal);
discount = obj.getDiscount();
discountDisplay = Double.toString(discount);
preferred = obj.getPreferred();
preferredDisplay = Boolean.toString(preferred);
custNameField.setText(custName);
custBalField.setText(acctBalDisplay);
custPrefField.setText(preferredDisplay);
custDisField.setText(discountDisplay);
if (custNameField == null)
{
JOptionPane.showMessageDialog(null, "Error");
}
}
}
}
catch (Exception ex)
{
System.out.println(ex.toString());
}
}
}
public static void main(String[] args)
{
new CustomerLocator();
}
}
So, with this, the JOptionPane doesn't show up, so my questions are
1. How do I get the error message to pop up?
2. How do I incorporate the method my professor requested?
Your code
if (custNameField == null)
{
JOptionPane.showMessageDialog(null, "Error");
}
should read
if (custName == null)
{
JOptionPane.showMessageDialog(null, "Error");
}
It should also be moved outside of the while loop.
You also need a way to break the loop once you reach the end of the file.
Everything inside and including your try { ... } catch (Exception ex) { ... } can be moved to the method that your instructor suggests.
You should also change the try-catch to have another catch (IOException ioEx) { throw ioEx; }

Displaying the values of an Arraylist with a JTable

I created a class named EmployeeGUI that is able to create any amount of user Employee objects and add them to an arraylist. The problem i have is that i have a JTable at the bottom of my GUI that i want to display all the objects that i've created but in my case the GUI Creates a new Table Object each time it goes through a for loop with the details of an object but as the for loop goes on the new details overwrites the old details rather than being added to the bottom of a jtable. Can anyone help me debug my errors?
Here is my Code
import java.awt.event.*;
public class EmployeeGUI extends JFrame implements ActionListener{
/**
* #param args
*/
JFrame frame;
JButton button1, button2, button3, button4;
JTextField box1, box2, box3;
JLabel label1, label2, label3;
JTable table1;
int length = 0;
ArrayList<Employee> empArray = new ArrayList<Employee>();
public static void main(String[] args) {
// TODO Auto-generated method stub
EmployeeGUI empG = new EmployeeGUI();
empG.frame.setVisible(true);
}
public EmployeeGUI()
{
initialize();
}
public void initialize() {
// TODO Auto-generated method stub
frame = new JFrame("A Sample Window");
frame.setBounds(50,50,680,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
label1 = new JLabel("F-Name:");
label1.setBounds(30,33,54,25);
frame.getContentPane().add(label1);
box1 = new JTextField();
box1.setBounds(94, 35, 128,20);
frame.getContentPane().add(box1);
label2 = new JLabel("S-Name:");
label2.setBounds(250,33,54,25);
frame.getContentPane().add(label2);
box2 = new JTextField();
box2.setBounds(305, 35, 128,20);
frame.getContentPane().add(box2);
label3 = new JLabel("Phone:");
label3.setBounds(461,33,54,25);
frame.getContentPane().add(label3);
box3 = new JTextField();
box3.setBounds(500, 35, 128,20);
frame.getContentPane().add(box3);
button1 = new JButton("Add Employee");
button1.addActionListener(this);
button1.setBounds(71,131,113,39);
frame.getContentPane().add(button1);
button2 = new JButton("Remove Employee");
button2.addActionListener(this);
button2.setBounds(194,131,128,39);
frame.getContentPane().add(button2);
button3 = new JButton("Display Employee");
button3.addActionListener(this);
button3.setBounds(332,131,128,39);
frame.getContentPane().add(button3);
button4 = new JButton("Quit Program");
button4.addActionListener(this);
button4.setBounds(475,131,113,39);
frame.getContentPane().add(button4);
table1 = new JTable();
table1.setBounds(0,184,664,178);
frame.getContentPane().add(table1);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String action = ((JButton) e.getSource()).getActionCommand();
if(action.equals("Add Employee"))
{
String fName = box1.getText();
String lName = box2.getText();
String pNo = box3.getText();
int mobile = Integer.parseInt(pNo);
Employee ee = new Employee(fName,lName,mobile);
empArray.add(ee);
length++;
JOptionPane.showMessageDialog(null, "Employee Added");
}
if(action.equals("Remove Employee"))
{
String fName = box1.getText(), lName = box2.getText();
int mobile = Integer.parseInt(box3.getText());
Employee ee = new Employee(fName,lName,mobile);
if(length>0)
{
for(int i=0; i<empArray.size(); i++)
{
if(empArray.get(i).getLName() == ee.getLName())
{
empArray.remove(i);
JOptionPane.showMessageDialog(null, "Employee Removed");
}
}
}
else{
throw new ListEmptyException("List is Empty");
}
}
if(action.equals("Display Employee"))
{
for(int i = 0; i <empArray.size(); i++)
{
table1.setModel(new DefaultTableModel(
new Object[][] {
{empArray.get(i).getFName(),empArray.get(i).getLName(),empArray.get(i).getMobile()}
},
new String[] {
"First Name", "Surname", "Phone Number"
}
));
}
}
if(action.equals("Quit Program"))
{
System.exit(0);
}
}
}
and the Employee Class
public class Employee {
private String fName,lName;
private int mobile;
public Employee(String fName, String lName, int mobile)
{
setFName(fName);
setLName(lName);
setMobile(mobile);
}
private void setMobile(int mobile) {
// TODO Auto-generated method stub
this.mobile = mobile;
}
public void setLName(String lName) {
// TODO Auto-generated method stub
this.lName = lName;
}
public void setFName(String fName) {
// TODO Auto-generated method stub
this.fName = fName;
}
public String getFName()
{
return fName;
}
public String getLName()
{
return lName;
}
public int getMobile()
{
return mobile;
}
public String toString()
{
return getFName()+" "+getLName()+" "+getMobile();
}
public void print()
{
System.out.println(toString());
}
}
only comment, longer
see number of table1.setModel(new DefaultTableModel( created in loop for(int i = 0; i <empArray.size(); i++)
new Object[][] {{empArray.get(i).getFName(), empArray.get(i).getLName(),empArray.get(i).getMobile()}}, is converted to DataVector, you lost, haven't access to this array
(if is there reason to hold two the same arrays in your program then) use array based on util.List in AbstractTableModel
the new details overwrites the old details rather than being added to the bottom of a jtable.
First add all the record in a List then set the model just once otherwise it will override the last one in loop.
sample code:
if (action.equals("Display Employee")) {
List<Object[]> list = new ArrayList<Object[]>();
for (int i = 0; i < empArray.size(); i++) {
list.add(new Object[] {
empArray.get(i).getFName(),
empArray.get(i).getLName(),
empArray.get(i).getMobile()
});
}
table1.setModel(new DefaultTableModel(list.toArray(new Object[][] {}),
new String[] {"First Name", "Surname", "Phone Number"}));
}
You can use the addRow() method of the DefaultTableModel, like this:
((DefaultTableModel)table1.getModel()).addRow(new Object[] {
empArray.get(i).getFName(),
empArray.get(i).getLName(),
empArray.get(i).getMobile()
});

Java reading and writing ArrayList type Contact to GUI

EDIT
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)
{}
}
Regarding
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 contents 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().
Regarding
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.
Edit
You show:
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(...) method.
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.

Java ArrayList null pointer exception

EDIT
I've cleaned up the .equals method for string equality and changed the ContactsCollection initialization to:
public static ArrayList<Contact> contactList = new ArrayList<Contact>();
I've also changed the action performed method in hopes that 'Display contacts' would show more than one contact.
if (contactInput.equals("Display contacts"))
{
ContactsCollection.read();
for (int i = 0; i < contactList.size(); i++)
{
contact = (Contact)contactList.get(i);
for (int j =0; j < contactList.size(); j++)
{
textArea.append(contact.getName() + "," + contact.getNumber() + "\n");
}
}
}
Ultimately the .dat file is written but does not contain any data that is added through the GUI.
END EDIT
I am writing a mock cellphone GUI that acts as a very basic contacts manager. There are several other classes that do not deal with the ArrayList that are working as intended.
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);
I have a feeling that I did something wrong when coding the Contacts and ContactsCollection classes. I'm hoping the program to run as follows: The user clicks add contact and enters the information which becomes an object Contact and is added to the contactList ArrayList and written (serialized) to a file "contactList.dat". When the user clicks display contacts the file is read in and each contact is displayed in GUI.
I think that there are several issues with the way I set up the ArrayList, but I think I'm very close to having the program run as I had hoped. Any help is greatly appreciated!
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)
{}
}
Change
public static ArrayList<Contact> contactList;
to
public static ArrayList<Contact> contactList = new ArrayList<>();
in your version contactList is null because you never initialize it and in the write() method you are trying to call size() on it.
Also, there are some serious flaws in your GUI class (in the actionPerformed() method), read this question to fix them: How do I compare strings in Java?
Also remember that textArea.setText(...) will set the complete text for the textArea, so because this is in a loop in your code, the textArea will contain the output of the last iteration of that loop only. In your case it will be only the last contact.

reading from file and showing in textarea java

I have the following code which reads names from the test file, which works fine
public class Names {
Scanner scan;
static String Firstname;
static String Surname;
static String Fullname;
public void OpenFile()
{
try
{
scan = new Scanner(new File("test.txt"));
System.out.println("File found!");
}
catch(Exception e)
{
System.out.println("File not found");
}
}
public void ReadFile()
{
while(scan.hasNext())
{
Firstname = scan.next();
Surname = scan.next();
Fullname = Firstname + " " + Surname;
System.out.println(Fullname);
}
}
public void CloseFile()
{
scan.close();
}
}
Then I have this main class which calls the Names class. it works fine apart from it only shows the last names from the test file.
public class NameSwing implements ActionListener {
private JTextArea tf = new JTextArea(20,20);
private JFrame f = new JFrame("names");
private JButton b = new JButton("view");
static String fullName;
public NameSwing(){
f.add(new JLabel("Name"));
tf.setEditable(true);
f.add(tf);
b.addActionListener(this);
f.add(b);
f.setLayout(new FlowLayout());
f.setSize(300,100);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
tf.setText(fullName);
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
NameSwing nameSwing = new NameSwing();
Names t = new Names();
t.OpenFile();
t.ReadFile();
t.CloseFile();
fullName = Names.Fullname;
}
}
This is the test file content.
Nick Harris
Olly Dean
Emma Sammons
Henry Blackwell
How can I get the textarea to show all of the names from the reader, and not just the last name?
Throw out your Names class as it isn't very helpful and over-uses static fields to its detriment. The best solution in my mind is to:
Create a File that holds your text file
Create a FileReader object with this File
Use this to create a BufferedReader object
call the JTextArea's read(...) method passing in the BufferedReader
And your done.
i.e., in actionPerformed:
BufferedRead buffReader = null;
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
buffReader = new BufferedReader(fileReader);
tf.read(buffReader, "file.txt");
} catch (WhateverExceptionsNeedToBeCaught e) {
e.printStackTrace();
} finally {
// close your BufferedReader
}
You are using too many static fields for no good reasons. Always use
static fields if you intend to make your class a Factory Class, which
in this case is not appropriate.
You are breaking the fundamental rule of encapsulation, by providing each method with a public Access Specifier, without the need of it.
Instead of calling setSize(), you can simply use pack(), which can determine the dimensions of the Container, in a much better way, than the arbitrary values you had specified.
Please do read about Concurrency in Swing, since appears to me your knowledge is a bit short on that front.
Please do learn Java Naming Conventions.
Moreover, you can simply use a StringBuilder Class, to do this thingy for you. Have a look at the modified code of yours. Do ask anything that is beyond your grasp, I be happy to help on that.
MODIFIED CODE :
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NameSwing implements ActionListener {
private Names t;
private JTextArea tf = new JTextArea(20,20);
private JFrame f = new JFrame("names");
private JButton b = new JButton("view");
public NameSwing(){
performFileRelatedTask();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JScrollPane scroller = new JScrollPane();
scroller.setBorder(BorderFactory.createLineBorder(Color.BLUE.darker(), 5));
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout(5, 5));
centerPanel.add(new JLabel("Name", JLabel.CENTER), BorderLayout.PAGE_START);
tf.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
tf.setEditable(true);
centerPanel.add(tf, BorderLayout.CENTER);
scroller.setViewportView(centerPanel);
JPanel footerPanel = new JPanel();
b.addActionListener(this);
footerPanel.add(b);
contentPane.add(scroller, BorderLayout.CENTER);
contentPane.add(footerPanel, BorderLayout.PAGE_END);
f.setContentPane(contentPane);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
private void performFileRelatedTask()
{
t = new Names();
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
tf.setText(t.getFullNames().toString());
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new NameSwing();
}
});
}
}
class Names {
private Scanner scan;
private String firstname;
private String surname;
private StringBuilder fullnames;
public Names()
{
fullnames = new StringBuilder();
openFile();
readFile();
closeFile();
}
public StringBuilder getFullNames()
{
return fullnames;
}
private void openFile()
{
try
{
scan = new Scanner(new File("test.txt"));
System.out.println("File found!");
}
catch(Exception e)
{
System.out.println("File not found");
}
}
private void readFile()
{
while(scan.hasNext())
{
firstname = scan.next();
surname = scan.next();
fullnames.append(firstname + " " + surname + "\n");
}
}
private void closeFile()
{
scan.close();
}
}
The problem is at line
Fullname = Firstname + " " + Surname;.
Make it
Fullname += Firstname + " " + Surname; + "\n"
You problem is solved :)
Here you need the change
while(scan.hasNext())
{
Firstname = scan.next();
Surname = scan.next();
//Assigning each time instead of append
Fullname = Firstname + " " + Surname;
}
Here is complete fix:
public class NameSwing implements ActionListener {
private JTextArea textArea = new JTextArea(20, 20);
private JFrame frame = new JFrame("Names");
private JButton btnView = new JButton("View");
private Scanner scanner;
private String firstName;
private String surName;
private String fullName;
public NameSwing() {
frame.add(new JLabel("Name"));
textArea.setEditable(true);
frame.add(textArea);
btnView.addActionListener(this);
frame.add(btnView);
frame.setLayout(new FlowLayout());
frame.setSize(300, 100);
frame.setVisible(true);
}
public void OpenFile() {
try {
scanner = new Scanner(new File("test.txt"));
System.out.println("File found!");
} catch (Exception e) {
System.out.println("File not found");
}
}
public void ReadFile() {
while (scanner.hasNext()) {
firstName = scanner.next();
surName = scanner.next();
// assign first time
if( fullName == null ) {
fullName = firstName + " " + surName;
} else {
fullName = fullName + "\n" + firstName + " " + surName;
}
System.out.println(fullName);
}
}
public void CloseFile() {
scanner.close();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnView) {
textArea.setText(fullName);
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
NameSwing nameSwing = new NameSwing();
nameSwing.OpenFile();
nameSwing.ReadFile();
nameSwing.CloseFile();
}
}

Categories