从JTable中排除列排序 [英] Exclude column from sorting in JTable

查看:119
本文介绍了从JTable中排除列排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Swing JTable和一个TableRowSorter.但是,我要从排序中排除第一列,因为我想保留它以显示行号. 我什么都看不到,除了

I have a simple Swing JTable and a TableRowSorter made by me. However, I would exclude the first column from the sorting, as I want to keep it to show row numbers. I can't see to find anything, except

sorter.setSortable(0, false);

这使该列不可单击,但在单击另一列时仍可排序... 如此简单的问题将是:如何防止TableRowSorter对列进行排序?

Which makes the column not clickable, but still sortable when another column is clicked... So quick question will be: how to keep a column from being sorter by a TableRowSorter?

谢谢!

推荐答案

因此,使用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.

这篇关于从JTable中排除列排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