Java 禁用 JTable 上的列标题排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20903136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Disable Column Header sorting on a JTable
提问by maloney
Is it possible to disable manual sorting on a JTable after adding a sorter? So I have a JTable that has the following sorter attached to it (basically sorts by column 3 when the table is initialised):
添加排序器后是否可以在 JTable 上禁用手动排序?所以我有一个 JTable,它附加了以下排序器(在初始化表时基本上按第 3 列排序):
JTable jTable = new JTable();
RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(jTable.getModel());
List<RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>();
sortKeys.add(new RowSorter.SortKey(3, SortOrder.DESCENDING));
sorter.setSortKeys(sortKeys);
jTable.setRowSorter(sorter);
This works fine, however the user is still able to click on the column headers in the table and sort by any of the columns, which I want to disable. Is this possible?
这工作正常,但是用户仍然可以单击表中的列标题并按我想禁用的任何列进行排序。这可能吗?
采纳答案by Rahul
You can use the setSortablemethod of TableRowSorteras below:
您可以使用TableRowSorter的setSortable方法,如下所示:
sorter.setSortable(0, false);
to make column 0 non-sortable. You can apply it on the column according to your requirement.
使第 0 列不可排序。您可以根据您的要求将其应用在色谱柱上。
回答by mostar
Alternatively, you can set your sortable and non-sortable columns like this:
或者,您可以像这样设置可排序和不可排序的列:
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel()) {
@Override
public boolean isSortable(int column) {
if(column < 2)
return true;
else
return false;
};
};
table.setRowSorter(sorter);
回答by Sandip Ghosh
I ran into the same problem recently, and found the perfect solution to this problem. The TableHeader
can simply be disabled.
我最近遇到了同样的问题,并找到了这个问题的完美解决方案。该TableHeader
可以简单地禁用。
jTable.getTableHeader().setEnabled(false);
This way, the sorterworks perfectly on any of the columns, but manual sortingis prevented by click on the Column Headers.
这样,排序器可以在任何列上完美运行,但通过单击列标题可以防止手动排序。
Hope this helps the future users who might want to have a look at it.
希望这可以帮助可能想要查看它的未来用户。