tags:

views:

311

answers:

2

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

Any idea how to do this?

Thanks

+1  A: 

What TableModel are you using?

You can override public Object getValueAt(int row, int column) to do this in your TableModel.

I.e.

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

If that isn't working when you sort your JTable, then another solution is to implement it in a custom TableCellRenderer and override:

Component getTableCellRendererComponent(JTable table,
                                        Object value,
                                        boolean isSelected,
                                        boolean hasFocus,
                                        int row,
                                        int column)
Jonas
Yes, I am extending AbstractTableModel. But I am not sure how to do this because the table can have an arbitrary number of rows, so I can't explicitly provide the row headers (i.e. '1', '2','3'...), I need it to automatically add the header
llm
Oh yea, good call - I didn't think to treat it like a regular column. Any idea how to get this column grayed out so that it stands apart from the "regular" table data?
llm
@llm: Yes, you can change the color using a custom CellRenderer. Have a look at http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#renderer
Jonas
Use a special TableCellRenderer on the first column to alter the appearance (border, color, fill, etc). Extend DefaultTableCellRenderer.
basszero
A: 

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

Gili