简体   繁体   English

JTable-绘制单元格中的内容(文本)

[英]JTable-Paint the content(text) in a cell

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. 我有一个JTable,我有一个方法,在表行和列中实现搜索,我使用正则表达式,我想绘制(例如黄色)与单元格中的正则表达式匹配的文本。 I want to paint the text not the background of the cell and only the part of word which matches with reg expression. 我想绘制文本而不是单元格的背景,只绘制与reg表达式匹配的单词部分。 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;
                                }
                }
            }

You will need a custom renderer to do this. 您需要一个自定义渲染器才能执行此操作。

The default renderer is a JLabel. 默认渲染器是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. 因此,执行此操作的唯一方法是在文本字符串周围包装HTML并更改要搜索的文本的字体颜色。 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: 如果要突出显示包含“100”的任何文本,则需要执行以下操作:

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

This is what I mean by wrapping. 这就是我的意思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM