1

I am trying to figure out how can I change the color of word which is in the row in 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)

In every row the structure is same and I want to show the user name in bold.

But I don't know how can I do it ? Does any one give some trick ?

Thanks.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Batuhan B
  • 1,835
  • 4
  • 29
  • 39
  • 2
    easiest of ways is to use Html in Renderer – mKorbel Oct 24 '13 at 11:53
  • For this tutorial or example , how can i search this topic ? – Batuhan B Oct 24 '13 at 12:01
  • I think that you would search in posts by @camickr, but your structure in form `dmpsrv log "Tue Mar 12 15:33:03 2013" (GMT) (DB=SS@2) pid=662 user="s46" node="B2-W4" execution time=1(s)` talking about four-five columns (correct me if Im wrong:-), then you can to forget about something special to put to the Renderer, just follows Oracle tutorial, bunch of code in SSCCE form here – mKorbel Oct 24 '13 at 12:07
  • I have only one column, also do you think that if I use JtextFields, will it be more easy ? – Batuhan B Oct 24 '13 at 12:09

1 Answers1

3

As @mKorbel stated you can use HTML tags in Swing: How to Use HTML in Swing Components

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. If it matches then replaces all instances of this sub-string with the same sub-string sorrounded by <b></b> tags. Finally sorrounds the whole text with <html></html> tags.

More info about regex in this Q&A: Using Java to find substring of a bigger string using Regular Expression

As DefaultTableCellRenderer extends from JLabel (yes, a Swing component!) HTML tags will do the trick.

Screenshot

enter image description here

Community
  • 1
  • 1
dic19
  • 17,821
  • 6
  • 40
  • 69