你應該幾乎從不使用KeyListener的上一個JTextArea後或其他JTextComponent。爲此,我會使用一個DocumentFilter,它允許您在用戶輸入發送給Document之前更新Document。
例如,
import javax.swing.*;
import javax.swing.text.*;
public class DocFilterEg {
public static void main(String[] args) {
JTextArea textArea = new JTextArea(10, 20);
PlainDocument doc = (PlainDocument) textArea.getDocument();
doc.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset, String text,
AttributeSet attr) throws BadLocationException {
text = checkTextForParenthesis(text);
super.insertString(fb, offset, text, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
text = checkTextForParenthesis(text);
super.replace(fb, offset, length, text, attrs);
}
private String checkTextForParenthesis(String text) {
if (text.contains("{") && !text.contains("}")) {
int index = text.indexOf("{") + 1;
text = text.substring(0, index) + "}" + text.substring(index);
}
return text;
}
});
JOptionPane.showMessageDialog(null, new JScrollPane(textArea));
}
}
所以沒有任何辦法做我必須通過KeyPreesed或任何其他的KeyListener之前說的嗎? – user3369353
@ user3369353:它可以完成,但不建議您使用這樣的低級偵聽器。 –
可以發表在這種情況下使用Documentfilter的示例代碼? – user3369353