Tho*_*rig 10 java swing document jtextarea jtextcomponent
我目前正在使用Swing的控制台窗口.它基于JTextArea,就像一个通用命令行.在一行中键入命令,然后按Enter键.在下一行中,显示输出,在该输出下,您可以编写下一个命令.
现在我想,你只能用你的命令编辑当前行.上面的所有行(旧命令和结果)都应该是不可编辑的.我怎样才能做到这一点?
Rev*_*nzo 16
您无需创建自己的组件.
这可以使用自定义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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这会阻止您以编程方式将内容插入终端的输出(不可编辑)部分.您可以做的是在您要添加输出时设置的过滤器上的直通标记,或者(我做了什么)在附加输出之前将文档过滤器设置为null,然后在您输出时重置它重做.
| 归档时间: |
|
| 查看次数: |
4886 次 |
| 最近记录: |