JTextField被清除后停止使用MaskFormatter
我正在做一个数独解算器,为此我希望我的 JTextFields 只接受数字 123456789 之一作为有效输入。因此,我将 MaskFormatter 与 JFormattedTextField 一起使用。但是,当我通过执行 .setText("") 清除所有 TextFields 时,MaskFormatter 不再工作。清除文本框后,我可以再次在其中写入任何内容。为什么以及如何修复它?
我的代码基本上是:
MaskFormatter formatter = new MaskFormatter("#");
formatter.setValidCharacters("123456789");
Font textFieldFont = new Font("Verdana", Font.BOLD, 30);
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
southPanel.setBorder(lineBorder);
field[i][j] = new JFormattedTextField(formatter);
field[i][j].setHorizontalAlignment(JTextField.CENTER);
field[i][j].setFont(textFieldFont);
southPanel.add(field[i][j]);
}
}
然后当我清除它时:
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
field[i][j].setText("");
}
}
编辑:这是所有代码,大部分代码都没有写,因为我的朋友这样做了。我现在刚刚接手稍微修复一下 GUI。
http://dl.dropbox.com/u/4018313/SudokuSolver.zip
另外,经过更多测试后,似乎在清除所有框后,您可以键入许多不应该出现的字符,但是当您单击另一个字段时,所有字符都会消失。然后,如果您单击其他框,您之前编写的数字将会出现。
别明白这个!
I'm doing a Sudoku solver and for that I want my JTextFields to only accept one of the numbers 123456789 as valid input. Therefore I use a MaskFormatter toghether with a JFormattedTextField. However when I clear all the TextFields by doing .setText("") the MaskFormatter doesn't work anymore. After clearing the textboxes I can write anything in them again. Why and how do I fix it?
My code is basically:
MaskFormatter formatter = new MaskFormatter("#");
formatter.setValidCharacters("123456789");
Font textFieldFont = new Font("Verdana", Font.BOLD, 30);
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
southPanel.setBorder(lineBorder);
field[i][j] = new JFormattedTextField(formatter);
field[i][j].setHorizontalAlignment(JTextField.CENTER);
field[i][j].setFont(textFieldFont);
southPanel.add(field[i][j]);
}
}
Then when I clear it:
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
field[i][j].setText("");
}
}
EDIT: Here is all the code, haven't written most of it cuz my friend did it. I'm just now taking over to fix the GUI a little bit.
http://dl.dropbox.com/u/4018313/SudokuSolver.zip
Also, after some more testing it seems like after clearing all the boxes you can type a lot of charachters that should not be there but when you click on another field all of them will disappear. Then if you click in the other boxes the numbers you wrote earlier will appear.
Don't get this!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我无法告诉您确切的原因,但
setText
似乎让您的JFormattedTextField
发疯,因为""
是一个字符串,并且与当前的字符串相反。面具。请尝试改用
setValue(null)
。我刚刚确定这个方法有效。下一段代码证明了这一点:
单击 null! 按钮后,格式化程序将继续按预期工作。
I can't tell you the exact reason but
setText
seems to drive yourJFormattedTextField
crazy because""
is a String and it is against the current mask.Please try using
setValue(null)
instead.I've just made sure that this method works. The next piece of code proves it:
After clicking the null! button formatter continues to work as it is supposed to work.