Hi!

I've spent 4 hours trying to read the data from file to ArrayList and then to JTable, but still cannot solve one problem.

I have the following class UserDataRow, where the data about a user is described.

public class UserDataRow {
    public String regnumber;
    public String firstname;
    public String lastname;
    public String profession;
    public String sex;
    public String dateofbirth;
    public int size;

    public UserDataRow(String rn, String fn, String ln, String p, String s, String dob) {
        this.regnumber = rn;
        this.firstname = fn;
        this.lastname = ln;
        this.profession = p;
        this.sex = s;
        this.dateofbirth = dob;
        this.size = 6;
    }
}

I'm using the following code to read the data from file:

public void readuserdatafromfile() throws IOException {
        try{
            FileInputStream fstream = new FileInputStream("src/filetree/UserDataFile.txt");
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine = "";
            String[] tokens = strLine.split(", ");
            //Read file line by line
            //int row = 0;
            UserDataRow p;
            while ((strLine = br.readLine()) != null)   {
              // Copy the content into the array
              tokens = strLine.split(", ");
              userdatarow.add(new UserDataRow(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6]));
              listofusers.add(userdatarow);
            }
            //Close the input stream
            in.close();
            } catch (Exception e){//Catch exception if any
              System.err.println("Error: " + e.getMessage());
            }
    }

Now I want just to put this 2d array "listofusers" into my JTable:

MyTableModel aModel = new MyTableModel(listofusers); // This constructor must add data to JTable, however I don't know how to implement it.

        filetree.Form.tableDetails.setModel(aModel);

As I understand, the problem is with MyTableModel:

class MyTableModel extends DefaultTableModel{
   private ArrayList<ArrayList<UserDataRow>> listofusers = null;
   public MyTableModel(ArrayList<ArrayList<UserDataRow>> listofusers){
    	this.listofusers=listofusers;
        setColumnIdentifiers(new String [] {"Reg.Nr.",
                          "Name",
                          "Surename",
                          "Profession",
                          "Sex",
                          "Date of Birth"});
   }

   @Override
    public Object getValueAt(int row, int column){
    	if(row>=listofusers.size()){
    		return null;
    	} else return listofusers;
    }
    
}

So, how could I implement "addAll" method or something like this in MyTableModel?
Pliz post any advises or links to good tutorials!

I've tried also the following:

Object d1[][] = (Object[][]) filetree.Form.listofusers.toArray();

        DefaultTableModel aModel = new DefaultTableModel(d1, new String [] {"Reg. Nr.",
                          "Name",
                          "Surename",
                          "Profession",
                          "Sex",
                          "Date of Birth"});

        filetree.Form.tableDetails.setModel(aModel);

...and got the following error:

Error: 6
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.Object;
        at filetree.FilterClass.initComponents(FilterClass.java:60)
        at filetree.FilterClass.<init>(FilterClass.java:42)
        at filetree.Form.createBaseRight(Form.java:139)
        at filetree.Form.createGUIforAdmin(Form.java:74)
        at filetree.Form.<init>(Form.java:64)
        at filetree.Form.main(Form.java:160)
Java Result: 1
BUILD SUCCESSFUL (total time: 4 seconds)

ava.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.Object;

The problem pointed out here is an object of one dim is being used where a two dim is required. Or visa versa. The [ and [[ in the message indicate one and two dimensions.
Look at the FilterClass line 60

Hmm. I've tried to change the code:

try {
           DefaultTableModel aModel = (DefaultTableModel)filetree.Form.tableDetails.getModel();
           Object d1[][]=(Object[][]) filetree.Form.listofusers.toArray();
           for (int i=0;i<d1.length;i++) {
               for (int j=0;j<d1[i].length;j++) {
                aModel.addRow(new Object[]{d1[i][j]});
               }
           }
        } catch (Exception e){
              System.err.println("Error: " + e.getMessage());
        }

But still have the errors:

Error: 6
Error: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.Object;

Yes, the problem is connected with the dimension. I see. But I cannot find the place in my code, where I'm using one-dimensional array. Don't understand where is the error.

So, in this last example I'm not using MyTableModel, as you may see. Instead of it, I use DefaultTableModel.

It would help if you posted the full text of the error message including the line number where the problem is.

Object d1[][]=(Object[][]) filetree.Form.listofusers.toArray();

How many dimension array does toArray() return?

I've got only these two lines of error message...nothing more.

well, I think that toArray() returns one dimension. However, how could I change it to two-dimensional case? I've tried to make it by: Object d1[][]=(Object[][]) filetree.Form.listofusers.toArray();

how could I change it to two-dimensional case?

You can't do it by casting.
You need code to extract elements from a one dim array and put them into a two dim array.
If the elements in the one dim array are: A, B, C, D
where do they go in the two dim array? Something like this:
[0][0] = A, [0][1] = B, [1][0] = C, [1][1] = D

Edited 6 Years Ago by NormR1: n/a

Now I'm using this code: Object d1[][] = filetree.Form.listofusers.toArray(new Object[0][]);

However, I still have one error message: Error: 6

What could I do to make my program working?

Sorry, I have no idea what "Error: 6" means?
Is it a compiler error or an execution error? Or is it from your IDE?

I checked that 6 refers to filetree.Form.userdatarow.size(). However, why does it bring to the error?

It is from NetBeans. I get this error after running my application. It is not the compiler error.

I get this error after running my application

Do you mean that the program runs to the end OK and exits and when control returns to the IDE, the IDE gives the error?

Well, I will change my question a little bit. Now I try using just 1-dimensional array. However, the size of "listofusers" is 0. It means that the data from a file is not added to this ArrayList. But why?

public void readuserdatafromfile() throws IOException {
        try{
            FileInputStream fstream = new FileInputStream("src/filetree/UserDataFile.txt");
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine = "";
            String[] tokens = strLine.split(", ");
            while ((strLine = br.readLine()) != null)   {
              // Copy the content into the array
              tokens = strLine.split(", ");
              listofusers.add(new UserDataRow(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6]));
            }
            //Close the input stream
            in.close();
            } catch (Exception e){//Catch exception if any
              System.err.println("Error: " + listofusers.size());
            }
    }

But why?

Try debugging your program to show what is happening.
Add println()s every place something is added to listofusers to show the size of the list after it has been added.
Add println() before and after every place listofusers is referenced and used by a method to show its size.
If you are adding items to the list, the size should increase. If at some point, the size goes to zero, track back thru your code to see why.

This article has been dead for over six months. Start a new discussion instead.