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?
2 Answers
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);
Comments
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.