Before any one suggests HTML, I explain later why thats not an option here. I have a table that contains a column with text cells in it. I need to be able to highlight some of the text in each cell. So for example if the cell contained “cat foo dog”… I might want to highlight foo.
My current method is to use a custom TableCellRenderer that puts html into a JLabel component that gets rendered and for a time it was good. Then I noticed that when the text in the cell became too long to fit in the column width it just truncated the text without the normal “…” that happens normally in this case. Thus users didnt know there was more text they were not seeing. The other problem was that if the original text itself contained HTML, which in my case it does at times, the cell would not render correctly. I know I could just escape the html but I would still have the prevous problem.
If I use a component other than a jlabel then it makes my table’s cells look strange. Does any one have any suggestions? Thanks
Well, here is a solution.
In short, you can subclass
JLabelto draw the highlight manually. Override thepaintComponentmethod to do the actual drawing and useFontMetricsto calculate where the highlighted region should be drawn.Here is that answer in excruciating detail:
Basically, you can make a subclass of
JLabelthat can highlight stuff. I would do that like this; you may want to do it somewhat differently:Add a method that tells the label which part to highlight. This could be something like this, assuming you just need one highlighted region:
If you need multiple regions, just have an ArrayList instead of a simple field. A method for dehighlighting would probably be useful too.
Now, you need to override the
paintComponentmethod ofJLabel. Here you need to do several discrete steps, which you may want to organize in different methods or something. For simplicity, I’ll put it all in the paint method.First, you need to figure out the physical dimensions of the highlight, which you can do using the nice
FontMetricsclass. Create theFontMetricsclass for theFontyou’re using.Now you can get all the information you need to create a rectangle that will be the highlight. You’ll need the starting position, the height and the width. To get this, you’ll need two substrings of the
JLabel‘s text as follows:Now you can draw the highlighted region before drawing the rest of the label:
Of course, if you want the highlight to span multiple rows, that will require more work.
If you were wondering, I have actually written something like this before. On a whim, I decided to write my own text area type component from a
JPanel, and this was basically the way I handled highlighting. Reinventing the wheel may be stupid in an actual project, but it does teach you random stuff that may come in useful…