Question on formating data in a file

Hello, I'm building an GUI address book that allows you to add new addresses, delete addresses and edit addresses entries. If you edit or add new addresses an another UI comes out allowing you to add in all details about the new address or the address that the user decided to edit. With the address comes other details about the address for example (the person who lives at this address, phone number, work number, etc...). Now my question what would be a better way to hold and collect the data. I was thinking of the the following two options:

Option 1: Read some data from a file - If I do this options I don't how to format the data in the file so when I read the file in Java it will collect all the data and associate it with the right variable names

Option 2: Build a vector that is empty and associate columns to all the variables - My thinking around this comes from database systems. In database systems all you would have to do is build a table with columns that represent a group of data and everytime that you enter in some new data the table would grow in rows.

If anyone can help me with this problem that would be great. Just to clarfiy I am using swing widgets . thanks!

DancingFighterGAsked:
Who is Participating?
 
objectsConnect With a Mentor Commented:
          for (Iterator it = Address.keySet().iterator(); it.hasNext(); ) {
                Object key = it.next();
                Object value = Address.get(key);
                ta.append("key+"="+value+"\n");
          }
0
 
CEHJCommented:
Simplest would be to make an Address class and de/serialize a collection of them from/to disk
0
 
objectsCommented:
There's not really a 'better' way, both those approaches are very suitable.
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
CEHJCommented:
Since you should probably have an Address class anyway or maybe an AddressBookEntry (since this would probably hold info in addition to the address) the method i suggested seems a fairly natural one
0
 
DancingFighterGAuthor Commented:
Well, right now I'm in the process of using an growable array to hold my data but I'm having problems displaying the data in the table in the GUI?
0
 
CEHJCommented:
Probably better to use a TableModel, and easier if you can use a ready-made one such as DefaultTableModel
0
 
CEHJCommented:
...although if you have a collection of classes such as AddressBookEntry, it may be easier to make your own from AbstractTableModel
0
 
CEHJCommented:
See "Creating a Table Model" at http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

You can serializable the TableModel to file
0
 
objectsCommented:
heres some details on using database:
http://java.sun.com/docs/books/tutorial/jdbc/index.html

how you actually maintain your data in your application is (and should be) independant of the perstistent data store you use to save it.
0
 
CEHJCommented:
What you can do is to program to an interface such as something like this:

import javax.swing.table.TableModel;

public interface IDataStorage {
      public TableModel loadData();
      public void storeData();
}

and your application can implement this interface. Changing the method of storage should  then not break your application code (the client of the interface), but only require a different implementation.

Using a database may be preferable in the sense that this is a more generic approach than serialization, is more scaleable and the experience gained in it will stand you in good stead.
This is a highly regarded free db written in Java  that is used in professional Open Source software:

http://hsqldb.sourceforge.net/
0
 
objectsCommented:
> Using a database may be preferable in the sense

Make up your mind :D
0
 
CEHJCommented:
This forum is about discussion and discovery. There is not just one single 'correct' way of implementing a solution in most cases, so 'making up one's mind' doesn't happen until implementation starts.
0
 
objectsCommented:
> There is not just one single 'correct' way of implementing a solution

Yes thats what I had already stated, but you suggested serialization was the easiest, and then stated db was preferable. All this does is confuses the asker.
0
 
CEHJCommented:
>>but you suggested serialization was the easiest, and then stated db was preferable.

Both statements are true. Are you suggesting DancingFighterG's mind can't cope with that complexity?
0
 
objectsCommented:
Never said they weren't true
0
 
DancingFighterGAuthor Commented:
In most situations using a database would be my first choice but I'm tyring to learn how to work with either arrays or vectors without getting input from an outside source. I'm tyring to get this application to be stand alone.
0
 
CEHJCommented:
OK. In that case serialization is the better option probably. Use the interface as i suggested and then you will be able to change to something else later if you want with greater ease
0
 
DancingFighterGAuthor Commented:
Right now I have two interfaces setup. One interface is used to view the current address and gives the user the options to edit the address, add a new address or delete the ones that are already present. My other UI gives is going to give detail on on the address. I have the table showing the data that I want but now I am on the task of linking the first and last name of the address to all the other information.
0
 
CEHJCommented:
Yes, 'interface' here in my example is being used in a different sense than user interface. See
http://mindprod.com/jgloss/interface.html#INTERFACE
0
 
objectsCommented:
> I'm tyring to get this application to be stand alone.

Then start by defining the format required to store the details of your data.
0
 
DancingFighterGAuthor Commented:
Ok, well the data is the following:

First Name, Last Name, Title, Company, Intial, Mr/Mrs., Birthday, Age

The second UI has other information which gives details beyond the previous details. For example:

Home Address, Work Address, Telephone, Categories, Email, and comments.

Now what I'm am tyring to do is in the first UI show the first and lastname of the person with an address. If I want to change the details of that persons address I would click on the name and used the name as a parameter to an action which would bring up the other details in the second UI. I'm really stumped on how to do this without a database!

0
 
CEHJCommented:
You need to define a Person class or some such. In keeping with db usage, you should have an id field (you may or may not display this) as this will distinguish between two Person uniquely

Isn't  Title the same thing as Mr/Mrs?
You should probably just define date of birth. Age and birthday can be derived from this.
Use a TableModel as i mentioned. You can wrap your Person objects in this and display them in a JTable. Clicking on a row could bring up your address UI. Often dbs would have another address entity, but you should probably keep things simple and store address data in Person
0
 
objectsCommented:
>  If I want to change the details of that persons address I would click on the name and used the name as a parameter to an action which would bring up the other details in the second UI.

If you're not intending to have too many people then you'd probably be fine to store all your people in memory in a Map. That would allow to easily locate the selected person.
In fact your first UI already had your list of Person's then a lookup probably would not even be necessary.
0
 
DancingFighterGAuthor Commented:
Ok, this is what I have right now. I was able to implement the table model so now I have the following:

JTable table = new JTable(new MyTableModel());
  class MyTableModel extends AbstractTableModel {
        private String[] columnNames = {"Name"};
        private Object[][] data = {{"Mary Campione"},{"Alison Huml"}, {"Kathy Walrath"}, {"Sharon Zakhour"}, {"Philip Milne"}};

         public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }
}

