TL;DR: What is the easiest and the most correct way to set up a Graphics
instance to use default settings to render strings? Or how to render a string using default anti-aliasing settings, so that it looks like a JLabel? More detailed description of the issue follows...
I'm trying to create a custom JComponent subclass. In fact, it's a sort of a TableCellRenderer
that is able display rich text. Extending JEditorPane
is too heavy and slow (tried it actually), and JLabel can't display rich text, so I decided to implement my own, lightweight and fast. Now, it (obviously) needs to draw some text in paintComponent()
, and I would like this text to look like in all other text components, like JLabel.
However, when I do it, it seems to use different anti-aliasing settings from the rest of the app, so it looks rather ugly. I realize that I can just cast Graphics
to Graphics2D
to use the appropriate API, but the question is, what exact settings to use? That is, what to pass to setRenderingHint()
as the second parameter?
I can get it look fine on my system by playing with various AA values, but then won't it suddenly look awful on some other system with different default AA settings?
I tried to look at JLabel and LabelUI sources, but they seem to use a lot of black magic, like querying some occult properties using JComponent.getClientProperty()
and SwingUtilities2
which isn't even a part of the official Swing. Of course, I could try to mimic that, but that's a) too tedious and b) bound to use some not-too-documented features that aren't event guaranteed to have a stable API.
Or maybe there is a way to reuse some existing UI delegate? Basically, I just want my text to look exactly as displayed by a JLabel
. I could even use an instance of JLabel
or its subclass as a sort of "rubber stamp" to draw the text, but that looks a bit ugly and I'm not sure about performance. I realize that JTable
actually does exactly that, but using a JLabel
to draw an entire cell is one thing, using it to draw parts of the cell just doesn't feel right. For example, it could happen that some L&F decorates these JLabel
s in a special way that will just look ugly.
Ideally, I would like to have something like this (imaginary code):
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
JLabel.getDefaultUI().getRenderingHint());
Or better yet (set up everything, not just AA):
JLabel.getDefaultUI().setupGraphics(g); // this sets up g just like for drawing a JLabel
But there is seems to be no such simple thing as far as I can see.