[英]Restrict JTextField to only accept certain characters
我有4個JTextFields
,只能接受某些字符:
0
, 1
) 0
- 7
) 0
- 9
) 0
- 9
, a
- f
, A
- F
) 用戶必須不能輸入禁止的字符。
我知道以后如何驗證輸入,但不知道如何過濾它。
我嘗試使用MaskFormatter
,但隨后根本無法輸入任何內容。
MaskFormatter binaryFormatter = new MaskFormatter();
binaryFormatter.setValidCharacters("01");
JFormattedTextField binaryText = new JFormattedTextField(binaryFormatter);
您不想格式化值,想要過濾內容。 在JTextField
的平原上使用DocumentFilter
首先查看實現DocumntFilter和示例以了解更多詳細信息...
例如,一個“二進制過濾器”,將僅接受0
和1
public class BinaryDocumentFilter extends DocumentFilter {
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String text, AttributeSet attr)
throws BadLocationException {
StringBuilder buffer = new StringBuilder(text.length());
for (int i = buffer.length() - 1; i >= 0; i--) {
char ch = buffer.charAt(i);
if (ch == '0' || ch == '1') {
buffer.append(ch);
}
}
super.insertString(fb, offset, buffer.toString(), attr);
}
@Override
public void replace(DocumentFilter.FilterBypass fb,
int offset, int length, String string, AttributeSet attr) throws BadLocationException {
if (length > 0) {
fb.remove(offset, length);
}
insertString(fb, offset, string, attr);
}
}
可以直接應用於該字段的Document
:
JTextField binaryField = new JTextField(10);
((AbstractDocument)binaryField.getDocument()).setDocumentFilter(new BinaryDocumentFilter());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.