gpt4 book ai didi

java - 使 JTextField 仅接受一位数字

转载 作者:太空宇宙 更新时间:2023-11-04 15:20:50 25 4
gpt4 key购买 nike

我正在开发一个数独小程序,我想制作它的单元格(扩展 JTextField),以便它只接受 0-9 之间且长度为 1 的整数。稍后我会进一步限制它(所以它符合游戏规则)。我开始于:

    public Block(int[] blockNum){
this.setLayout(new GridLayout(3,3));
this.setBorder(new LineBorder(Color.BLACK,2));
for(int i=0; i<CELL_COUNT; i++){
cells[i] = new Cell(); // Cell extends JTextField
((AbstractDocument)cells[i].getDocument()).setDocumentFilter(
new MyDocumentFilter()); // <- this is relevant for this question

if(blockNum[i]!=0){
cells[i].setNumber(blockNum[i]);
cells[i].setEditable(false);
}
this.add(cells[i]);
}
}
}

在这里,我尝试过滤输入,一开始我只是尝试将其限制为整数和一位数字,但似乎我可以输入任意多的数字,并且最后一行不会被触发。

希望得到一些帮助,谢谢:

class MyDocumentFilter extends DocumentFilter
{
@Override
public void replace(DocumentFilter.FilterBypass fp, int offset
, int length, String string, AttributeSet aset)
throws BadLocationException
{
int len = string.length();
boolean isValidInteger = true;
if (len>1 || !Character.isDigit(string.charAt(0))) isValidInteger = false;


if (isValidInteger)
super.replace(fp, offset, length, string, aset);
else
Toolkit.getDefaultToolkit().beep();
}
}

最佳答案

尝试使用 DocumentFilter 类。这将允许您在实际显示之前检查输入。您还可以编辑下面的内容以仅检查整数。

JTextField tf = new JTextField();
AbstractDocument d = (AbstractDocument) tf.getDocument();
d.setDocumentFilter(new DocumentFilter(){
int max = 1;

@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
int documentLength = fb.getDocument().getLength();
if (documentLength - length + text.length() <= max)
super.replace(fb, offset, length, text.toUpperCase(), attrs);
}
});

关于java - 使 JTextField 仅接受一位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20406870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com