It shows contents in the form of a table!

I also tried implementing a vector and it displayed the info but not in the table. Example:

Vector v1 = new Vector(0);
    Vector v2 = new Vector(0);
    v1.add("hello");
    v2.add("bob");
    v1.add("bie");
    v2.add("sam");
    v1.add("run");
    v2.add("spot");
    horizontal.add(v1);
    horizontal.add(v2);

Since I still new to Java I somehow was able to display these elements to a text area using addElement.

Now object, how do I go about doing a map in java? Looking up a person would not be an issue since the first UI has the list of people. I need to be able access the other  information that can be shown in the other UI. Also, how would I format my data so when I look at second UI it wil display the data the corresponds with the person that was picked. Right now I not going to worry about get the new, edit and update to work. I still need to make sure that the vector or array that I can use can grow or shrink.
0
 
objectsCommented:
>  I need to be able access the other  information that can be shown in the other UI.

where is this data currently stored?
0
 
DancingFighterGAuthor Commented:
Right now my data is not stored anywhere. I don't know what would be the best way to handle it all. i.e Array or Vecotr. The data is the following:

LastName
Firstname
Zip
State
etc...

There is over thirty pieces of data that a user has access too.
0
 
DancingFighterGAuthor Commented:
Let me clairfy. The data that is displaying to the first UI is in an array. All this data displays to the table. Exmaple!

private Object[][] data = {{"Mary Campione"},{"Alison Huml"}, {"Kathy Walrath"}, {"Sharon Zakhour"}, {"Philip Milne"}};
0
 
DancingFighterGAuthor Commented:
Ok, well I'm trying a new approach and just reading a file and storing the data in a vector. Right now, I give the user the option to pick a file to upload. The problem is that when I load the file the programs exits out. I don't know why? Also, how would I take the contents from the vector and display them to a textarea not a table. This is what I have right now:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.*;
import java.io.*;

public class AddressBookUI extends JFrame {
  JPanel contentPane;
  JFileChooser fileChooser;
  JPanel jPanel3 = new JPanel();
  JButton Edit = new JButton();
  JButton New = new JButton();
  JButton Delete = new JButton();
  JTextPane Category = new JTextPane();
  JTextPane middlefor = new JTextPane();
  JTextPane viewing = new JTextPane();
  String[] items = {"Friend", "Family", "Collegues", "Client", "CS538", "Custom1", "Custom2", "Custom3", "Custom4", "Custom5", "Custom6", "Custom7"};
  JComboBox All = new JComboBox(items);
  JTextPane TextHead = new JTextPane();
  JTextPane TextHead2 = new JTextPane();
  JScrollPane Address = new JScrollPane();
  JTextArea jTextArea1 = new JTextArea();
  JMenuBar jMenuBar1 = new JMenuBar();
  JMenu jMenu1 = new JMenu();
  JMenu jMenu2 = new JMenu();

