I\'ve just started porting my Swing app from OS X to Windows and things are painful with JLabel
s.
I\'ve noticed that the font specified to setFont
For reference, here's what is seen on Mac OS X.
By comparison, here's the display on Ubuntu 10, OpenJDK 6.
import java.awt.Font;
import java.awt.GridLayout;
import java.io.File;
import javax.swing.*;
public class LabelTestFrame extends JFrame {
public LabelTestFrame() throws Exception {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(0, 1));
String fontPath = "SophomoreYearbook.ttf";
Font testFont = Font.createFont(
Font.TRUETYPE_FONT, new File(fontPath)).deriveFont(18f);
JLabel label1 = new JLabel("<html>Some HTML'd text</html>");
label1.setFont(testFont);
this.add(label1);
JLabel label2 = new JLabel("Some plaintext");
this.add(label2);
this.pack();
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
new LabelTestFrame().setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
registerFont()
I found this little gem while Googling about if I could copy a .ttf
into the JRE at runtime. It does exactly what it's supposed to. If you use Font.createFont
to load a font at runtime, just do:
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(myCreatedFont)
to register it with the JRE.
This allows the font to show up in HTML'd text as well as plaintext on Windows!