简体   繁体   中英

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:

 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.

I think you have problem in create object of 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.

Thanks, Jignesh Gothadiya

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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