0

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 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

I understand what you are saying but the problem here is that I need to interact with the table model.
Can you explain what is interaction here?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.