【问题标题】:HTML within JLabel doesnt show same result in BrowserJLabel 中的 HTML 在浏览器中不显示相同的结果
【发布时间】:2017-07-25 22:37:03
【问题描述】:

我有一个 JLabel,里面有一些 html 格式的文本。最终我试图在 JTable 中换行。但是,我的问题可以通过 JLabel 来简化。其中的 HTML 格式如下所示:

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

在浏览器中运行它,一切都按预期工作,即使是一个很长的单字字符串,它也会按照我的意愿进行换行。如果我把它放在这样的 JLabel 中:

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();
            }

        });
    }

}

换行有效,但不会在单词之间中断,好像我不会使用 style='word-wrap: break-word;.

有人可以向我解释为什么 html 格式在浏览器中的工作方式不同(我尝试了最常见的)以及是否有解决方法?

【问题讨论】:

    标签: java html css swing


    【解决方案1】:

    有人可以向我解释为什么 html 格式在浏览器中的工作方式不同..

    Swing 仅支持 HTML 3.2 的子集和非常简单的样式。如果它确实支持word-wrap: break-word;,我会感到惊讶

    ..如果有办法解决它?

    嵌入浏览器。 Swing 不提供,但Java-FX does

    【讨论】:

    • WebView 可以嵌入到 Swing 中,用于example
    【解决方案2】:

    JLabel 是一个 Swing 组件,因此它对 CSS 的支持很可能达不到最新标准……甚至是之前的标准。技术世界已经从 Swing 转移...

    【讨论】:

      猜你喜欢
      • 2016-07-02
      • 1970-01-01
      • 2018-06-06
      • 2020-01-13
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      • 2014-05-04
      • 2018-02-01
      相关资源
      最近更新 更多