使JTextArea的部分不可编辑(而不是整个JTextArea!)


问题内容

我目前正在使用Swing中的控制台窗口。它基于JTextArea并像普通命令行一样工作。在一行中键入命令,然后按Enter。在下一行中,显示输出,在该输出下,您可以编写下一条命令。

现在,我想只能用命令编辑当前行。上面的所有行(旧命令和结果)均不可编辑。我怎样才能做到这一点?


问题答案:

您不需要创建自己的组件。

这可以使用自定义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,然后在输出时将其重置重做。