JTable-绘制单元格中的内容(文本) [英] JTable-Paint the content(text) in a cell

查看:477
本文介绍了JTable-绘制单元格中的内容(文本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JTable,我有一个方法,在表行和列中实现搜索,我使用正则表达式,我想绘制(例如黄色)与单元格中的正则表达式匹配的文本。我想绘制文本而不是单元格的背景,只绘制与reg表达式匹配的单词部分。
我的搜索方法的代码是:

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


推荐答案

您需要一个自定义渲染器才能执行此操作。

You will need a custom renderer to do this.

默认渲染器是JLabel。因此,执行此操作的唯一方法是在文本字符串周围包装HTML并更改要搜索的文本的字体颜色。您需要将搜索文本传递给渲染器,以便渲染器可以确定要突出显示的文本。

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).

编辑:

通常当你添加文字时您使用的标签:

Normally when you add text to a label you use:

label.setText("user1005633");

如果要突出显示包含100的任何文本,则需要执行以下操作:

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.

这篇关于JTable-绘制单元格中的内容(文本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