I want to color text in a JTable cell. I'm using a DefaultTableCellRender
with HTML Tags to color multible words/text. I'm using Regex to find words/text and replacing them by adding HTML Tags.
The problem here is that the HTML tags them selves should not match by the regex.
example:
Text:
This is a example text background
text to color "a example":
This is <font color="FFFFFF" style="background-color: #FFAABB">a example</font>
text background
next word to color "back":
This is <font color="FFFFFF" style="background-color: #FFAABB">a example</font>
text <font color="FFFFFF" style="background-color: #AAAAAA">back</font>ground
the "back" in the HTML tag should not be replaced. Is there a way to exclude this by the Regex?
code:
private String color(String val, ArrayList<ColorKeyWord> list) {
for(ColorKeyWord ckw: list){
val = val.replaceAll(ckw.getKeyWord(), "<font color=\"" + DecodedDataHTMLTags.color_white + "\" " +"style=\"background-color: #" + ckw.getColor() + "\">" + ckw.getKeyWord() + "</font>");
}
return val;
}
I think a simpler solution would be to us StyledLabel
from jidesoft and use StyleRange
. But the StyledTableCellRenderer
is not included in the free library.
I'm also using JTable
because i need variable cell height. This can not be achieved with swt tables.
There's probably a better way, but basically, what this does it sets up a series of optional groups which allows a
Pattern
andMatcher
to break theString
down into "ranges"We then use those ranges to "inject" the rules...
And the
MatchRange
...And this basically outputs
I added some additional conditions for testing.
What I would do, is create a class which could carry a condition (
"example text"
) and which could format the value (wrapping the HTML around it for example) and simply iterate over these to create the expression and apply the formatMaybe something like...
Which contains the "condition" or "rule" and the format to apply. Normally, I might be tempted to separate the "rule" and the "formatter", but I think you can get the basic idea...
Then you could do something like...
And...