How to make Swing use native HTMLEditorKit for JLabel / JButton / etc

Suppose I create a subclass of HTMLEditorKit (and other relevant classes) to display some custom HTML tags. I want to be able to use these custom tags in JLabel , JButton , etc. Is there any way to do this, besides creating my own look? That is, I want to say swing "use this instance of HTMLEditorKit to render HTML in JLabel / etc", no matter what look is currently in use. From the little trick I did in the Swing chests, I don't think it is possible, but I would really like to be proved.

+4
source share
3 answers

It can be done:

The key is in the javax.swing.plaf.basic.BasicLabelUI class, which is the basic interface for shortcuts.

In the drawing method, we see this code:

 View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { v.paint(g, paintTextR); } 

The BasicHTML class is a provider of HTML features in Java, so theoretically, if you replace the client property for BasicHTML.propertyKey your own implementation of View, then this class will be used and you can do whatever you want to render the text.

The javax.swing.plaf.basic.BasicLabelUI class is the parent of most other LAF label user interfaces, but not for everyone, so it may not work for all LAFs. LAFs that do not support HTML using the BasicHTML class BasicHTML also not work with your fix.

But IMHO this is more a hack than a feature. You program the implementation again, not the interface. Therefore, if you don’t have really serious reasons for this, I would suggest finding a cleaner way to render your custom HTML, such as a subclass of JLabel.

+3
source

This cannot be done normally. If you extend the JLabel and JButton classes, this may be possible, but for them there seems to be a lot of work for something, there are better ways to do it [1]. However, classes would be helpful.

[1]: If the text should not be dynamic, try using images in JImagesIcons .

+1
source

Refer to https://bugs.openjdk.java.net/browse/JDK-6540252
The error reporter offers several workarounds.

-1
source

Source: https://habr.com/ru/post/1379423/


All Articles