简体   繁体   English

Java-JFormattedTextField不允许在首次尝试时输入

[英]Java - JFormattedTextField does not allow input on first attempt

I am making a little Sudoku game with a GUI and use a MaskFormatter for the JFormattedTextFields: 我正在用GUI制作一个数独游戏,并将MaskFormatter用于JFormattedTextFields:

 formatter = new MaskFormatter(s);
 formatter.setValidCharacters("123456789");

But my problem is that when the window opens and i click into one of those fields, it is not possible to type something, 但是我的问题是,当窗口打开且我单击这些字段之一时,无法键入内容,
it only works on second try, namely when I click into another field and then back to the first one. 它仅适用于第二次尝试,即当我单击另一个字段然后返回到第一个字段时。

Is it like it has to lose focus first to activate? 是否需要先失去焦点才能激活?

If some of my code is necessary please let me know. 如果需要我的一些代码,请告诉我。

Here's what it looks like 这是它的样子

在此处输入图片说明

EDIT: The problem was here: 编辑:问题在这里:

if (guessMatrix[i][j] == 0) {
    tfM[j][i].setBackground(Color.yellow);
    tfM[j][i].setText("");

Without the setText("") it works perfectly fine. 如果没有setText(“”),它可以正常工作。

I think you have problem in create object of MaskFormatter. 我认为您在创建MaskFormatter的对象时遇到问题。 you create object with pattern of masking and then after set valid characters. 您可以使用遮罩模式创建对象,然后设置有效字符。

 MaskFormatter formatter = new MaskFormatter("#");
 formatter.setValidCharacters("123456789");
 JFormattedTextField txt = new JFormattedTextField(formatter);

This work perfectly, when you click on textfield and type any number(1-9 only) it allow but you type any non-number then not allow. 当您单击文本字段并键入任何数字(仅1-9)时,它可以正常工作,但您键入任何非数字则不允许。

Thanks, Jignesh Gothadiya 谢谢,Jignesh Gothadiya

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM