I have found myself with an obstacle. I am developing a calculator project I have, and one of the objects in it is the JFormattedTextField, but I think we can call it just "text field". In the mentioned object, I wanted to allow only digits to be typed in it, as well as having a limit on the numbers that could be typed.
So I created the CalculatorsFilter class, and inside it, the code that would run the two objectives I wanted, so we can separate the class as, the digit filter:
public class CalculatorsFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String text,
AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, revise(text), attr);
}
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
super.replace(fb, offset, length, revise(text), attrs);
}
private String revise(String text) {
final StringBuilder builder = new StringBuilder(text);
int index = 0;
while (index < builder.length()) {
if (accept(builder.charAt(index))) {
index++;
} else {
builder.deleteCharAt(index);
}
}
return builder.toString();
}
public boolean accept(final char c) {
return Character.isDigit(c) || c == '.' || c == '-' || c == '+';
}
And the second part, which is the limit "creator":
private final int numlimit;
public CalculatorsFilter(int limit) {
if (limit <= 0) {
throw new IllegalArgumentException("The number limit can not be <= 0");
}
this.numlimit = limit;
}
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
final int currentLength = fb.getDocument().getLength();
final int overLimit = (currentLength + text.length()) - numlimit - length;
if (overLimit > 0) {
text = text.substring(0, text.length() - overLimit);
}
if (text.length() > 0) {
super.replace(fb, offset, currentLength, text, attrs);
}
}
}
As you probably have noticed, the problem here is that I have the same methods inside the same class, the method replace(). And of course, it gives an error message, as I actually expected. However, if I try to rename one of them, let's say, to "replace1", the renamed method will not work anymore, even if the error message went away. Another solution I have tried, is what seemed to be the simplest, just creating another class for each of these filters I wanted. However again, the obstacle is that I cannot use...
//intField is the JFormattedTextField.
intField.setDocumentFilter();
two times on my Main class, which means I can't use one class to each filter. Have I done something wrong while trying to fix, or is there a way to solve the duplicate method error without compromising one of them?