我正在研究数独求解器,我正在尝试限制用户可以输入单元格的数字的数量以及仅能够输入数字,目前它也接受字母。目前它是这样工作的:如果用户输入“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, 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");
关于java - 限制数字输入 JTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15931099/