Java Swing - adding row column # (row header) to JTable

I have data from a database loaded into a JTable via a custom table model. I want to have a column (must be the first column) that just shows the display row number (i.e. it is not tied to any data (or sort), but just the row number on the screen, starting at 1). These "line headers" should be grayed out like line headers.

Any idea how to do this?

thanks

+2


a source to share


3 answers


Which TableModel are you using?

You can override public Object getValueAt(int row, int column)

this in your TableModel.

those.



public Object getValueAt(int row, int column) {
    if(column == 1) {
        return row; 
    } ...
}

      

If that doesn't work when sorting the JTable, another solution is to implement it in a custom one TableCellRenderer

and override:

Component getTableCellRendererComponent(JTable table,
                                        Object value,
                                        boolean isSelected,
                                        boolean hasFocus,
                                        int row,
                                        int column)

      

+1


a source


This page might be what you are looking for: http://www.chka.de/swing/table/row-headers/JTable.html



0


a source


If you want the row header to remain fixed when you do horizontal scrolling (in Excel for example), you can combine the two JTables together. This component shows you how to do it:

http://blue-walrus.com/2014/12/row-number-column-in-jtable/

0


a source







All Articles