• Post Reply Bookmark Topic Watch Topic
  • New Topic

spent three hour already, please help on table model issue!

 
marshal ma
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am new to java, need help! I have a table in a GUI, in default I just want it show column names and no rows, but after I press some button on GUI I get some data , but I don't know how to add data to table and make them show in rows. part of the code is like the following :

class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"First Name",
"Last Name",
"Sport",
"Years",
"Vegetarian"};

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 data[row][col];
}

After I got data {"Mary", "Campione","Snowboarding", "1995", "tomato")} , I tried to write the following code (in the same class with the above) but data didn't show on table (or give me error saying ArrayIndexOutOfBoundsException on line "return data [row][col] ", can anyone help to tell me how to add data to table? Thanks a lot!!

public void addValue(String a, String b, String c, String d, String e ) {
Object [][] data = { {a, b, c, d, e } };
this.getColumnCount( );
this.getColumnName(0);
this.getRowCount();
this.getValueAt(0,0);
}

}
 
Stefan Krompass
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

your code could look something like this:


The probleme with this solution is that you can only store one entry in the table. The old entry is deleted each time you call the addValue-method. But it should be no problem to adapt the code so that more rows are possible...

cu

Stefan
 
marshal ma
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Stefan !

I tried but it didn't work, I think there is something wrong in other parts of my program. I used DefaultTableModel finally.

Good luck !

marshal
 
Cathy Song
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
private Object[][] data = { null, null, null, null};

If you have n column names put in "n" nulls in the data [][] array.
Let me know how that works.

Cathy.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!