Results 1 to 12 of 12
  1. #1
    purple is offline Member
    Join Date
    Nov 2009
    Posts
    5
    Rep Power
    0

    Default Reading from file and adding to JTable

    I need to read in contacts from a file (each contact has 4 lines each - name, phone number etc.)
    I then have to display these contacts in a JTable.
    I tried to read the details into an arrayList, but then realised that after every 4 lines i need {} to separate the contacts.
    Would I be able to create substrings surrounded by {} and then put them in a table that way?
    Sorry if this doesn't make much sense, I'm getting myself pretty confused.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    If I were doing this, I would read in each row of data (name, phone number, etc) into a Vector<Object> and then place the newly created Vector into a Vector<Vector>. I'd then create a DefaultTableModel object using this Vector<Vector> plus a Vector<String> that holds my column names, and then set my JTable's model to this model. YMMV. Much luck!

  3. #3
    purple is offline Member
    Join Date
    Nov 2009
    Posts
    5
    Rep Power
    0

    Default

    I understand what you mean, I'll have a go at doing that and see how it goes.
    Just out of interest, would my idea work?
    We've been learning about arrayLists in class, but we haven't thouched on vectors at all.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    ArrayList could work if you used an AbstractTableModel, but that would involve a lot more work.

    I have no idea what you meant though about the brackets: { and }.

  5. #5
    purple is offline Member
    Join Date
    Nov 2009
    Posts
    5
    Rep Power
    0

    Default

    I've been playing around with the Vectors but am struggling now.
    The layout of the text file is this:
    smith, bob
    0207393933
    0774545435
    1 london road, london
    jones, mary
    06546546
    056506
    123 elm road
    etc

    So each 'contact' has 4 lines in the text file.
    In the example we used in class we were using objects, not vectors, and each 'contact' was surrounded by {} e.g. Object[][] addresses = {{"Hancock, Bob", "01202719029", "07676101393","1 Charminster Road, Bournemouth, Dorset, BH8 8UE"}};

    I've managed to read the whole file in as one long vector. How would I go about breaking it up so that it will split it up into sections of 4 lines?

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Those curly braces are java code for the boundaries of an array, and they are not String literals. You do not want to add them to your data. You could use an array of arrays, as you are doing in class, but this would require that you know in advance how many rows of data that your table will have. Most of the time this is not the case, and in these situations, Vectors would work much better.

    For more help, I think that you'll have to post your code (using code tags).

    Much luck.

  7. #7
    purple is offline Member
    Join Date
    Nov 2009
    Posts
    5
    Rep Power
    0

    Default

    Well here's what I've got so far:
    Java Code:
    class AddressBook2 extends JFrame
    {
        //String[][] addresses = {{"Hancock, Bob", "01202719029", "07676101393",
                               //"1 Charminster Road, Bournemouth, Dorset, BH8 8UE"}};
        DefaultTableModel contactsTable;
        JTable table;
        Vector<Object> vectors = new Vector<Object>();
    
        public AddressBook2() throws IOException
        {
            this.setSize(new Dimension(640, 480));
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setLayout(new GridBagLayout());
    
            BufferedReader fileIn = new BufferedReader(new FileReader("AddressBook.buab"));
            while (true)
            {
               String line = fileIn.readLine();
               if (line == null)
               break;
               vectors.add(line);
               //System.out.println(addresses2);
            }
            fileIn.close();
    Here's the bit for the table:
    Java Code:
     this.contactsTable = new DefaultTableModel (vectors,new String[] {"Surname", "First Name", "Home Phone Number", "Mobile number", "Address"});
            table = new JTable(this.contactsTable);

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You're just using one Vector here and that won't work. You actually need to have one Vector<String> that holds a row of data, say call it rowVector, and then a second Vector<Vector<String>>, say dataVector that holds all the rowVectors. A third Vector will hold the column names. For instance:

    Java Code:
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    
    @SuppressWarnings("serial")
    public class TableModelTest extends JPanel {
       public static final String FILE_PATH = "src/yr2009/m11/d/";
       public static final String FILE_NAME = "FuSwing2.txt";
       public static final String[] COLUMNS = {"Column 1", "Column 2", "Column 3", "Column 4"};
       
       private JTable table = new JTable();
       private DefaultTableModel model;
       
       public TableModelTest() {
          setLayout(new BorderLayout());
          add(new JScrollPane(table), BorderLayout.CENTER);
          
          Vector<String> colNames = new Vector<String>(Arrays.asList(COLUMNS));
          
          try {
             Scanner scanner = new Scanner(new File(FILE_PATH + FILE_NAME));
             int count = 0;
             Vector<Vector<String>> dataVector = new Vector<Vector<String>>();
             Vector<String> rowVector = new Vector<String>();
             while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                rowVector.add(line);
                count++;
                count %= COLUMNS.length;
                if (count == 0) {
                   dataVector.add(rowVector);
                   rowVector = new Vector<String>();
                }
             }
             model = new DefaultTableModel(dataVector, colNames);
             table.setModel(model);
             
          }
          catch (FileNotFoundException e) {
             e.printStackTrace();
          }
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("FuSwing2");
          frame.getContentPane().add(new TableModelTest());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }

  9. #9
    purple is offline Member
    Join Date
    Nov 2009
    Posts
    5
    Rep Power
    0

    Default

    Thank you!
    I wasn't sure how to get all the row vectors inside a bigger vector, if that makes sense??
    I do have a couple of questions about your code though -

    1. I understand that you set the count to 0 before reading in the lines, and it increases by one each time until it gets to 4 (the length of the columns string), but why do you have if (count == 0) , then it adds the rowvector to the datavector. Surely it should be when the count is equal to the column.length?
    or am i missing something?
    2. What does this symbol mean? %=

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    % is the mod operator and returns the remainder (if any) that is left after dividing by that number, and works like so:
    1 % 5 is 1
    2 % 5 is 2
    3 % 5 is 3
    4 % 5 is 4
    5 % 5 is 0
    6 % 5 is 1
    7 % 5 is 2
    8 % 5 is 3
    9 % 5 is 4
    10 % 5 is 0

    %= is the mod equivalent of += operator. So
    count %= 4
    is the same as
    count = count % 4

    if count is 4 then
    count %= 4 will change count to hold 0

  11. #11
    Alexis is offline Member
    Join Date
    Nov 2010
    Posts
    17
    Rep Power
    0

    Default

    Hello friends . I use the code above to my simple project . Can you tell me the changes to read a .txt file from inside .jar file ;;;;;;;

    Thanks

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Alexis View Post
    Hello friends . I use the code above to my simple project . Can you tell me the changes to read a .txt file from inside .jar file ;;;;;;;

    Thanks
    Please do not hijack another's thread with your question. If your question is truly important, ask it in its own thread.

    I am locking this old thread now.

Similar Threads

  1. Replies: 0
    Last Post: 11-24-2009, 02:49 PM
  2. Adding JButton to a JTable
    By ting.at.net@hotmail.com in forum AWT / Swing
    Replies: 6
    Last Post: 05-26-2009, 04:37 AM
  3. Replies: 2
    Last Post: 04-10-2009, 12:59 AM
  4. Replies: 6
    Last Post: 12-12-2008, 04:35 PM
  5. Adding information to a JTable in a JTabbedPane
    By bigpappatrader in forum AWT / Swing
    Replies: 0
    Last Post: 12-05-2007, 08:09 AM

Posting Permissions

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