JLabel shifts the text vertically down while displaying HTML

半腔热情 提交于 2019-12-05 20:25:14

It seems that if we set the Font (family,size etc) for the HTML JLabel using setFont(..) the font is not rendered to the correct metrics of JLabel.

Here is an example I made to demonstrate (Both JLabels shown are using HTML):

A simple work around is to the the font size, family etc in HTML too.

As we can see the cyan HTML JLabel used setFont(..) (and was incorrectly rendered) while the green HTML JLabel used HTML to set the font and was rendered correctly:

JLabel labelHtml2 = new JLabel("<html><font size=10 family='Calibri'>" + text + "</font></html>");

Test.java:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static Font font = new Font("Calibri", Font.PLAIN, 38);

    public Test() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();

                }
                new Test();
            }
        });
    }

    private void initComponents() {
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        String text = "Hello world";

        //this label will not render correctly due to setting font via setFont(..)
        JLabel labelHtml1 = new JLabel("<html>" + text + "</html>");
        labelHtml1.setBackground(Color.CYAN);
        labelHtml1.setOpaque(true);//so background will be painted
        labelHtml1.setFont(font);

        //this label will render correcty font is set via html
        JLabel labelHtml2 = new JLabel("<html><font size=10 family='Calibri'>" + text + "</font></html>");
        labelHtml2.setBackground(Color.GREEN);
        labelHtml2.setOpaque(true);
        //labelHtml2.setFont(font);

        frame.add(labelHtml1, BorderLayout.NORTH);
        frame.add(labelHtml2, BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!