I am facing an issue with JTable and the TableModel associated with it. The problem here is that let's say if I make a row/rows selections on my JTable, I would like to get the particular row object from the TableModel and pass it somewhere. Does anyone know how to do this efficiently?
Asked
Active
Viewed 365 times
2 Answers
1
Assuming you have a custom TableModel, you can do this:
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (rowIndex >= items.size()) {
return null;
}
Object obj = items.get(rowIndex);
if (obj == null) {
return null;
}
switch (columnIndex){
case -1:
return obj;
case 0: ...
(Assuming that items
is the List where you store your objects)
... and then when you need the object at a given row, just take it by calling tableModel.getValueAt(row, -1);

Gilberto Torrezan
- 5,113
- 4
- 31
- 50
1
I have done a similar application. In my task I have to get the data (row/rows) from one table and drag it to another table. i.e, if a user select row/rows from one table he should be able to drag to another table.
When an user selects a row use tableA.getSelectedRow(). Now loop over to get all the columns for each selected row. Store each row in a String and use new line character as an end to a row. While importing parse through the string and get each row.
// Sample code that I have worked on.
protected String exportString(JComponent c) {
JTable table = (JTable) c;
rows = table.getSelectedRows();
int colCount = table.getColumnCount();
StringBuffer buff = new StringBuffer();
for (int i = 0; i < rows.length; i++) {
for (int j = 0; j < colCount; j++) {
Object val = table.getValueAt(rows[i], j);
if (j != colCount - 1) {
buff.append(",");
}
}
if (i != rows.length - 1) {
buff.append("\n");
}
}
System.out.println("Export Success");
return buff.toString();
}
Hope this may help you.

Amarnath
- 8,736
- 10
- 54
- 81
-
I understand what you are saying but the problem here is that I need to interact with the table model. – Bytekoder Sep 13 '12 at 03:54
-
Can you explain what is interaction here? – Amarnath Sep 13 '12 at 04:07
-
Well, if I need to make selection on a table, I have to do that in a JTable but at the same time I need to refer that selection in my table model as well. In this it will be a row selection at multiple intervals. So for example, when I select rows 2, 3, 4... I need the objects from my table model that has data pertaining to those selected rows. Hope this explains. – Bytekoder Sep 13 '12 at 04:18
-
Please have a look http://stackoverflow.com/questions/856888/getting-selected-row-through-abstracttablemodel – Amarnath Sep 13 '12 at 04:28