简体   繁体   English

限制JTextField只接受某些字符

[英]Restrict JTextField to only accept certain characters

I have 4 JTextFields that should only accept certain characters: 我有4个JTextFields ,只能接受某些字符:

  1. binary digits ( 0 , 1 ) 二进制数字( 01
  2. octal digits, so ( 0 - 7 ) 八进制数字,所以( 0 - 7
  3. all digits ( 0 - 9 ) 所有的数字( 0 - 9
  4. all hexadecimal characters ( 0 - 9 , a - f , A - F ) 所有十六进制字符( 0 - 9a - fA - 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 例如,一个“二进制过滤器”,将仅接受01

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM