【发布时间】:2021-10-16 08:04:47
【问题描述】:
将 HTML 插入 JEditorPane 后,如果有空的段落元素,我将无法读取 HTML。这对我的项目很重要,因为我将它用作 html 编辑器,用户可以在其中创建新段落,但如果他们没有在段落中输入任何内容,他们会在下一个 editor.getText() 中被删除,这令人困惑为用户。
如果我调用 .getText() 而不做任何更改,编辑器窗格加载后,它具有以下 HTML 结构:
<html>
<head>
</head>
<body>
<p style="margin-top: 0">
</p>
</body>
</html>
但是如果我只是打电话
editor.setText(editor.getText())
System.out.println(editor.getText())
输出变为
<html>
<head>
</head>
<body>
</body>
</html>
我需要能够获取 HTML,使用 JSoup 对其进行修改,然后重新插入。理想情况下,调用 getText() 时我不会有任何损失。我尝试使用 HTMLDocument 读取 HTML:
StringWriter writer = new StringWriter();
try {
htmlKit_.write(writer, htmlDoc_, 0, htmlDoc_.getLength());
} catch (IOException e1) {
e1.printStackTrace();
} catch (BadLocationException e1) {
e1.printStackTrace();
}
String s = writer.toString();
System.out.println(s);
但它给了我相同的结果。有什么办法可以保留这些空标签?我还需要保留空列表标签、空表标签等。这是我的代码。感谢您的帮助
测试者:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import java.io.*;
import javax.swing.text.*;
public class TestEditor implements ActionListener {
JButton printHTMLButton_;
JEditorPane editor_;
HTMLEditorKit htmlKit_;
HTMLDocument htmlDoc_;
public TestEditor() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,600);
JPanel panel = new JPanel();
frame.getContentPane().add(panel);
panel.setBackground(Color.red);
printHTMLButton_ = new JButton("HTML");
printHTMLButton_.addActionListener(this);
panel.add(printHTMLButton_);
editor_ = new JEditorPane("text/html", "");
editor_.setEditable(true);
editor_.setPreferredSize(new Dimension(500, 500));
panel.add(editor_);
htmlKit_ = new HTMLEditorKit();
editor_.setEditorKit(htmlKit_);
htmlDoc_ = (HTMLDocument)editor_.getDocument();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == printHTMLButton_) {
System.out.println(editor_.getText());
editor_.setText(editor_.getText());
System.out.println(editor_.getText());
StringWriter writer = new StringWriter();
try {
htmlKit_.write(writer, htmlDoc_, 0, htmlDoc_.getLength());
} catch (IOException e1) {
e1.printStackTrace();
} catch (BadLocationException e1) {
e1.printStackTrace();
}
String s = writer.toString();
System.out.println(s);
}
}
public static void main(String[] args) {
new TestEditor();
}
}
【问题讨论】:
-
可能改成
<p style="margin-top: 0">&nbsp;</p> -
是的,这是一种快速而肮脏的修复,但随着程序的发展, 到处都会引起问题。有没有办法告诉编辑器“看看你为什么不直接返回所有的 html?我很确定空的
标签在编辑器模型中,我就是无法访问它们??跨度>
标签: java swing jeditorpane