【问题标题】:JTextArea, JTextField, how to replace text from the caret to the left with another stringJTextArea,JTextField,如何用另一个字符串替换左侧插入符号的文本
【发布时间】:2018-01-28 11:35:53
【问题描述】:
我正在制作一个文本处理程序,我希望如果用户按下“a”(“a”只是为了演示,我有一个这样的特殊字符列表),它将替换插入符号中的一些字符左边有一个字符串。
我已经尝试过“setText”方法,但是它替换了然后移动了插入符号并且文本组件滚动到了末尾,我想要的是插入符号不要移动到其他任何地方并且文本组件不要滚动到末尾,怎么能我为此编写代码(我正在覆盖 processKeyEvent)?
任何帮助将不胜感激。
【问题讨论】:
标签:
java
jtextfield
jtextarea
【解决方案1】:
尝试使用文档过滤器:
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);
}
});