【问题标题】:Cant add text to JEditorPane with text/html无法使用 text/html 将文本添加到 JEditorPane
【发布时间】:2014-07-30 07:08:13
【问题描述】:

我的班级中有一个JEditorPane,我正在尝试向其中添加文本。 (我没有使用文本区域或窗格,因为它必须支持某些内容,例如 HTML)

我遇到的问题是(我的 JEditorPane 称为 chatLog),当我输入 chatLog.setContentType("text/html"); 并输入 chatLog.setText("Test");
什么都没有发生...

第二次我注释掉/删除chatLog.setContentType("text/html");应该出现的文本,看起来很好。

我不知道我做错了什么。

来源:

public ServerGUI() {
    // Rest of code above.

    JEditorPane chatLog = new JEditorPane();
    chatLog.setContentType("text/html");
    chatLog.setEditable(false);

    // Rest of code below.
}

public void appendText(String str) {
    // Can use a word instead of str too like the "Test" above.
    chatLog.setText(chatLog.getText() + str);
    //chatLog.setCaretPosition(chatLog.getText().length() - 1);
}

此外,我遇到的另一个小问题不是太大,当我将内容类型设置为 HTML 时,我无法将插入符号的位置设置为如上所示。它说有一个IllegalArgument Exception

感谢您的帮助。

【问题讨论】:

  • 我认为你有一个 x --> y 问题,从这个问题中看不清楚 - 投票结束的范围太广,(如何以及是否使用 XxxEditorKit,覆盖或初始化),but shot into the dark .... by @Guillaume Polet
  • 或者好吧,现在已经解决了,不用担心。

标签: java html swing jeditorpane


【解决方案1】:

问题是您像这样附加新文本:

chatLog.setText(chatLog.getText() + str);

因此,您将文本附加到当前内容。如果您设置text/html 内容类型并且您从不调用JEditorPane.setText(),它仍然有一些默认的HTML 代码。此默认 HTML 代码以正确的 </html> 结束标记结束。现在,如果您将任何内容附加到 HTML 文本,那将在 </html> 结束标记之后,因此不会被呈现。

演示一下:

JEditorPane chatLog = new JEditorPane();
chatLog.setContentType("text/html");
System.out.println(chatLog.getText()); // This will print an HTML document

空的 HTML 文档有一个<body> 标记和一个空的<p> 标记,如下所示:

<html>
  <head>

  </head>
  <body>
    <p style="margin-top: 0">

    </p>
  </body>
</html>

建议的解决方案:

使用JEditorPane.getDocument()。如果您设置text/html 内容类型,默认情况下返回的Document 将是HTMLDocument 的一个实例,您可以使用它为新的聊天消息添加新元素。

【讨论】:

  • 当我第二次调用它时,它会出现但不是 HTML 格式?
  • 糟糕,我的错误,只是粗体了。 :P
  • 另外,谢谢,这解决了我所有的问题,现在我只需要修复我的 HTML 并让它变得时尚:P
猜你喜欢
  • 2013-02-09
  • 2014-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
  • 1970-01-01
相关资源
最近更新 更多