How can I assign an id to each row of jTable?
I don't want user be able to see it.
3 Answers
A quick hack is just to use a hidden column. A better method may be to write a custom table model that doesn't even expose said data to the JTable, but that is more involved :-)
Happy coding.

- 1
- 1
You should implement your own table model by creating a class that implements TableModel, or perhaps more easily create a class that extends AbstractTableModel.
If you do that then, you only need to implement
class MyModel extends AbstractTableModel {
public Object getValueAt(int rowIndex, int columnIndex) {
// return what value is appropriate
return null;
}
public int getColumnCount() {
// return however many columns you want
return 1;
}
public int getRowCount() {
// return however many rows you want
return 1;
}
}
typically you would create a List in the class of object of your choosing, and getRowCount would just be how big the list was.
getValueAt would return values from the Object in the list.
for instance If i wanted a table of users with a hidden id, it would be
class UserModel extends AbstractTableModel {
private List<User> users = new ArrayList<User>();
public Object getValueAt(int rowIndex, int columnIndex) {
User user = users.get(rowIndex);
if (columnIndex == 0)
return user.getName();
else
return user.getAge(); //whatever
}
public int getColumnCount() {
return 2;
}
public int getRowCount() {
return users.size();
}
}
class User {
private int userId; // hidden from the table
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
}

- 28,272
- 7
- 61
- 66
rowData is just an Object array, so in your class that represents a row model have an member variable for id which won't be included in toString().

- 6,198
- 4
- 28
- 36