DocumentFilter allowing only numbers and period (.) into JTextField?

5.5k views Asked by At

\Here is the creation of the JTextField:

hourlyWageInput = new JTextField("7.25");
DocumentFilter filter = new UppercaseDocumentFilter();
((AbstractDocument) hourlyWageInput.getDocument()).setDocumentFilter(filter);
hourlyWageInput.setHorizontalAlignment(JTextField.CENTER);
add(hourlyWageInput);

Here is my DocumentFilter:

import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class UppercaseDocumentFilter extends DocumentFilter {

 public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
      String text, javax.swing.text.AttributeSet attr)

      throws BadLocationException {
           fb.insertString(offset, text.replaceAll("\\D", ""), attr);   
 }
}

This automatically removes all letters and characters from the JTextField.

However, I was wondering if anyone knows of a place with all of the commands similar to "\D". It took me a while to find the right information.

Also, the code I have now also prevents . from being types which I need as I am working with doubles. Any ideas?

Thanks! It's amazing how much I have learned today. I've been coding 13 hours straight.

1

There are 1 answers

4
Nick Rippe On BEST ANSWER

The replaceAll function takes in a regular expression. You can learn a bit about regular expressions from many tutorials online (see @Hovercraft Full Of Eels comment) or directly from the Java api: http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

Essentially you can put together any of the regular expression constructs (listed in the above link) together to form a regular expression. If you for instance wanted to ensure that only 0-9 and . are allowed, you can use:

text.replaceAll("[^0-9.]", "")