我有一个用于过滤JTable中的数据(多个或没有)的方法,这是代码:

public void filter() {
    if(Main.is_loading)
        return;
    RowFilter<Object, Object> serviceFilter = null;
    if (!multiple) {
        String filterText = tfield.getText();
        if (filterText.length() > 2)
            serviceFilter = RowFilter.regexFilter("(?iu)" + filterText);
    } else {
        List<RowFilter<Object, Object>> filters = new ArrayList<RowFilter<Object, Object>>(2);
        for (int i = 0; i < tfields.size(); i++) {
            String filterText = "";
            JTextField cur = tfields.get(i);
            filterText = cur.getText();
            if (cur.getText().length() > 2) {
                filters.add(RowFilter.regexFilter("(?iu)" + filterText, i));
            }
        }
        serviceFilter = RowFilter.andFilter(filters);
    }
    sorter.setRowFilter(serviceFilter);
    table.setRowSorter(sorter);
}


如何更改找到的符号的颜色?我需要标记匹配的符号。

最佳答案

首先过滤表模型以查找匹配的单元格。然后,对于所有匹配的单元格,强制重新绘制单元格视图(如果使用了AbstractTableModel调用fireTableCellUpdated(int,int))。另外,您还需要改进单元格渲染器。当您使用文本过滤器和单元格文本匹配时,只需显示具有其他颜色的匹配文本即可。

class Renderer extends DefaultTableCellRenderer {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        if (isFilterUsed() && isCellMatched(row, column)) {
            String stringValue = value.toString();
            String filter = getFilterValue();
            int start = stringValue.indexOf(filter);
            int end = start + filter.length();
            String result = String.format("<html>%s<font color='red'>%s</font>%s</html>",
                    stringValue.substring(0, start),
                    stringValue.substring(start, end),
                    stringValue.substring(end));

            return super.getTableCellRendererComponent(table, result, isSelected, hasFocus, row, column);
        } else {
            return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        }
    }
}

09-08 06:36