JTable-Paint content (text) in cell

I have a JTable and I have a method that implements a search in the rows and columns of a table, I am using regular expressions and I want to draw (like yellow) text that matches the regular expression in a cell. I want to draw the text, not the background of the cell, but only the part of the word that matches the reg expression. Code for my search method:

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

      

0


source to share


1 answer


For this, you need a dedicated renderer.

The default renderer is the JLabel. So the only way to do this is to wrap HTML around your text string and change the font color of the text you are looking for. You will need to pass the search text to the renderer so that the renderer can figure out which text to highlight.

The code you have entered has a problem as it will always scroll to the bottom of the table. So what is your exact requirement. You want to select all cells in one go. Or you just want to have a Next button that will find the next cell of text. In the first case, you don't want to automatically scroll the table. In the second case, you scroll through the table.

In addition, depending on the requirement, you will need to either redraw the entire table (if you show all occurrences at once), or just the current row (if you have the following functionality).

Edit:



Usually when you add text to the shortcut you are using:

label.setText("user1005633");

      

If you want to select any text containing "100" you will need to do:

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

      

This is what I mean by the wrapper.

+2


source







All Articles