Only allowing numbers and a symbol (-) to be typed into a JTextField

后端 未结 3 1163
天涯浪人
天涯浪人 2020-11-29 11:39

I\'m trying to create a math quiz and I only want the user to be able to enter numbers whether they\'re negative or positive. Is there any way to do so? I\'ve thought of u

相关标签:
3条回答
  • 2020-11-29 12:15

    Use DocumentFilter:

    NumberOnlyFilter.java:

    import javax.swing.*;
    import javax.swing.text.*;
    import java.util.regex.*;
    public class NumberOnlyFilter extends DocumentFilter
    {
    
        public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
        {
            StringBuilder sb = new StringBuilder();
            sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
            sb.insert(offset, text);
            if(!containsOnlyNumbers(sb.toString())) return;
            fb.insertString(offset, text, attr);
        }
        public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException
        {
            StringBuilder sb = new StringBuilder();
            sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
            sb.replace(offset, offset + length, text);
            if(!containsOnlyNumbers(sb.toString())) return;
            fb.replace(offset, length, text, attr);
        }
    
        /**
         * This method checks if a String contains only numbers
         */
        public boolean containsOnlyNumbers(String text)
        {
            Pattern pattern = Pattern.compile("([+-]{0,1})?[\\d]*");
            Matcher matcher = pattern.matcher(text);
            boolean isMatch = matcher.matches();
            return isMatch;
        }
    
    }
    

    and then you can use it like:

    ((AbstractDocument)yourTxtField.getDocument()).setDocumentFilter(new NumberOnlyFilter());
    
    0 讨论(0)
  • 2020-11-29 12:26

    You can use Integer.parseInt(String s, int radix), for decimal use 10 as a redix value.

    0 讨论(0)
  • 2020-11-29 12:33

    Alternatively, consider Validating Input using an InputVerifier. A Formatted Text Field may also be suitable.

    0 讨论(0)
提交回复
热议问题