Java Tips Weblog

Row Number Table

Posted by Rob Camick on November 18, 2008

Sometimes you may have a requirement for your table to look like a spreadsheet. That is you want column headings on the top and row numbers along the side. Well, a JTable has a default API to show a column header. It does this by adding the JTableHeader component to the column header area of a JScrollPane. Although there is no component in the API to display row numbers, the scroll pane also supports a row header area for a row header component. So all we need to do is create a row header component and the problem is solved.

The RowNumberTable is such a component. It is a simple extension of JTable that shares properties of the main table along with the TableModel and SelectionModel of the main table. Although it shares the TableModel it does not actually use any of the data in the model, it just needs to be notified when rows are added or removed so it can paint itself correctly.

You can use the RowNumberTable in your program with code like the following…

JTable mainTable = new JTable(...);
JScrollPane scrollPane = new JScrollPane(mainTable);
JTable rowTable = new RowNumberTable(mainTable);
scrollPane.setRowHeaderView(rowTable);
scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER,
    rowTable.getTableHeader());

which will generate a table looking something like…

row-number-table

Get The Code

RowNumberTable.java

Related Reading

Using a Scroll Pane: Providing Custom Decorations

3 Responses to “Row Number Table”

  1. Jan Zitniak said

    We used your RowNumberTable.java solution. In the following case when we used first column of table as Boolean Type we got error:

    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
    at javax.swing.JTable$BooleanRenderer.getTableCellRendererComponent(JTable.java:5406)
    at javax.swing.JTable.prepareRenderer(JTable.java:5729)
    ...

    Thank you for any help.

  2. Rob Camick said

    Thanks for the feedback.

    RowNumberTable code has been modified to make sure the included RowNumberRenderer is used to render the row numbers. The renderer is now attached directly to the TableColumn.

  3. Jan Zitniak said

    Thank you, now it works ok.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>