使JTextArea的部分不可编辑(不是整个JTextArea!) [英] Make parts of a JTextArea non editable (not the whole JTextArea!)
问题描述
我目前正在使用Swing的控制台窗口。它基于JTextArea,就像一个常见的命令行。在一行中键入命令,然后按Enter键。在下一行中,显示输出,在该输出下,您可以编写下一个命令。
I'm currently working on a console window in Swing. It's based on a JTextArea and works like a common command line. You type a command in one line and press enter. In the next line, the output is shown and under that output, you could write the next command.
现在我想,您只能编辑当前行命令。上面的所有行(旧命令和结果)都应该是不可编辑的。我该怎么做?
Now I want, that you could only edit the current line with your command. All lines above (old commands and results) should be non editable. How can I do this?
推荐答案
您不需要创建自己的组件。
You do not need to create your own component.
这可以使用自定义 DocumentFilter 。
您可以从 textPane.getDocument()获取文档
并通过 document.setFilter()
在其上设置过滤器。在过滤器中,您可以检查提示位置,并且只有在位置在提示之后才允许修改。
You can get the document from textPane.getDocument()
and set a filter on it by document.setFilter()
. Within the filter, you can check the prompt position, and only allow modifications if the position is after the prompt.
例如:
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,然后在您输出时重置它完成。
However, this prevents you from programmatically inserting content into the output (noneditable) section of the terminal. What you can do instead is either a passthrough flag on your filter that you set when you're about to add the output, or (what I did) set the document filter to null before appending the output, and then reset it when you're done.
这篇关于使JTextArea的部分不可编辑(不是整个JTextArea!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!