I'm fairly new to Java and stackoverflow. Please alert me if I make a mistake or if I provide insufficient information.
I'm working on a Java Swing project and trying to use a custom DocumentFilter class to monitor and filter input in a JTextField. Specifically, I want to ensure that only three digits and certain special characters (-, comma) can be Typed in.
Here is the class i wrote:
import javax.swing.*;
import javax.swing.text.*;
public class NumberOnlyField extends JTextField {
public NumberOnlyField() {
PlainDocument doc = (PlainDocument) getDocument();
doc.setDocumentFilter(new NumberOnlyFilter());
}
private class NumberOnlyFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
throws BadLocationException {
if (string == null) {
return;
}
super.insertString(fb, offset, onlynumbers(string), attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
if (text == null) {
return;
}
super.replace(fb, offset, length, onlynumbers(text), attrs);
}
}
private String onlynumbers(String string) {
StringBuilder builder = new StringBuilder(string);
for (int i = builder.length() - 1; i >= 0; i--) {
char ch = builder.charAt(i);
if ((!Character.isDigit(ch) && ch != '-' && ch != ',') || i > 3) {
builder.deleteCharAt(i);
}
}
return string;
}
}
Here is use the TextField:
JTextField minRain = new NumberOnlyField();
minRain.setBounds(155, 130, 35, 20);
add(minRain);
minRain.setColumns(10);
The filter isn't functioning at all. The text field appears normally with no errors occurring and i can write evrything in it. Given its straightforward nature, I'm struggling to pinpoint what I might be doing incorrectly.
A
DocumentFilteris certainly one way to do it, but if you're fine switching gears, it would probably be much easier to just use aDocumentListener. It's less work that way.Here is a quick, easy example.
I also see that you are trying to edit the text. Normally, people just put up some warning that the text is bad, but that's fine. That's easy to do here too. Just use
Document#remove(int offset, int length). So if someone types in a1, then a2, and then af, you just get the offset, which is the index of the last character in the document, and then you get the length, which is 1, since you only want to remove the last character, then plug those 2 into the method, and you are good.