2

I'm working on a java desktop application and I have a Swing JTable for displaying data. I need to have a column for displaying row index for each row in the table. I don't want to add index in the grid data. Here is the way that I'm using to fill my table:

private DefaultTableModel defaultTableModel = new DefaultTableModel();
defaultTableModel.setDataVector(dataArray, headerArray);
jTable.setModel(defaultTableModel);
hamed
  • 7,939
  • 15
  • 60
  • 114

2 Answers2

2

JTable displays what the TableModel tells it to display. Instead, extend AbstractTableModel. In your implementation of getValueAt(), return the row number for column zero and return the appropriate element of dataArray otherwise. Related examples may be found here and here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2

You can add a row header to the scroll pane to display numbers for each row in the table.

Any component can be added to the row header. So one solution is to add a second (custom) JTable that just displays row numbers with a custom renderer so that the number look like the column headers.

Check out Row Table Number for an example of this approach.

camickr
  • 321,443
  • 19
  • 166
  • 288