这是我当前将文本附加到 JEditorPane 的方法 editorPane
。 hmtl
是一个字符串,它将 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/