Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing JLabel, HTML and custom fonts

In our Java Swing application, we're loading a custom font and adding it to a 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);

Easy and worked fine on 3 different systems. Until someone else tried to run it. The font was loaded (as we're also using on some other Swing elements), but not used in the JLabel.

After some searching, I've found out you can't use both HTML and a loaded font. For some reasons it works on my system (I assume it has something to do with the Java version), but not on some others. As we would like the project to work in outdated Java versions, just asking to update isn't an option.

One option is to install the font on the computer, something we don't like to do. The best solution I've found is this one: How can I create a Java/Swing text component that is both styled and has a custom font?

However, that question is about a JTextPane. A JLabel doesn't seem to have a getStyledDocument() method I can use for that.

Is there any way to let our font work with the JLabel?

like image 519
Bv202 Avatar asked Dec 07 '11 21:12

Bv202


People also ask

Can you use custom fonts in HTML?

html , then open styles. css in your text editor. You can use the @font-face rule to load a custom font on a web page.

What fonts can I use in Java Swing?

Logical fonts are the five font families defined by the Java platform which must be supported by any Java runtime environment: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical fonts are not actual font libraries.

How do I change the font style in swing?

To set the font for a Swing component, use its setFont() method of the component. JButton closeButton = new JButton("Close"); closeButton. setFont(f4);


2 Answers

To use some font:

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

The Font you created has to be registered first in the singleton GraphicsEnvironment to be accessible to all:

GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
genv.registerFont(font);
like image 187
Joop Eggen Avatar answered Oct 15 '22 20:10

Joop Eggen


Because StyledDocument extends Document, you may be able use an implementation thereof using JTextField's setDocument() method.

like image 2
BenCole Avatar answered Oct 15 '22 19:10

BenCole