DAndy
DAndy

Reputation: 147

How to change the Font used in Java BasicHTML View when bold/italic

So here is my tricky problem:

In our app, we are using Swing Views to display text items, more specifically ones that use and interpret HTML. Here is a little snippet to show our mechanism:

JLabel label = new JLabel();
label.setFont(StyleContext.getDefaultStyleContext().getFont("Roboto Light", Font.PLAIN, 13));

label.setText("<p><strong>bold</strong></p>");

htmlView = BasicHTML.createHTMLView(label, label.getText());

This solution worked perfectly fine for us for some years now, and all bold or italic words, converted from HTML/CSS within the text-String, were displayed well.

But now we are using a new font (more specifically: Roboto Light), and we are unhappy with the resulting fonts / "how the letters look" when words are bold or italic.

Now our question is: Is there a way to tell the view or any component, which font to use, when the standard font is combined with a bold / italic word?

Upvotes: 2

Views: 992

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168845

The fonts can be set in a stylesheet.

enter image description here

import javax.swing.*;

public class CustomFontForBoldAndItalic {

    public static String EOL = System.getProperty("line.separator");
    private static String styles = 
            "p {font-family: serif; font-size: 25px;}" + EOL
            + "b {font-family: sans-serif;}" + EOL
            + "em {font-family: monospaced;}" + EOL
            ;
    private static String html = "<html><head><title>HaHa</title><style type='text/css'>" 
            + EOL
            + styles + "</style></head><body>"
            + "<p>This part is <b>bold</b> while this part is <em>italic</em>.</p>"
            + "</body></html>";

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(null, new JLabel(html));
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

Upvotes: 4

Related Questions