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 Ass 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.

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.

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

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

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

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();
}

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

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...

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!

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", "Ass", "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);

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

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

my instructor said its possible with an ArrayList

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

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?

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.

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.

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]
}
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", "Ass", "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

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

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 = {""};

Your compiler should have told you that rosterList.size is an error. It should be rosterList.size();
You can delete all the data[][] stuff because your data is stored in the rosterList.
Beware of becoming dependent on step-by-step "is this OK?" posts. You won't learn so much or so well that way. Give it a try, see if it works, if it doesn't work try to see why, and only ask for help when you are stuck.
James

public Object getValueAt(int row, int col) 
{    return rosterList.at(row)[col]}

ok sorry, most of this stuff is new to me, so im learning as i go, and you have been a major help! thanks alot...
this part ive tried changing and i have no idea why its wrong?

says:

cannot find symbol - method at(int)

is it ment to be return rosterList.get(row)[col]}? that still comes up with an error though

Sorry - typing too fast! Yes it's get(int). Sorry. What's the error?
Your fragment shows )} at the end, which should be );}

public Object getValueAt(int row, int col) 
        {    
            return rosterList.get(row)[col];
        }

error = array required but java.lang.object found


i even tried:

((row)[col]); - still error

and tried removing [] around col.. still error

public Object getValueAt(int row, int col) 
        {    
            return rosterList.get(row);
            return col = columnNames.length;
        }

i used columnNames.length because thats a string array full of the column names i created earlier in the code. i think thats correct. now i get an error down below in the creatArr class

error says: non static variable rosterList cannot be reference from a static context

rivate static void creatArr() 
  {
     BufferedReader br = null;
     
     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();
    }
    
    
}

ok i think everything is ok, i could compile and run the app, the table shows up and the columns do but in every row it said:

[Ljava.lang.String;@408fbecf

when i compiled it successful i had removed col from getValueAt() class completely... but now i think it has to be there in order for the rows to show up properly...

the only problem is i keep getting unreachable statement error pointing at my for loop in getValueAt() class

note: anything that i put into getValueAt() which returns something to do with col gives me unreachable statement error

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;
    [B]static ArrayList rosterList = new ArrayList();   <-------- added static infront becuase got non static referencing error[/B]

    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", "Ass", "DP", "Inj", "Sus"};
        

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

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

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

      
        public Object getValueAt(int row, int col) 
        {    
            return rosterList.get(row);
            for(int i = 0; i < 28; i++) [B]<------- unreachable statement error[/B]
            {
                return col = i;
            }
        }

        
    }

   
    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() {
                creatArr();
                createAndShowGUI();
                
            }
        });
    }
    

private static void creatArr() 
  {
     BufferedReader br = null;
     
     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();
    }
    
    
}
    
  
    

}
public Object getValueAt(int row, int col) 
        {    
            return rosterList.get(row);
            for(int i = 0; i < 28; i++) <------- unreachable statement error
            {
                return col = i;
            }
        }

You said return rosterList.get(row) which causes whatever element is at rosterList.get(row) to be returned. When you return something, you are literally "returning" to wherever you were before (so if you called getValueAt from the main method, you'd return to main). In other words, the method you are in exits -- and since the method exits before you reach the for loop, it is giving you an unreachable statement error.

ahh i see... i changed it back to

public Object getValueAt(int row, int col) 
        {    
            return rosterList.get(row)[col];
                              
        }

but i still get an error: array required but java.lang.object found

You have a syntax error. Is rosterList an ArrayList? If so, look at the get method here. You'd have to use return rosterList.get(yourIndexHere);

If rosterList is a two dimensional array, then you would have to use return rosterList[row][column].

And the reason for your error is because when you put the brackets [], that means you are trying to get the index of an array. But there is no array there.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.