且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-03 12:14:34

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

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.