UPDATED - the problem is now resolved in an ugly way - but should there be a proper way to do this?
I'm having trouble displaying text in a custom font in HTML in JLabel when the font name conflicts with the name of the font already installed on the system.
The system font is in a different format (otf vs ttf), so it is not surprising that the text is distorted.
The call to GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont returns false to indicate that the font could not be registered. Therefore, I think the question is, is there a way to use this font without registering, or is there a way to rename it before registering?
Now I solved my problem by editing the ttf file and looking for the font name to make the conflict extremely unlikely, but I assume that there should be a proper way to handle this situation.
package test; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Font; import java.awt.FontFormatException; import java.awt.GraphicsEnvironment; import java.io.IOException; import java.io.InputStream; import javax.swing.JApplet; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; @SuppressWarnings("serial") class MyComponent extends JPanel { Font font; String text; public MyComponent(Font f) {font=f;} public void initSwing() { final String labelcontents = "<html><center>foo</center></html>"; System.out.println(labelcontents); JLabel text = new JLabel(labelcontents); text.setFont(font); add(text,BorderLayout.CENTER); } } @SuppressWarnings("serial") public class TestApplet extends JApplet { public void init() { Font mainFont = null; InputStream is = getClass().getResourceAsStream("fonts/Exo-Bold.ttf"); try { mainFont = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(24f); System.out.println(mainFont.getName()); boolean registered=GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(mainFont); System.out.println("registered "+registered); } catch (FontFormatException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } final Container fframe = (JComponent)(getContentPane()); final MyComponent component = new MyComponent(mainFont); Thread t = new Thread(new Runnable() { public void run() { try { SwingUtilities.invokeAndWait(new Runnable() {public void run() { fframe.add(component); component.initSwing(); fframe.revalidate(); fframe.repaint(); }}); } catch (Exception e) { e.printStackTrace(); } } }); t.start(); } }
source share