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 开发者_StackOverflowcolumn) 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
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)
This page might be what you're looking for: http://www.chka.de/swing/table/row-headers/JTable.html
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/
精彩评论