JTable-Paint the content(text) in a cell

半腔热情 提交于 2019-12-01 12:17:51

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/16740332/jtable-paint-the-contenttext-in-a-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!