Lets say I've made a sublcass of HTMLEditorKit
(and other relevant classes) in order to display some custom HTML tags. I want to be able to to use these custom tags in JLabel
, JButton
, and so on. Is there any way to do this beside creating my own look-and-feel? That is, I want to tell swing "use this instance of HTMLEditorKit
for rendering HTML in JLabel
/etc" regardless of what look-and-feel is currently being used. From the little poking around I've done in Swing internals I don't think it's possible, but I'd love to be proven wrong.
How to make Swing use my own HTMLEditorKit for JLabel/JButton/etc
662 Views Asked by Matthew Cline At
3
There are 3 best solutions below
0

It can't be done normally . . . If you extend the JLabel
and JButton
classes, it might be possible, but these seems like a lot of work for something there are better ways to do[1]. Would be useful classes though.
[1]: If the text doesn't need to be dynamic, try using images in JImagesIcons
.
1

Please refer to https://bugs.openjdk.java.net/browse/JDK-6540252
The bug reporter proposes a several workarounds.
It can be done:
The key is in the class
javax.swing.plaf.basic.BasicLabelUI
, which is a basic UI for labels.In the paint method, we can see this code:
A BasicHTML class is the supplier of HTML capabilities in Java, so, theoretically, if you replace the client property for
BasicHTML.propertyKey
with your own implementation of View, then that class will be used and you can do whatever you want to render the text.The class
javax.swing.plaf.basic.BasicLabelUI
is the parent of most of other LAF label UIs out there, but not all, so it may not work for all LAFs. LAFs that don't support HTML using theBasicHTML
class will not work with your fix, either.But IMHO this is more of a hack than feature. You are programming againts implementation, not interface. So if you don't have really serious reasons to do that, I would suggest to find a cleaner way to render your custom HTML, such as JLabel subclass.