1,105,169 Community Members

reading .txt files to put into JTable

Member Avatar
bokz06
Junior Poster in Training
67 posts since Apr 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

i have a mydata.txt file with this in it:

B.Friedel     38 LRC usa 20  1  1  1 21 410 300 300 300  18   0 1673   0  76  26   0   0   0   0   0   0   0   0
M.Fulop       26 LRC hun 17  1  1  1 26 308 300 300 300   1   1   16   0   1   0   0   0   0   0   0   0   0   0
B.Guzan       25 LRC usa 15  1  1  1 23 300 300 300 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0
M.Laursen     32   C den  1 24  6 12 25 300 493 409 373  17   0 1619   0   0   0  17   7  15   2   0  14   0   0
C.Davies      24   C eng  1 23  9  6 25 300 302 430 304  15   0 1457   0   0   0   8   9   6   0   0   4   0   0
C.Cuellar     28  RC esp  1 23 12  8 24 300 302 412 320  14   1 1273   0   0   0  10  10  13   0   0   8   0   0
L.Young       30  RC eng  1 23 10  6 22 280 328 435 316  11   1 1006   0   0   2  14   9   5   0   0   0   0   0
N.Shorey      28   L eng  1 23  8  4 22 300 312 353 312  14   0 1367   0   0   0  10   2   7   0   1   8   0   0
W.Bouma       31   L ned  1 22 14 12 23 300 504 358 301   4   0  378   0   0   0   4   6   3   0   0   8   0   0
J.Collison    21  RC wal  1  9 21  9 21 300 296 754 320   9   0  771   0   0   0   1  15  11   0   1   0   0   0

i need to read this text file, and put the information into a JTable so that then i can sort the information alphabetically.

JTable needs to have these columns: Name Age Prs Nat St Tk Ps Sh Ag KAb TAb PAb SAb Gam Sub Min Mom Sav Con Ktk Kps Sht Gls ### DP Inj Sus under neath these columns i need the information from the .txt file to fall under its right catgory.
i was told i need to read the text line by line, put it into an arraylist and then split the lines up at every " " <-- space and put that into a JTable

my code so far:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;


public class rosterSorter
{
public static void main() 
  {
     BufferedReader br = null;
     ArrayList rosterList = new ArrayList();
     
     try
    {
      br = new BufferedReader(new FileReader("mydata.txt"));
      String line = br.readLine();
      String [] rowfields = line.split(" ");  
      while (line != null )
      {
        rosterList.add(line);
        line = br.readLine();
       
      }
      
    }
    catch (FileNotFoundException e)
    {
      // can be thrown when creating the FileReader/BufferedReader
      // deal with the exception
      e.printStackTrace();
    }
    catch (IOException e)
    {
      // can be thrown by br.readLine()
      // deal with the exception
      e.printStackTrace();
    }
    show(rosterList);
    
}
    public static void show(ArrayList rosterList){
        
    for (int i = 0; i < rosterList.size(); i++)
    {
        System.out.println(rosterList.get(i));
    }
}
  
    
}

the method show is only used for my testing to see if it works, the program outputs the original .txt to the terminal but not the split one, how would i split it and get to output the split up text to the terminal?
thanks in advance.

Member Avatar
JamesCherrill
... trying to help
10,362 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,749 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
0
 

You split the line into the String array rowFields, but then you do nothing with it. Perhaps you should loop thru the members of that array printing them, or storing them somewhere.

Member Avatar
bokz06
Junior Poster in Training
67 posts since Apr 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

ok that helps :D... but my .split only splits the first Line in the text and the rest is displayed as normal..

just after the while loop i added:

for (int i = 0; i < rowfields.length; i++)
    {
        System.out.println(rowfields[i]);
    }
Member Avatar
JamesCherrill
... trying to help
10,362 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,749 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
0
 

Of course it does. If it was inside the first loop it would print the split version of every line.
ps: the "enhanced for loop" syntax is easier and less error-prone:
for (String s : rowfields) {
System.out.println(s);
}

Member Avatar
bokz06
Junior Poster in Training
67 posts since Apr 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

i put rowfields inside the first loop and now it wont let me do the second loop... says variable rowfields may not have been initialized

Member Avatar
JamesCherrill
... trying to help
10,362 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,749 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
0
 
