简体   繁体   English

更改JTable行中特定单词的颜色

[英]Change the specific word's color in the row JTable

I am trying to figure out how can I change the color of word which is in the row in JTable. 我想弄清楚如何更改JTable中行中的单词的颜色。

For example this is my sentence which in one row; 例如,这是我的一行中的句子;

dmpsrv log "Tue Mar 12 15:33:03 2013" (GMT) (DB=SS@2) pid=662 user="s46" node="B2-W4" execution time=1(s) dmpsrv log“Tue Mar 12 15:33:03 2013”​​(GMT)(DB = SS @ 2)pid = 662 user="s46" node =“B2-W4”执行时间= 1(s)

In every row the structure is same and I want to show the user name in bold . 在每一行中结构都相同,我想以bold显示用户名。

But I don't know how can I do it ? 但我不知道怎么办呢? Does any one give some trick ? 有没有人给出一些技巧?

Thanks. 谢谢。

As @mKorbel stated you can use HTML tags in Swing: How to Use HTML in Swing Components 正如@mKorbel所说,你可以在Swing中使用HTML标签: 如何在Swing组件中使用HTML

Also you'll need a custom cell renderer: Using Custom Renderers 您还需要一个自定义单元格渲染器: 使用自定义渲染器

Example

This is just an example of implementation (it's not exactly what you need) but you can manage to make it more accurate: 只是实现的例子 (这不是正是你需要的),但你可以管理,使之更准确:

table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer(){

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

        String str = value.toString();
        String regex = ".*?user=\".*?\".*?";
        Matcher matcher = Pattern.compile(regex).matcher(str);
        if(matcher.matches()){
            regex = "user=\".*?\"";
            matcher = Pattern.compile(regex).matcher(str);
            while(matcher.find()){
                String aux = matcher.group();
                str = str.replace(aux, "<b>" + aux + "</b>");
            }
            str = "<html>" + str + "</html>";

            setText(str);
        }                
        return this;                
    }            
});

This renderer looks for user="whateverHere" pattern in the string. 此渲染器在字符串中查找user="whateverHere"模式。 If it matches then replaces all instances of this sub-string with the same sub-string sorrounded by <b></b> tags. 如果匹配,则用<b></b>标记所包含的相同子字符串替换此子字符串的所有实例。 Finally sorrounds the whole text with <html></html> tags. 最后用<html></html>标签来覆盖整个文本。

More info about regex in this Q&A: Using Java to find substring of a bigger string using Regular Expression 有关此问答的正则表达式的更多信息: 使用Java查找使用正则表达式的更大字符串的子字符串

As DefaultTableCellRenderer extends from JLabel (yes, a Swing component!) HTML tags will do the trick. DefaultTableCellRendererJLabel扩展时(是的,一个Swing组件!)HTML标签就可以了。

Screenshot 截图

在此输入图像描述

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

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