java和ctrl + v中的DocumentFilter无法正常工作

时间:2017-01-23 18:03:42

标签: java copy-paste documentfilter

当我尝试使用此DocumentFilter时,ctrl + v和ctrl + c无效。

StockLog

我该怎么办?我正在使用这个documentfilter来控制输入文本的长度。另一种限制JTextarea或JTextfield长度的方法是什么?

public class stringLengthTrim extends DocumentFilter { private int limit; public stringLengthTrim(int limit) { this.limit = limit; } @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { Document innerDoc = fb.getDocument(); StringBuilder sb = new StringBuilder(innerDoc.getText(0, innerDoc.getLength())); sb.insert(offset, string); if (textOK(sb.toString())) { super.insertString(fb, offset, string, attr); } } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { Document innerDoc = fb.getDocument(); StringBuilder sb = new StringBuilder(innerDoc.getText(0, innerDoc.getLength())); int start = offset; int end = offset + length; sb.replace(start, end, text); if (textOK(sb.toString())) { super.replace(fb, offset, length, text, attrs); } } @Override public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { super.remove(fb, offset, length); } private boolean textOK(String text) { if (text.length() <= limit) { return true; } return false; } }

how to set documentfilter to support ctrl+v and ctrl+c?

and this is usage:

PlainDocument cID = (PlainDocument) contentID.getDocument(); cID.setDocumentFilter(new stringLengthTrim(9)); 是一个JTextarea。

0 个答案:

没有答案