br = new BufferedReader(new FileReader("mydata.txt"));
String line = br.readLine();
while (line != null ) {
    rosterList.add(line);
    String [] rowfields = line.split(" ");  
    for (String s : rowfields) {
          System.out.println(s);
    } 
    line = br.readLine();
}
Member Avatar
bokz06
Junior Poster in Training
67 posts since Apr 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

ok that works but it only prints: is that just a limitation of the terminal to not show above a certain amount of lines or is there something wrong?

12
23
300
504
358
301
4
0
378
0
0
0
4
6
3
0
0
8
0
0
J.Collison
21
RC
wal
1
9
21
9
21
300
296
754
320
9
0
771
0
0
0
1
15
11
0
1
0
0
0
Member Avatar
JamesCherrill
... trying to help
10,362 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,749 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
0
 

You may want to do some more clever formatting of your output - the simple code you have now just proves that it works, even if it does overflow your console window. the print(...) method is just like the println(...) method, except that it does not put a new line character after every print. This will enable you to print multiple items on one line and thus see more clearly what's going on...

Member Avatar
bokz06
Junior Poster in Training
67 posts since Apr 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

ah yeh i see... well all i really wanted with the println is just too see that it works.. now i need to display the split up code in a JTable.. any pointers as to how i would go about that?

thanks for helping btw, legend!

Member Avatar
bokz06
Junior Poster in Training
67 posts since Apr 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

this is what i got for the JTable... am i on the right track?

public class rosterCreate extends JFrame {
  public rosterCreate() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    String[] columns = { "Name", "Age", "Pos", "Nat", "St", "Tk", "Ps", "Sh", "Ag", "Kab", "Tab", "Pab", "Sab", "Gam", "Sub", "Min", "Mom", "Sav", "Con", "Ktk", "Kps", "Sht", "Gls", "###", "DP", "Inj", "Sus"};
        Object[][] rows = { {  } };


    TableModel model = new DefaultTableModel(rows, columns) {
      public Class getColumnClass(int column) {
        if (column >= 0 && column <= getColumnCount())
          return getValueAt(0, column).getClass();
        else
          return Object.class;
      }
    };
    JTable table = new JTable(model);
    RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    table.setRowSorter(sorter);
    getContentPane().add(new JScrollPane(table));

    setSize(200, 150);
    setVisible(true);
Member Avatar
naugiedoggie
Newbie Poster
12 posts since Apr 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

i have a mydata.txt file with this in it:

i need to read this text file, and put the information into a JTable so that then i can sort the information alphabetically.

i was told i need to read the text line by line, put it into an arraylist and then split the lines up at every " " <-- space and put that into a JTable

the method show is only used for my testing to see if it works, the program outputs the original .txt to the terminal but not the split one, how would i split it and get to output the split up text to the terminal?
thanks in advance.

Hello,

This seems to me to be going in the wrong direction. There are no constructors for JTable that use an ArrayList. To build a JTable, you should put your data into a Vector. The recommended procedure would be to create a TableModel based on a Vector and then create the JTable based on the TableModel.

This is pretty basic Swing programming and you can see how to do it in the Java Swing Tutorial section on JTable. The tutorial includes a section on implementing sorts, as well.

I know the Sun tutorial isn't always the easiest to follow, but once you have your data into the Vector, you are 75% of the way to having your table.

Thanks.

mp

Member Avatar
bokz06
Junior Poster in Training
67 posts since Apr 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

an ArrayList can be created into a 2D arraylist which the JTable accepts??

my instructor said its possible with an ArrayList

Member Avatar
JamesCherrill
... trying to help
10,362 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,749 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
0
 

ArrayList and Vector are interchangeable as far as this app is concerned; the subtle differences between them aren't relevant here.

Member Avatar
bokz06
Junior Poster in Training
67 posts since Apr 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import java.awt.Dimension;
import java.awt.GridLayout;

/** 
 * TableDemo is just like SimpleTableDemo, except that it
 * uses a custom TableModel.
 */
public class TableDemo extends JPanel {
    private boolean DEBUG = false;

    public TableDemo() {
        super(new GridLayout(1,0));

        JTable table = new JTable(new MyTableModel());
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this panel.
        add(scrollPane);
    }

