【问题标题】:Styling text in a JTextArea or JTextPane在 JTextArea 或 JTextPane 中设置文本样式
【发布时间】:2012-02-26 19:49:58
【问题描述】:

基本上,我有一个 JTextPane 来保存一些我希望设置样式的文本。 JTextArea 对我来说会更好用,但有人告诉我你不能设置这些文本的样式?

但是,JTextPane 的样式似乎不正确。例如,以下代码仅返回包含 HTML:

public static void main(String[] args) {
    JFrame j = new JFrame("Hello!");
    j.setSize(200,200);
    JTextPane k = new JTextPane();
    k.setText("<html><strong>Hey!</strong></html>");
    j.add(k);
    j.setVisible(true);
}

当用户与界面交互时,我希望能够在 JTextPane 中设置一些文本的样式,但到目前为止,它只返回带有 HTML 的字符串!救命!

【问题讨论】:

    标签: java html swing jtextpane


    【解决方案1】:

    如果要在JTextPane 中显示Html 的内容,则必须设置为JTextPane#setContentType("text/html");,例如here

    编辑:

    对于JEditorPanes / JTextPanes,是否有另一种方法可以实现StyledDocumentMutableAttributeSet 和自定义Highlighter,例如here

    上午方法是不使用Html syntax

    【讨论】:

      【解决方案2】:

      使用setContentType 方法让Java 知道它将是HTML。

      k.setContentType("text/html"); 
      

      【讨论】:

        【解决方案3】:

        我使用外观 (Substance) 并调用 setContentType("text/html") 时显示的字体有问题。我通过调用解决了它:

        textPane.putClientProperty(JTextPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
        

        另一种选择是将 HTML 文本包装在 JLabel 中。按照你的例子,代码是:

        JTextPane k = new JTextPane();
        k.insertComponent(new JLabel("<html><strong>Hey!</strong></html>"));
        

        【讨论】:

        • 使用JTextArea 通常比使用JLabel 更好,因为JTextAreaJScrollPane 中滚动效果更好,并允许用户选择和复制文本。感谢您提供有关 Substance 外观和感觉的信息。我也使用它,所以提示很有帮助。
        猜你喜欢
        • 2016-02-05
        • 2011-01-30
        • 2011-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多