Java – restrict digital input jtextfield
•
Java
I'm working on a Sudoku solver. I'm trying to limit the number of cells users can enter and can only enter numbers. At present, it also accepts letters It works as follows: if the user enters "11125455876", it will only use the last number entered (in this case, "6") I want to limit the number of individual cells that users can enter to 1 and accept only the numbers 1-9 I'm not sure what I should do So maybe it just overwrites the previous numbers or something. If I press a letter key as "a", nothing will happen
This 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,Color.white)); cells[i][j].setHorizontalAlignment(JTextField.CENTER); panel.add(cells[i][j]); } } }
As you can see, I am currently using digital format
Solution
NumberFormat f = NumberFormat.getInstance();
NumberFormat f = NumberFormat.getInstance(); f.setMaximumIntegerDigits(1); f.setMinimumIntegerDigits(0); f.setGroupingUsed(false);
You want to use maskformat instread:
MaskFormatter f = new MaskFormatter( "#" ); f.setValidCharacters("123456789");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码