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?