  /**Construct the frame*/
  public AddressBookUI() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
      jbInit();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }

//Method that displays the JFileChooser and returns the name of the selected file
public String fileChooser() throws IOException
{
  String fileName, currentPath = new String();

               File currentDirectory = new File(".");
               currentPath = currentDirectory.getAbsolutePath();
               fileChooser = new JFileChooser(currentPath);
               fileChooser.showOpenDialog(null);

               File selectedFile = fileChooser.getSelectedFile();
               fileName = selectedFile.getName();

               return fileName;
          }

public Vector fileBuffer(String fileName) throws IOException
{
    FileReader fileIn = new FileReader(fileName);
    BufferedReader in = new BufferedReader(fileIn);
    Vector stringVector = new Vector();
    String tempString = "";

    while(true)
    {
        String currentLine = in.readLine();
        if(currentLine == null)
        {
            if(tempString.length() > 0)
            {
                stringVector.addElement(tempString);
            }
            break;
        }
        else if(currentLine.length() > 0)
        {
            tempString = tempString + "  " + currentLine + '\n';
        }
        else
        {
            stringVector.addElement(tempString);
            tempString = "";
        }
    }
    in.close();
    return stringVector;
}

  /**Component initialization*/
  private void jbInit() throws Exception  {
    contentPane = (JPanel) this.getContentPane();
    jPanel3.setLayout(null);
    jPanel3.setBounds(new Rectangle(22, 36, 353, 93));
    jPanel3.setBorder(BorderFactory.createEtchedBorder());
    jPanel3.setBackground(Color.lightGray);
    contentPane.setLayout(null);
    this.getContentPane().setBackground(Color.lightGray);
    this.setSize(new Dimension(635, 729));
    this.setTitle("AddressBookUI");
    Edit.setText("Edit");
    Edit.setBounds(new Rectangle(134, 31, 84, 39));
    Edit.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        Edit_mousePressed(e);
      }
    });
    New.setText("New");
    New.setBounds(new Rectangle(16, 31, 84, 38));
    New.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        New_mousePressed(e);
      }
    });
    Category.setBackground(Color.lightGray);
    Category.setEditable(false);
    Category.setText("Category");
    Category.setBounds(new Rectangle(405, 49, 67, 21));
    middlefor.setBackground(Color.lightGray);
    middlefor.setEditable(false);
    middlefor.setText("for");
    middlefor.setBounds(new Rectangle(480, 48, 36, 22));
    viewing.setBackground(Color.lightGray);
    viewing.setEditable(false);
    viewing.setText("Viewing");
    viewing.setBounds(new Rectangle(517, 48, 61, 24));
    All.setBounds(new Rectangle(435, 77, 125, 21));
    All.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(ActionEvent e) {
        All_actionPerformed(e);
      }
    });
    Delete.setBounds(new Rectangle(257, 32, 80, 39));
    Delete.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        Delete_mousePressed(e);
      }
    });
    Delete.setText("Delete");
    TextHead.setBackground(Color.lightGray);
    TextHead.setText("Address");
    TextHead.setBounds(new Rectangle(244, 164, 61, 18));
    TextHead2.setBackground(Color.lightGray);
    TextHead2.setText("List");
    TextHead2.setBounds(new Rectangle(302, 164, 38, 18));
    Address.getViewport().setBackground(Color.lightGray);
    Address.setAutoscrolls(true);
    Address.setToolTipText("Hello");
    Address.setBounds(new Rectangle(13, 191, 611, 392));
    jTextArea1.setToolTipText("");
    jMenu1.setText("File");
    jMenu2.setText("Help");
    jPanel3.add(Delete, null);
    jPanel3.add(Edit, null);
    jPanel3.add(New, null);
    contentPane.add(middlefor, null);
    contentPane.add(viewing, null);
    contentPane.add(Category, null);
    contentPane.add(All, null);
    contentPane.add(TextHead, null);
    contentPane.add(TextHead2, null);
    contentPane.add(Address, null);
    Address.getViewport().add(jTextArea1, null);
    contentPane.add(jPanel3, null);
    jMenuBar1.add(jMenu1);
    jMenuBar1.add(jMenu2);
}

  /**Overridden so we can exit when window is closed*/
  protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
      System.exit(0);
    }
  }
  void All_actionPerformed(ActionEvent e) {
    // Display all address that fall under the following category
  }

  void New_mousePressed(MouseEvent e) {
       AddressEntryUI frame1 = new AddressEntryUI();
       frame1.setVisible(true);
  }

  void Edit_mousePressed(MouseEvent e) {
      AddressEntryUI frame = new AddressEntryUI();
      frame.setVisible(true);
  }

  void Delete_mousePressed(MouseEvent e) {
  }

}

