java - 如何在不刷新整个 Pane 的情况下附加到 JEditorPane?

标签 java html swing user-interface jeditorpane

这是我当前将文本附加到 JEditorPane 的方法 editorPanehmtl是一个字符串,它将 HTML 文本存储在 JEditorPane 中,并且 line是一个字符串,它存储我想要添加到 <body> 末尾的 HTML 文本。 .

// Edit the HTML to include the new String:
html = html.substring(0, html.length()-18);
html += "<br>"+line+"</p></body></html>";

editorPane.setText(html); // Add the HTML to the editor pane.

这基本上只是编辑 HTML 代码并重置 JEditorPane,这是一个问题,因为这意味着整个 JEditorPane 刷新,使图像重新加载、文本闪烁等。如果可能的话,我想停止此操作。

所以我的问题是,如何在不刷新整个 Pane 的情况下附加到 JEditorPane?

我使用 JEditorPane 纯粹是因为它可以显示 HTML,欢迎使用任何替代方案。

最佳答案

另一个选择是使用 HTMLDocument#insertBeforeEnd(...) (Java Platform SE 8) .

Inserts the HTML specified as a string at the end of the element.

import java.awt.*;
import java.io.IOException;
import java.time.LocalTime;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;

public class EditorPaneInsertTest {
  private Component makeUI() {
    HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
    JEditorPane editor = new JEditorPane();
    editor.setEditorKit(htmlEditorKit);
    editor.setText("<html><body id='body'>image</body></html>");
    editor.setEditable(false);

    JButton insertBeforeEnd = new JButton("insertBeforeEnd");
    insertBeforeEnd.addActionListener(e -> {
      HTMLDocument doc = (HTMLDocument) editor.getDocument();
      Element elem = doc.getElement("body");
      String line = LocalTime.now().toString();
      String htmlText = String.format("<p>%s</p>", line);
      try {
        doc.insertBeforeEnd(elem, htmlText);
      } catch (BadLocationException | IOException ex) {
        ex.printStackTrace();
      }
    });

    Box box = Box.createHorizontalBox();
    box.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    box.add(Box.createHorizontalGlue());
    box.add(insertBeforeEnd);

    JPanel p = new JPanel(new BorderLayout());
    p.add(new JScrollPane(editor));
    p.add(box, BorderLayout.SOUTH);
    return p;
  }
  public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new EditorPaneInsertTest().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}

关于java - 如何在不刷新整个 Pane 的情况下附加到 JEditorPane?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48500891/

相关文章:

java - JPanel 如何显示颜色数组中的不同颜色?

java - GetResource 方法在 java 11 中不起作用

java - 如何在 JAX-RS/Jersey REST 应用程序中实际实现分页​​/排序/过滤?

javascript - Safari 不播放视频但有声音

html - 将列表放入一页并保持元素比例

java - 如何将一系列java.awt.image.BufferedImages(TYPE_3BYTE_BGR)压缩为视频(avi,mp4或其他格式可以用普通播放器播放)

java - 是否有一种经过批准的方法来根据 Java 类的功能对其进行分类?

java - 从 Android 中的 StartActivityForResult 返回一个类

html - 将父 div 的高度和另一个子 div 的高度扩展到更大的子 div 的高度

java - 将对象添加到 Swing 组件时,Java 在哪里复制和存储对象?