简体   繁体   中英

Java Swing - Adding a row # column (row header) to a JTable

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 (ie 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

What TableModel are you using?

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

Ie

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)

If you want a row header that remains fixed in place when you do a horizontal scroll (like in Excel), then you could merge two JTables together. This component shows you how its done :

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

您可能正在寻找此页面: http : //www.chka.de/swing/table/row-headers/JTable.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM