I would like to know the recommended library or procedure for dealing with multi-coloured text within Java. My current usage of java.awt.Graphics, while function, appears to be a bit more complex than necessary.
The main issue involves the frequent change of colour, creating a new java.awt.Colour() object whenever a new colour is needed (and it’s usually not one of the predefined values.) I already keep track of the previously used rgb value, but it’s possible that the colour can potentially change to unique values for each character I draw:
java.awt.Color colorRender = new java.awt.Color(rgb); g.setColor(colorRender);
I also ran a profiler on my code, and identified a secondary bottleneck in an extreme case. I suspect that it may be the method used for drawing a single character, but there may be overhead in determining said character:
char[] c = new char[1]; // Created once for many uses /* ... */ g.drawChars(charRender, 0, 1, x, y);
I have looked at the BufferedImage class – while it’s great for pixel-level graphics, it doesn’t directly support drawing characters.
I’m assuming you’re rendering text to an arbitrary component (via paintComponent()) rather than trying to modify the color of text in a JTextPane, JLabel, or other pre-existing widget.
If this is the case, you should look into using an AttributedString along with TextAttribute. These allow you to assign different styles (color, font, etc.) to various ranges of characters within a string and then render the whole string using Graphics.drawString(…). This way, the underlying graphics subsystem will handle any necessary changes to the graphics state during rendering making your code much more readable, and probably faster.
Here is an example usage.
Of course, as other have mentioned, you should also be caching your Color objects rather than recreating them over and over.