java限制对JTextArea中某些行的访问?
我想制作一个JTextArea,用户不能在其中删除前一行。就像Windows中的命令提示符和Linux中的终端一样,您不能编辑前面的行
这就是我想到的,但似乎不起作用,我只能想出一个原因,但似乎不止一个原因
if(commandArea.getCaretPosition() < commandArea.getText().lastIndexOf("\n")){
commandArea.setCaretPosition(commandArea.getText().lastIndexOf("\n"));
}
此代码块存在于此方法中:
private void commandAreaKeyPressed(java.awt.event.KeyEvent evt)
# 1 楼答案
您可以对JTextArea的文档使用DocumentFilter。仅允许在JTextArea中编辑最后一行的可运行工作示例:
它是如何工作的?JTextArea是一个文本控件,实际数据包含文档。文档允许侦听更改(DocumentListener),有些文档允许设置DocumentFilter以禁止更改。PlainDocument和DefaultStyledDocument都是从AbstractDocument扩展而来的,AbstractDocument允许设置过滤器
请务必阅读java文档:
我还推荐教程: