| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
package com.timjohnstondev.unitconverter.view; |
| 12 | |
|
| 13 | |
import java.util.ArrayList; |
| 14 | |
import java.util.List; |
| 15 | |
import java.util.ResourceBundle; |
| 16 | |
import javax.swing.text.AttributeSet; |
| 17 | |
import javax.swing.text.BadLocationException; |
| 18 | |
import javax.swing.text.PlainDocument; |
| 19 | |
|
| 20 | |
|
| 21 | |
|
| 22 | |
|
| 23 | |
|
| 24 | |
|
| 25 | |
final class InputFilter extends PlainDocument |
| 26 | |
{ |
| 27 | |
private ResourceBundle resources; |
| 28 | |
private List <Character> allowableCharacters; |
| 29 | |
|
| 30 | |
|
| 31 | |
|
| 32 | |
|
| 33 | |
|
| 34 | |
|
| 35 | |
InputFilter(final String allowableChars) |
| 36 | 6 | { |
| 37 | 6 | resources = ResourceBundle.getBundle("com.timjohnstondev.unitconverter.view.View"); |
| 38 | 6 | allowableCharacters = asList(allowableChars); |
| 39 | 6 | } |
| 40 | |
|
| 41 | |
@Override |
| 42 | |
public void insertString(final int offset, final String text, final AttributeSet attr) throws BadLocationException |
| 43 | |
{ |
| 44 | 9 | final String oldText = getText(0, getLength()); |
| 45 | 9 | final String newText = removeNonNumericChars(text); |
| 46 | |
|
| 47 | 9 | super.insertString(offset, newText, attr); |
| 48 | |
|
| 49 | 9 | if (!matchesPattern(getText(0, getLength()))) |
| 50 | |
{ |
| 51 | 0 | super.replace(0, getLength(), oldText, attr); |
| 52 | |
} |
| 53 | 9 | } |
| 54 | |
|
| 55 | |
private String removeNonNumericChars(final String text) |
| 56 | |
{ |
| 57 | 9 | String number = ""; |
| 58 | 27 | for (char character : text.toCharArray()) |
| 59 | |
{ |
| 60 | 18 | if (allowableCharacters.contains(character)) |
| 61 | |
{ |
| 62 | 16 | number += character; |
| 63 | |
} |
| 64 | |
} |
| 65 | 9 | return number; |
| 66 | |
} |
| 67 | |
|
| 68 | |
private List <Character> asList(final String characters) |
| 69 | |
{ |
| 70 | 6 | final char[] chars = characters.toCharArray(); |
| 71 | 6 | final List <Character> list = new ArrayList <Character>(); |
| 72 | 78 | for (char c : chars) |
| 73 | |
{ |
| 74 | 72 | list.add(new Character(c)); |
| 75 | |
} |
| 76 | 6 | return list; |
| 77 | |
} |
| 78 | |
|
| 79 | |
private boolean matchesPattern(final String text) |
| 80 | |
{ |
| 81 | 9 | return text.matches(resources.getString("InputFilter.inputPatternCombined")); |
| 82 | |
} |
| 83 | |
} |