0

I have a JTable and i have a method which implements search in table rows and columns, i use regular expressions and i want to paint(eg yellow) the text which matches with the regular expression in the cell. I want to paint the text not the background of the cell and only the part of word which matches with reg expression. The code for my search method is:

        for (int row = 0; row <= table.getRowCount() - 1; row++) {

            for (int col = 0; col <= table.getColumnCount() - 1; col++) {

                Pattern p = Pattern.compile("(?i)" + search_txt.getText().trim());
                Matcher m = p.matcher(table.getValueAt(row, col).toString().trim());
                if (m.find()){

                    isFound = true;

                    table.scrollRectToVisible(table.getCellRect(row, 0, true));

                    table.setRowSelectionInterval(row, row);
                    break;
                                }
                }
            }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
user1005633
  • 625
  • 3
  • 9
  • 23

1 Answers1

2

You will need a custom renderer to do this.

The default renderer is a JLabel. So the only way to do this would to wrap HTML around your text string and change the font color of the text you are searching for. You would need to pass the search text to the renderer so the renderer can determine which text to highlight.

The code you posted has a problem in that it will always scroll to the bottom of the table. So what is your exact requirement. Do you want to highlight all cells at one time. Or do you just want to have a "Next" button that will find the next cell with the text. In the first case you would not want to automatically scroll the table. In the second case you would scroll the table.

Also, depending on the requirement you would need to either repaint the entire table (if you show all occurrences at once) or only the current row (if you have next functionality).

Edit:

Normally when you add text to a label you use:

label.setText("user1005633");

If you want to highlight any text containing "100" then you would need to do:

label.setText("<html>user<font color="yellow">100</font>5633</html>");

This is what I mean by wrapping.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • I want to have a next button which find the next match and highlight the matching text...Thanks! – user1005633 May 24 '13 at 17:33
  • Ok, so I've given you an approach, I'm not going to write the code for you. – camickr May 24 '13 at 17:46
  • Ok, i am not asking code :-) ... By the way i don't understand the part with HTML wrap... – user1005633 May 24 '13 at 17:49
  • +1 very good suggestion, description, @user1005633 [not easy job, could be possible without Html](http://stackoverflow.com/questions/6410839/highlights-substring-in-the-tablecells-which-is-using-for-jtable-filetering) – mKorbel May 24 '13 at 18:13