Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法使用text/html向窗格添加文本_Java_Html_Swing_Jeditorpane - Fatal编程技术网

Java 无法使用text/html向窗格添加文本

Java 无法使用text/html向窗格添加文本,java,html,swing,jeditorpane,Java,Html,Swing,Jeditorpane,我班上有一个JEditorPane,我正在尝试向其中添加文本。(我没有使用文本区域或窗格,因为它必须支持某些东西,如HTML) 我的问题是(我的JEditorPane称为chatLog),当我键入chatLog.setContentType(“text/html”)和类型chatLog.setText(“测试”) 什么都没发生 第二个我注释掉/removechatLog.setContentType(“text/html”)应该显示的文本显示良好 我不知道我做错了什么 来源: public Se

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

我的问题是(我的
JEditorPane
称为chatLog),当我键入
chatLog.setContentType(“text/html”)和类型
chatLog.setText(“测试”)
什么都没发生

第二个我注释掉/remove
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时,我不能像上面看到的那样设置插入符号的位置。它说有一个
非法辩论异常


谢谢您的帮助。

问题是您添加了如下新文本:

chatLog.setText(chatLog.getText() + str);
<html>
  <head>

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

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

为了证明这一点:

JEditorPane chatLog = new JEditorPane();
chatLog.setContentType("text/html");
System.out.println(chatLog.getText()); // This will print an HTML document
空HTML文档有一个
标记和一个空的
标记,如下所示:

chatLog.setText(chatLog.getText() + str);
<html>
  <head>

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

    </p>
  </body>
</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);
}

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

我认为您有一个x-->y问题,这个问题没有什么明确的内容-投票结束太广泛,(XxxEditorKit是如何使用、覆盖还是初始化的),或者,它现在已经解决了,所以不用担心。每当我第二次调用它时,它都会出现,但不是HTML格式的?哎呀,我错了,只是粗体了帕索,谢谢,这解决了我所有的问题,现在我只需要修改我的HTML并使之时尚:P