JTable按指定列排序后自定义着色单元格位置未同步变更问题求助
问题原因
一共有3处核心错误导致排序后着色错位、排序配置不生效:
- 重复实例化
JTable:第一次实例化配置的TableRowSorter排序规则,被后续第二次实例化的带自定义渲染逻辑的JTable完全覆盖,最终显示的表格没有绑定排序器。 - 视图行与模型行索引混淆:
prepareRenderer方法传入的row参数是视图层的行索引,排序后视图行顺序和底层TableModel的存储行顺序不一致,直接用row访问模型会拿到错误位置的数据。 - 滚动面板嵌套错误:代码中错误将带表格的滚动面板又套了一层滚动面板,还写了多余的
JPanel添加逻辑,可能导致布局异常。
修复方案
核心修改点
- 只实例化一次自定义
JTable,排序逻辑绑定到最终显示的表格实例上 - 调用
convertRowIndexToModel()方法将视图行索引转为模型行索引后,再访问TableModel取值 - 修正滚动面板和窗口布局逻辑
修复后代码
// 仅实例化一次自定义JTable secondary_table = new JTable(table_model){ @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int col) { Component comp = super.prepareRenderer(renderer, row, col); // 视图行转模型行,解决排序后索引不对应的问题 int modelRow = convertRowIndexToModel(row); Object value = getModel().getValueAt(modelRow, col); if (value.equals("غائب")) { comp.setBackground(Color.red); comp.setForeground(Color.white); } else if (value.equals("دوام كامل")) { comp.setBackground(Color.green); comp.setForeground(Color.black); } else if (value.equals("دوام جزئي دخول فقط") || value.equals("دوام جزئي خروج فقط") ) { comp.setBackground(Color.yellow); comp.setForeground(Color.black); } else { comp.setBackground(Color.white); comp.setForeground(Color.black); } return comp; } }; // 给最终显示的表格绑定排序器 TableRowSorter<TableModel> sorter = new TableRowSorter<>(secondary_table.getModel()); secondary_table.setRowSorter(sorter); ArrayList<RowSorter.SortKey> sortKeys = new ArrayList<>(); int columnIndexToSort = 3; sortKeys.add(new RowSorter.SortKey(columnIndexToSort, SortOrder.ASCENDING)); sorter.setSortKeys(sortKeys); sorter.sort(); // 修正窗口布局逻辑 JFrame frame1 = new JFrame(employee_name); frame1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); // 直接把表格放到滚动面板中,不要重复嵌套 frame1.getContentPane().add(new JScrollPane(secondary_table), "Center"); frame1.pack(); frame1.setVisible(true);
内容的提问来源于stack exchange,提问作者ali shakarchi
相关产品推荐
相关产品推荐

