I want my jtextfield to accept only numerical values between 0 and the MAX
value specified in the code example below.
Let´s say the MAX
variable is set to 8, as below. Then I just want it to be possible to enter a numeric value between 0 and 8. In my code example below you can type 88, 77, 66 etc and that should not be possible. I have no clue how I can make it so it only accepts values between 0 and MAX
.
import javax.swing.*;
import javax.swing.text.*;
public class DocumentDemo extends JFrame {
public static void main(String[] args) {
new DocumentDemo();
}
final int MAX = 8;
public DocumentDemo() {
this.setVisible(true);
JTextField textField = new JTextField();
((AbstractDocument)textField.getDocument()).setDocumentFilter(
new DocumentFilter() {
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
int len = text.length();
boolean isValidValue = true;
for(int i = 0; i < len; i++) {
if(!Character.isDigit(text.charAt(i))){
isValidValue = false;
}
}
if(isValidValue && Integer.parseInt(text) > MAX) {
isValidValue = false;
}
if(isValidValue && fb.getDocument().getText(0, fb.getDocument().getLength()).length() > String.valueOf(MAX).length()) {
isValidValue = false;
}
if(isValidValue) {
super.replace(fb, offset, length, text, attrs);
}
}
}
);
textField.setColumns(5);
this.add(textField);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
}
}
JFormattedTextField sounds like what you want.
NumberFormatter nf = new NumberFormatter();
nf.setMinimum(new Integer(0));
nf.setMaximum(new Integer(8));
JFormattedTextField field = new JFormattedTextField(nf);
Edit: showed how to set min, max