[英]Restrict JTextField to only accept certain characters
I have 4 JTextFields
that should only accept certain characters: 我有4个
JTextFields
,只能接受某些字符:
0
, 1
) 0
, 1
) 0
- 7
) 0
- 7
) 0
- 9
) 0
- 9
) 0
- 9
, a
- f
, A
- F
) 0
- 9
, a
- f
, A
- F
) The user must not be able to input a forbidden character. 用户必须不能输入禁止的字符。
I know how I could validate the input afterwards, but not how to filter it. 我知道以后如何验证输入,但不知道如何过滤它。
I tried using a MaskFormatter
, but then I can't enter anything at all. 我尝试使用
MaskFormatter
,但随后根本无法输入任何内容。
MaskFormatter binaryFormatter = new MaskFormatter();
binaryFormatter.setValidCharacters("01");
JFormattedTextField binaryText = new JFormattedTextField(binaryFormatter);
You don't want to format the value, you want to filter the content. 您不想格式化值,想要过滤内容。 Use a
DocumentFilter
on a plain on JTextField
在
JTextField
的平原上使用DocumentFilter
Start by having a look at Implementing a DocumntFilter and Examples for more details... 首先查看实现DocumntFilter和示例以了解更多详细信息...
As an example, a "binary filter", which will only accept 0
and 1
例如,一个“二进制过滤器”,将仅接受
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);
}
}
Which can be applied directly to the field's Document
: 可以直接应用于该字段的
Document
:
JTextField binaryField = new JTextField(10);
((AbstractDocument)binaryField.getDocument()).setDocumentFilter(new BinaryDocumentFilter());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.