Home > other >  Setting font of JLabel or JOptionPane with html
Setting font of JLabel or JOptionPane with html

Time:05-05

I tried to set/change the font of a JLabel and the message of a JOptionPane with this code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SetFontViaHtml extends JFrame {

  String html= """
    <html>Default <b>bold</b> off</font><br>
    <font face=Arial>Arial <b>bold</b> off</font><br>
    <font face=Dialog>Dialog <b>bold</b> off</font><br>
    <font face=Monospaced>Monospaced <b>bold</b> off</font><br>
    <font face=Courier>Courier <b>bold</b> off</font><br>
    <font face=Courier New>Courier New <b>bold</b> off</font><br>
    <font face=Liberation Sans>Liberation Sans <b>bold</b> off</font><br>
    <font face=Segoe UI>Segoe UI <b>bold</b> off</font><br>
    <font face=Times New Roman>Times New Roman <b>bold</b> off</font><br>
    <font face=Verdana>Verdana <b>bold</b> off</font><br>
    <p style=font-family:Monospaced>Monospaced <b>bold</b> off</p>
    <p style=font-family:Arial>Arial <b>bold</b> off</p>
    <p style=font-family:Dialog>Dialog <b>bold</b> off</p>
    </html>""",
    html2= html.replace("\n", "");

  public SetFontViaHtml() {
    setSize(300,300);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    JButton b= new JButton("Show option pane");
    b.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        String title= "Html OptionPane";
        JOptionPane.showMessageDialog(SetFontViaHtml.this, html2, title,
                    JOptionPane.INFORMATION_MESSAGE);
      }
    });
    add(new JLabel(html), BorderLayout.CENTER);
    add(b, BorderLayout.SOUTH);
    setVisible(true);
 }

  public static void main(String args[]) {
    EventQueue.invokeLater(SetFontViaHtml::new);
  }   
}

All these fonts are installed in my os (Win10), but except for Monospaced and Verdana all the requested fonts are displayed in the default font of Dialog.bold. I also didn't find a way to at least switch off the 'bold' attribute. Any idea how to achieve this?
This is how it looks like at my site.
Result

CodePudding user response:

I would tend to stick to CSS2. This approach works for me:

  String html = """
    <html>
    <p style="font-family: Times New Roman;font-size: 20px">Times New Roman</p>
    <p style="font-family: Verdana;font-size: 16px">Verdana <span style="font-weight: bold;font-style:italic">bold</span></p>
    </html>
    """
  • Related