Java Swing JLabel, HTML and Custom Fonts

In our Java Swing application, we load our own font and add it to JLabel :

 try { this.font = Font.createFont(Font.TRUETYPE_FONT, new File("resources/fonts/ourcoolfont.ttf")).deriveFont(16f); } catch (Exception e) { this.font = new Font("Arial", Font.PLAIN, 16); } this.label.setFont(this.font); 

Simple and convenient operation on three different systems. Until someone else has tried to run it. The font has been loaded (since we also use some other Swing elements), but it is not used in JLabel .

After some searching, I found that you cannot use both HTML and the downloaded font. For some reason, it works on my system (I assume this has something to do with the Java version), but not for some others. Since we would like the project to work in legacy versions of Java, just an update request is not an option.

One option is to install the font on the computer, which we don’t like to do. The best solution I found is this one: How to create a Java / Swing text component that has both styles and has its own font?

However, this question concerns a JTextPane . A JLabel doesn't seem to have a getStyledDocument() method that I can use to do this.

Is there a way for our font to work with JLabel ?

+4
source share
2 answers

To use some font:

 <html><head><style type="text/css"> body { font-family: Cool; } </style></head><body>... 

The font you created must be registered first in singleton GraphicsEnvironment in order to access all:

 GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); genv.registerFont(font); 
+9
source

Because StyledDocument extends Document , you can use its implementation using the JTextField setDocument() method.

+2
source

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


All Articles