Ich habe ein JLabel mit einigen HTML-formatierten Text drin. Ultimately im Versuch, Zeilen innerhalb einer JTable einzuwickeln. Allerdings kann mein Problem nur mit einem JLabel vereinfacht werden. Die HTML-Formatierung sieht in etwa so aus:HTML in JLabel zeigt nicht das gleiche Ergebnis in Browser
<html>
<body style='width: 250px;'>
<p style='word-wrap: break-word;'>some string</p>
</body>
</html>
Ausführen dieses in einem Browser funktioniert alles wie erwartet, und auch mit einem langen Wortkette, es wickelt, wie ich es will. Wenn ich diese in einem JLabel etwa 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();
}
});
}
}
die Verpackung funktioniert, aber es funktioniert nicht zwischendurch Worte brechen, als ob i style = "word-wrap verwenden würde nicht: break-word ;.
Könnte mir jemand erklären, warum das HTML-Format im Browser anders funktioniert (ich habe es am häufigsten versucht) und ob es einen Weg gibt, es zu umgehen?
'WebView' kann in Swing eingebettet werden, für [Beispiel] (https://stackoverflow.com/a/31576647/230513). – trashgod