我正在研究一个数独求解器,我试图限制用户可以进入单元格的数量,以及只能输入数字,目前它也接受字母.它的工作原理如下:如果用户输入“11125455876”,它将只使用输入的最后一个数字(在本例中为“6”).我想将用户可以输入单个单元格的数量限制为1,并且只接受数字1-9.我不确定我该怎么做.所以也许它只会覆盖以前的数字或者其他东西,如果我按一个字母键作为“a”就不会发生任何事情.
这是我的代码:
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]); } } }
如您所见,我目前正在使用数字格式.
解决方法
NumberFormat f = NumberFormat.getInstance(); f.setMaximumIntegerDigits(1); f.setMinimumIntegerDigits(0); f.setGroupingUsed(false);
您想使用MaskFormat instread:
MaskFormatter f = new MaskFormatter( "#" ); f.setValidCharacters("123456789");