I'm working on a sudoku solver and I'm trying to limit the amount of numbers a user can enter into a cell as well as ONLY being able to enter numbers, currently it also accepts letters. At the moment it works like this: If a user enters "11125455876" it will just use the last number entered (in this case "6"). I would like to limit the amount of numbers a user can enter into a single cell to 1 and only accept numbers 1-9. I'm not really sure how I can do that. So maybe it'll just overwrite the previous number or something and if I press a letter key as "a" nothing should happen.
Here is my code:
public PanelGUI(int size) {
super(size);
NumberFormat f = NumberFormat.getInstance();
f.setMaximumIntegerDigits(1);
f.setMinimumIntegerDigits(0);
f.setGroupingUsed(false);
cells = new JTextField[size][size];
panel.setLayout(new GridLayout(size, size));
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cells[i][j] = new JFormattedTextField(f);
cells[i][j].setEditable(true);
cells[i][j].setFont(boldFont);
cells[i][j].setBorder(BorderFactory.createMatteBorder(1, 1, 1,
1, Color.white));
cells[i][j].setHorizontalAlignment(JTextField.CENTER);
panel.add(cells[i][j]);
}
}
}
As you can see I'm currently using number format
.
NumberFormat f = NumberFormat.getInstance();
f.setMaximumIntegerDigits(1);
f.setMinimumIntegerDigits(0);
f.setGroupingUsed(false);
You want to use a MaskFormat instread:
MaskFormatter f = new MaskFormatter( "#" );
f.setValidCharacters("123456789");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With