BigFish
BigFish

Reputation: 21

HTML within JLabel doesnt show same result in Browser

I have a JLabel with some html formatted text in it. Ultimatly im trying to wrap lines within a JTable. However, my problem can be simplified just with a JLabel. The HTML formatting within looks like this:

<html>
<body style='width: 250px;'>
    <p style='word-wrap: break-word;'>some string</p>
</body>
</html>

Running this in a browser everything works as expected, and even with a long one word string, it wraps as i want it to. If i put this in a JLabel like so:

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class HtmlInLabelExample extends JFrame {

    private static final long serialVersionUID = 2194776387062775454L;

    public HtmlInLabelExample() {
        this.setTitle("HTML within a JLabel");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new BorderLayout());
        this.setSize(new Dimension(300, 100));
        this.setLocationRelativeTo(null);

        String HTML_1 = "<html><body style='width: ";
        String HTML_2 = "px;'><p style='word-wrap: break-word;'>";
        String HTML_3 = "</p></body></html>";

        String strWithSpaces = "This is a long String that should be wrapped and displayed on multiple lines. However, if this was only one really long word, that doesnt work.";
        String strWithoutSpaces = "ThisisalongStringthatshouldbewrappedanddisplayedonmultiplelines.However,ifthiswasonlyonereallylongword,thatdoesntwork.";
        JLabel lblHtml = new JLabel();

        lblHtml.setText(HTML_1 + String.valueOf(250) + HTML_2 + strWithoutSpaces + HTML_3);

        this.add(lblHtml);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new HtmlInLabelExample();
            }

        });
    }

}

the wrapping works but it doesnt break inbetween words, as if i wouldnt use style='word-wrap: break-word;.

Could somebody explain to me why the html format works differently in the Browser (i tried most common ones) and if there is a way around it?

Upvotes: 1

Views: 68

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168825

Could somebody explain to me why the html format works differently in the Browser ..

Swing supports only a sub-set of HTML 3.2 & very simple styles. I'd be surprised if it did support word-wrap: break-word;

..if there is a way around it?

Embed a browser. Swing does not offer one, but Java-FX does.

Upvotes: 2

ControlAltDel
ControlAltDel

Reputation: 35011

JLabel is a Swing component, so it's support for CSS may very well not be up to the latest standards... or even the standards before that. The world of technology has kind of moved on from Swing...

Upvotes: 0

Related Questions