您无需创建自己的组件.
这可以使用自定义DocumentFilter完成(就像我已经完成的那样).
您可以从textPane.getDocument()获取文档,并通过document.setFilter()在其上设置过滤器.在过滤器中,您可以检查提示位置,并且只有在位置在提示之后才允许修改.
例如:
private class Filter extends DocumentFilter {
public void insertString(final FilterBypass fb, final int offset, final String string, final AttributeSet attr)
throws BadLocationException {
if (offset >= promptPosition) {
super.insertString(fb, offset, string, attr);
}
}
public void remove(final FilterBypass fb, final int offset, final int length) throws BadLocationException {
if (offset >= promptPosition) {
super.remove(fb, offset, length);
}
}
public void replace(final FilterBypass fb, final int offset, final int length, final String text, final AttributeSet attrs)
throws BadLocationException {
if (offset >= promptPosition) {
super.replace(fb, offset, length, text, attrs);
}
}
}
但是,这会阻止您以编程方式将内容插入终端的输出(不可编辑)部分.您可以做的是在您要添加输出时设置的过滤器上的直通标记,或者(我做了什么)在附加输出之前将文档过滤器设置为null,然后在您输出时重置它重做.