且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从JTable中排除列排序

更新时间:2023-12-04 19:00:04

因此,使用JTable(例如下面)对A列进行排序将产生以下结果.但是,您要对数据进行排序,而不对行号进行排序,对吗?

So, with a JTable (ex below) sorting on column A would produce the following. However, you want the data to sort, but not the row numbers, correct?

|row| column A  |       |row| column A  |
+---+-----------+       +---+-----------+
| 1 | blah blah |  -->  | 1 | blah blah |
| 2 | something |       | 3 | more blah |
| 3 | more blah |       | 2 | something |

我会使用 TableCellRenderer 表示第0列.窍门是忽略传递的值,而使用row参数.

I would approach this with a TableCellRenderer for column 0. The trick is to ignore the value passed and instead use the row parameter.

public class RowRenderer extends JLabel implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object color,
        boolean isSelected, boolean hasFocus, int row, int column) {
        setText(Integer.toString(row));
        return this;
    }
}

注意:如果您要对表格进行分页(即模型不包含所有行;例如仅行100-200),则需要告知单元格渲染器添加到row以获得要显示的行号.

Note: if you are paginating your table (ie the model does not contain all of the rows; for example only rows 100-200) you will need to advise the cell renderer of the amount to add to row to obtain the row number to display.