当一个由JEditorPane支持的HTMLEditorKit包含一个<br>标记,后面跟着一个空行时,该行就不会正确地呈现,插入符号也不会被正确地处理。请考虑以下示例代码:
import java.awt.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
public class HTMLEditorTest {
public static void main(String[] args) throws IOException, BadLocationException {
JFrame frame = new JFrame();
Reader stringReader = new StringReader("test<br><p>a");
HTMLEditorKit htmlKit = new HTMLEditorKit();
HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
htmlKit.read(stringReader, htmlDoc, 0);
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(htmlKit);
editorPane.setDocument(htmlDoc);
frame.getContentPane().add(BorderLayout.CENTER, new JScrollPane(editorPane));
frame.setBounds(100, 100, 500, 400);
frame.setVisible(true);
}
}未呈现<br>标记后的空行。当插入符号位于'a‘字符的左侧,并按下箭头向上键时,插入符号将消失:
在按“向上”之前:

按下‘up’之后:

请注意,“test”和“a”之间的距离太小,插入符号已经消失。
然后输入文本时,缺失的空行将可见:

问题似乎是空行的高度为0px,因此不可见,如果它在该行上,则包括插入符号。一旦该行有了内容,该内容将强制一个非零行高度.
你知道解决这个问题的简单方法吗?在最坏的情况下,我必须编写我的自己的编辑器包 (参见这里和这里中的自定义行包装)和/或自定义标签 (也是这里)。
发布于 2016-10-19 11:06:49
使用自定义编辑器工具包找到解决方案:
public class MyEditorKit extends HTMLEditorKit {
private static final int MIN_HEIGHT_VIEWS = 10;
@Override
public ViewFactory getViewFactory() {
return new HTMLFactory() {
@Override
public View create(Element e) {
View v = super.create(e);
// Test for BRView must use String comparison, as the class is package-visible and not available to us
if ((v instanceof InlineView) && !v.getClass().getSimpleName().equals("BRView")) {
View v2 = new InlineView(e) {
@Override
public float getMaximumSpan(int axis) {
float result = super.getMaximumSpan(axis);
if (axis == Y_AXIS) {
result = Math.max(result, MIN_HEIGHT_VIEWS);
}
return result;
}
@Override
public float getMinimumSpan(int axis) {
float result = super.getMinimumSpan(axis);
if (axis == Y_AXIS) {
result = Math.max(result, MIN_HEIGHT_VIEWS);
}
return result;
}
@Override
public float getPreferredSpan(int axis) {
float result = super.getPreferredSpan(axis);
if (axis == Y_AXIS) {
result= Math.max(result, MIN_HEIGHT_VIEWS);
}
return result;
}
};
v = v2;
}
return v;
}
};
}
}编辑器工具包返回一个自定义HTMLFactory。此工厂为叶元素创建自定义InlineView对象,其中InlineView不能具有0的高度。它总是至少有一个MIN_HEIGHT_VIEW,我将其设置为10个像素(在默认字体大小下工作得相当好)。当仅为查看而呈现HTML时,最初的实现是有意义的,因为在<br>标记之后的空行确实应该被忽略。但是,对于编辑,用户将期望在插入换行后看到下一行的插入符号。
https://stackoverflow.com/questions/40102869
复制相似问题