UPDATED - problem is now solved in an ugly way - but there must be a proper way to do it?
I am having problems rendering text in a custom font, in HTML in a JLabel when the font name conflicts with the name of a font already installed on the system.
The system font is in a different format (otf vs ttf) so unsurprisingly the text is garbled.
The call to GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont
returns false to show the font failed to register. So I guess the question is, is there a way to use this font without registering, or a way to rename it before registering?
I have now solved my problem by editing the ttf file and mangling the font name to make a conflict extremely unlikely, but I'm guessing there must 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();
}
}
Maybe the text contained HTML commands with charset or such.
String text1 = "<html><body>"
+ text.replace("&", "&")
.replace("<", "<")
.replace(">", ">");
+ "</body></html>";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With