我正在做一个数独解算器,为此我希望我的JTextFields只接受数字123456789中的一个作为有效输入。因此,我使用带有JFormattedTextField的MaskFormatter。但是,当我通过执行.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
此外,经过更多的测试,似乎在清除所有框之后,您可以键入许多不应该出现的字符,但当您单击另一个字段时,这些字符将全部消失。然后,如果您在其他框中单击,则会显示您先前输入的数字。
别拿这个!
发布于 2012-02-21 02:07:51
我不能告诉你确切的原因,但setText似乎会让你的JFormattedTextField发疯,因为""是一个字符串,它反对当前的掩码。
请尝试使用setValue(null)。
我刚刚确认了这个方法是有效的。下一段代码证明了这一点:
public class Two extends JFrame {
public static void main(String[] args) throws Exception {
new Two().a();
}
void a() throws Exception {
this.setLayout(new GridLayout(2, 1));
MaskFormatter formatter = new MaskFormatter("#");
formatter.setValidCharacters("123456789");
final JFormattedTextField field = new JFormattedTextField(formatter);
JButton b = new JButton("null!");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
field.setValue(null);
}
});
this.add(field);
this.add(b);
this.setSize(100, 100);
this.setVisible(true);
}
}单击null后!按钮格式化程序继续工作,因为它应该工作。
https://stackoverflow.com/questions/9365862
复制相似问题