JTextArea,JTextField,如何用另一个字符串替换从插入符号到左边的文本
JTextArea, JTextField, how to replace text from the caret to the left with another string
我正在制作一个文本处理程序,如果用户按 'a'('a' 只是为了演示,我有一个特殊字符列表),它会用字符串替换插入符号左侧的一些字符。
我已经尝试了 "setText" 方法,但它替换了然后移动了插入符号,文本组件滚动到末尾,我想要的是插入符号不要移动到其他任何地方,文本组件不要滚动到最后,我该如何编写代码(我正在覆盖 processKeyEvent)?
如有任何帮助,我们将不胜感激。
尝试使用文档过滤器:
JTextArea textArea = new JTextArea();
((AbstractDocument) textArea.getDocument()).setDocumentFilter(new DocumentFilter() {
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
if ("a".equals(text)) {
text = "B";
}
super.replace(fb, offset, length, text, attrs);
}
});
我正在制作一个文本处理程序,如果用户按 'a'('a' 只是为了演示,我有一个特殊字符列表),它会用字符串替换插入符号左侧的一些字符。
我已经尝试了 "setText" 方法,但它替换了然后移动了插入符号,文本组件滚动到末尾,我想要的是插入符号不要移动到其他任何地方,文本组件不要滚动到最后,我该如何编写代码(我正在覆盖 processKeyEvent)?
如有任何帮助,我们将不胜感激。
尝试使用文档过滤器:
JTextArea textArea = new JTextArea();
((AbstractDocument) textArea.getDocument()).setDocumentFilter(new DocumentFilter() {
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
if ("a".equals(text)) {
text = "B";
}
super.replace(fb, offset, length, text, attrs);
}
});