    class MyTableModel extends AbstractTableModel {
        private String[] columnNames = {"First Name",
                                        "Last Name",
                                        "Sport",
                                        "# of Years",
                                        "Vegetarian"};
        private Object[][] data = {
            {"Mary", "Campione","Snowboarding", new Integer(5), new Boolean(false)},
            {"Alison", "Huml","Rowing", new Integer(3), new Boolean(true)},
            {"Kathy", "Walrath","Knitting", new Integer(2), new Boolean(false)},
            {"Sharon", "Zakhour","Speed reading", new Integer(20), new Boolean(true)},
            {"Philip", "Milne","Pool", new Integer(10), new Boolean(false)},
        };

        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];
        }

        /*
         * JTable uses this method to determine the default renderer/
         * editor for each cell.  If we didn't implement this method,
         * then the last column would contain text ("true"/"false"),
         * rather than a check box.
         */
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("TableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        TableDemo newContentPane = new TableDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

would it be as simple as putting my arraylist in some sort of loop around the Object [][] = " " part of the code?

Member Avatar
JamesCherrill
... trying to help
10,362 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,749 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
0
 

The missing step here is that you have stored your data as a 1-dimensional list, whereas it really needs to be stored in some kind of 2D structure to fit int0 a table (original lines as the rows, with the split elements as the columns). You could use an ArrayList of String arrays, or an ArrayList of ArrayLists, or various other solutions.

Member Avatar
bokz06
Junior Poster in Training
67 posts since Apr 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

ahh i give up... this is too difficult for me, i just can't find any examples of it done before where it actually makes sense to me...

thanks for your help though.

Member Avatar
JamesCherrill
... trying to help
10,362 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,749 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
0
 

Don't give up - you're almost there!
Suppose, when you read the data file, you store the rowfields array into rosterList instead of line. Then your getValueAt method can be

public Object getValueAt(int row, int col) {
    return rosterList.at(row)[col]
}
Member Avatar
bokz06
Junior Poster in Training
67 posts since Apr 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.*;
import java.util.*;


public class TableDemo extends JPanel {
    private boolean DEBUG = false;

    public TableDemo() {
        super(new GridLayout(1,0));

        JTable table = new JTable(new MyTableModel());
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this panel.
        add(scrollPane);
    }

    class MyTableModel extends AbstractTableModel {
        private String[] columnNames = { "Name", "Age", "Pos", "Nat", "St", "Tk", "Ps", "Sh", "Ag", "Kab", "Tab", "Pab", "Sab", "Gam", "Sub", "Min", "Mom", "Sav", "Con", "Ktk", "Kps", "Sht", "Gls", "###", "DP", "Inj", "Sus"};
        private Object[][] data = {""};

        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 rosterList.at(row)[col];
        }

        
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("TableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        TableDemo newContentPane = new TableDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    

public static void creatArr() 
  {
     BufferedReader br = null;
     ArrayList rosterList = new ArrayList();
     try
    {
      br = new BufferedReader(new FileReader("mydata.txt"));
      String line = br.readLine();
        
      while (line != null )
      {
        String [] rowfields = line.split("[ ]+");
        rosterList.add(rowfields);
        line = br.readLine();
       }
     
    }
    catch (FileNotFoundException e)
    {
      // can be thrown when creating the FileReader/BufferedReader
      // deal with the exception
      e.printStackTrace();
    }
    catch (IOException e)
    {
      // can be thrown by br.readLine()
      // deal with the exception
      e.printStackTrace();
    }
    
    
}
    
  
    

}

this is what i have so far... i did what you said and now it says cannot find variable rosterList

Member Avatar
JamesCherrill
... trying to help
10,362 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,749 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
0
 

Yeah, you declare it in the creatArr method, so it's limited to that method. If you move its declaration to outside the method (ie just in the class) it will be available to all the methods.
ps Don't forget to call creatArr before you try to display the data or there won't be anything to display.
pps getRowCount() needs to return the number of rows (String arrays) in rosterList

Member Avatar
bokz06
Junior Poster in Training
67 posts since Apr 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 
public int getRowCount() {
            return rosterList.size;
        }

is that better?

public class TableDemo extends JPanel {
    private boolean DEBUG = false;
    ArrayList rosterList = new ArrayList();

defined it at the beginning of the class

now i have no clue what to put in: private Object[][] data = {""};

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article