Help!
0
 
DancingFighterGAuthor Commented:
Does anyone have any sources concerning TreeMaps?
0
 
CEHJCommented:
What do you want to know about them? btw i was going to post this for you a while ago:

import javax.swing.table.TableModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.event.TableModelListener;
import java.util.List;
import java.util.ArrayList;
import javax.swing.JTable;
import javax.swing.JFrame;
import javax.swing.JScrollPane;

import java.awt.*;
import javax.swing.*;

/**
 *  Description of the Class
 *
 * @author     CEHJ
 * @created    29 March 2004
 */
public class People implements IDataStorage, TableModel {

  List personList;
  /**
   *  Description of the Field
   */
  public final static String[] COLUMN_NAMES = {"ID", "First name", "Last name"};


  public static void main(String[] args) {
    JFrame frame = new JFrame();
    JTable table = new JTable(new People().loadData());
    JScrollPane scrollPane = new JScrollPane(table);
    frame.getContentPane().add(scrollPane);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 200);
    frame.setVisible(true);
  }

  public void setValueAt(Object o, int row, int col) {
  }

  public Object getValueAt(int row, int col) {
    Person person = (Person) personList.get(row);
    switch (col) {
            //case 0:
            //return new Integer(person.getId());
            case 0:
              return person.getFirstName();
            case 1:
              return person.getLastName();
            default:
              return null;
    }
  }

  public String getColumnName(int col) {
    return COLUMN_NAMES[++col];
  }

  public TableModel loadData() {
    // Deserialize. For the purposes of this demo, we're calling demoLoad
    demoLoad();
    return this;
  }

  public void demoLoad() {
    personList = new ArrayList();
    final String NAMES[][] = {
        {"John", "Adams"},
        {"Benjamin", "Franklin"},
        {"Abraham", "Lincoln"},
        };
    for (int i = 0; i < NAMES.length; i++) {
      personList.add(new Person(i, NAMES[i][0], NAMES[i][1]));
    }

  }

  public void storeData() {
    // Serialize
  }

  public Class getColumnClass(int col) {
    if (col == 0) {
      //return java.lang.Integer.class;
      // (Hide id column)
      return java.lang.String.class;
    }
    else {
      return java.lang.String.class;
    }
  }

  public boolean isCellEditable(int row, int col) {
    return false;
  }

  public int getRowCount() {
    return personList.size();
  }

  public int getColumnCount() {
    // (Hide id column)
    return 2;
  }

  public void addTableModelListener(TableModelListener listener) {
  }

  public void removeTableModelListener(TableModelListener listener) {
  }

}


interface IDataStorage {


  public TableModel loadData();


  public void storeData();
}


class Person {


  private int id;
  private String firstName;
  private String lastName;
  private String addressLine1;
  private String addressLine2;


  public Person(int id) {
    this.id = id;
  }


  public Person(int id, String firstName, String lastName) {
    this(id);
    this.firstName = firstName;
    this.lastName = lastName;
  }



  public void setId(int id) {
    this.id = id;
  }

  public int getId() {
    return id;
  }


  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setAddressLine1(String addressLine1) {
    this.addressLine1 = addressLine1;
  }


  public String getAddressLine1() {
    return addressLine1;
  }

  public void setAddressLine2(String addressLine2) {
    this.addressLine2 = addressLine2;
  }

  public String getAddressLine2() {
    return addressLine2;
  }

}
0
 
DancingFighterGAuthor Commented:
Wow, thanks. I was trying a different approach using TreeMap. I like the concept of treemaps because the items are easy to find. I would like to implement this application this way.
0
 
DancingFighterGAuthor Commented:
Right now I'm trying to read in a file and place the contents in a textarea. This is what I have right now:

try {
        BufferedReader in = new BufferedReader(new FileReader("trivia.txt"));
        String addresslist;
        while ((addresslist = in.readLine()) != null) {
             // I don't know what to put here
        }
        in.close();
    } catch (IOException e) {
    }

