Suleiman Dibirov
Suleiman Dibirov

Reputation: 1023

How to colorize found symbols in JTable?

I have a method for filter (multiple or not) data in JTable, here is the code:

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);
}

How do I change the color of found symbols? I need to mark matched symbols.

Upvotes: 0

Views: 85

Answers (1)

Sergii Lagutin
Sergii Lagutin

Reputation: 10671

First filter your table model to find matched cells. Then for all matched cells force repaint cell view (if you used AbstractTableModel call fireTableCellUpdated(int,int)). Also you need improve your cell renderer. When you use text filter and cell text matched, just display matched text with other color.

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);
        }
    }
}

Upvotes: 2

Related Questions