Row Number Column in JTable

Ever wanted to have a number column in your JTable similar to Excel?

This utility class I made takes in a JTable and appends a number column.

Let’s take a look at it!

The rendering of the number column matches the rendering of the headers :


As you scroll horizontally, the row column remains fixed in place :


Highlighting of rows also incorporates the number column :




As the numbers increase, the width of the column needs to be changed. This happens automatically and also shrinks when the numbers get smaller :


How does this work?

The row column is really just a JTable with a single column. This table is then lined up next to the main table making sure that all metrics match, so that it appears to just be another column in the JTable. A simple table model is required which is just an numerical incrementation, and listeners need to be set up to link the two tables. When the vertical scrollbar is moved, the numerical table listens and changes its position respectively. When a horiyontal scroll happens then the numerical table ignores it.

All the code can be found on my github repository

Or you can just copy and paste the code below :


Posted in Swing, Swing Components | Tagged , , | 2 Comments

2 Responses to Row Number Column in JTable

  1. Scott Polk says:

    I am seeing an issue where the row number labels do not change background colors until after the first time you click on any row number in the row header table. I tested this on both Windows (Windows 7) and Mac (Snow Leopard) using Java 6 (not sure if that matters for this). So, the scenario is, the JTable loads, click a cell/row in the user table. Row header does not show selected. Click a row header. The row header and row in the user table all show selected. Click on a cell/row in the user table again, and the appropriate row header shows selected. Any suggestions to fix this?

    Also, on Mac, the table header color is white and the gridlines are white (at least in the Aqua L&F, so I made a slight change in my code to set the gridline colors to black and the label background color to light gray if System.getProperty(“”).toLowerCase().contains(“mac”). I’ve already verified that this change did not cause the issue above.

    Other than those small issues, great work! It is just what I was looking for.

  2. Salinda Dahanayake says:

    Just Use DefaultTableModel and Vector,

    DefaultTableModel df = (DefaultTableModel) jTable1.getModel();
    Vector vec = new Vector();
    int ln = df.getRowCount();

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">