Also how would I get the contents in the textarea?
0
 
DancingFighterGAuthor Commented:
After the while loop I would like to print out contents to the textArea called AddressList and store the contents in a TreeMap.
0
 
objectsCommented:
      while ((addresslist = in.readLine()) != null) {
            ta.append(line);
            ta.append("\n");
        }

> Also how would I get the contents in the textarea?

String contents = ta.getText();
0
 
DancingFighterGAuthor Commented:
Ok, this is what I have:

 try {
        BufferedReader in = new BufferedReader(new FileReader("test.txt"));
        String BigList;
        while ((BigList = in.readLine()) != null) {
            AddressList.append(BigList);
            AddressList.append("\n");
        }
        in.close();
    } catch (IOException e) {
    }

  }

I tried the string contents = AddressList.getText() to get the contents from the file in the textarea but nothing showed up. I even tried putting that statement in the while loop.
0
 
objectsCommented:
nothing showed up where?
0
 
DancingFighterGAuthor Commented:
In the textArea. Overall this is part of what I want to do:

1. Read a file into a TreeMap
2. Output of contents of the TreeMap to a textArea
3. Be able to do operations on the data in the TreeMap (i.e Delete, Add and Edit info)
0
 
DancingFighterGAuthor Commented:
Sorry for being such a nag but I REALLY WANT to get this working! As you can tell I'm very new to Java
0
 
objectsCommented:
have you added the text area to your gui?
Is it reading the file ok? you currently ignore any exceptions reading the file so would not know if it failed to read the file. I suggest at least:

   } catch (IOException e) {
       e.printStackTrace();
    }
0
 
DancingFighterGAuthor Commented:
There is a textArea in my gui. Right now it throws an error saying that the file cannot be found but I have the file in the spot that the applications is being stored at. Is there suppose to another place to put it?
0
 
DancingFighterGAuthor Commented:
Ok, I found the problem. The file had to be in the same place as my project not my source code!
0
 
DancingFighterGAuthor Commented:
Ok, so how can I get all this data to be stored in a TreeMap so I can do some New, Delete and Edit to the info.
0
 
objectsCommented:
you need to create a new class to store the details and add them to your map using whatever key field you use:
map.put(personkey, person);
0
 
DancingFighterGAuthor Commented:
When you mean my keyfield are you reffering to the different fields that a person might have. For example, for a person named Greg the personkey would be something like address or gender. Is that what you are getting at. I'm still learning some aspects about TreeMaps.
0
 
DancingFighterGAuthor Commented:
I think I have an idea of what you are talking about. So would I have to iterate to collect them all and put them in a TreeMap?
0
 
objectsCommented:
by key i mean a field that uniquely identifies a particular person
0
 
objectsCommented:
0
 
DancingFighterGAuthor Commented:
Can someone give me an example of how I would populate a TreeMap with a text file.
0
 
DancingFighterGAuthor Commented:
Ok, I have formatted my data like so;

Greg, Richardson, 1010 Austin Bluffs, Student, GR, Mr., 08/07/81, 1
Scott, Richardson, 1010 Austin Bluffs, Student, SR, Mr., 08/07/81, 2
Richard, Richardson, 1010 Austin Bluffs, Student, RR , Mr., 08/07/81, 3
Voldo, Richardson, 1010 Austin Bluffs, Student, VR , Mr., 08/07/81, 4

I'm trying to have each section with a comma be a key so Greg , Scott, Richard and Voldo will a name key.

Is this the right idea?
0
 
DancingFighterGAuthor Commented:
Ok, right now I am trying to display the contents of a TreeMap. This is what I have right now.

try {
        BufferedReader in = new BufferedReader(new FileReader("test.txt"));
        String BigList;
        while ((BigList = in.readLine()) != null) {
            AddressList.append(BigList);
            AddressList.append("\n");
            Map map = new HashMap();
            map.put("Foo", "Bar");
            map.put("Bar", "Foo");
            map.put("Greg", "Voldo");
            map.put("Foo", "Baz");
            map = new TreeMap(map);

            // List the entries
           for (Iterator it = Address.keySet().iterator(); it.hasNext(); ) {
                Object key = it.next();
                Object value = Address.get(key);
          }

        }
        in.close();
    }
    catch (IOException e) {
      e.printStackTrace();
    }

  }

What statement am I missing to display the elements to the textArea?
0
 
DancingFighterGAuthor Commented:
thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.