I am doing this assignment, make a program that solves sudoku. I have a panel with a grid of SudokuTextBox extends JFormattedTextField. I have a MaskFormatter so that it only accepts one integer per text box. Then in my panel I have this code when a key is relesed.
public void keyReleased(KeyEvent e) {
SudokuTextBox tb = (SudokuTextBox) e.getSource();
int row = tb.getRow();
int col = tb.getCol();
int value = toInteger(tb.getText());
//System.out.println(value);
if(sudoku.isValid(row, col, value)) {
sudoku.set(row, col, value);
}
else {
sudoku.set(row, col, 0);
tb.setText(null);
}
tb.setCaretPosition(0);
sudoku.print();
}
The thing is, if i put a valid value in a text box, then i go back and enter an invalid value (by the rules of sudoku) the text box is cleared. But then when I tab forward the previous valid value is displayed in the text box. My sudokumatrix that contains all the numbers that has been inputed do clear the value like it should so it is only in the corresponding text box.
To make matters even more confusing when i change "SudokuTextBox extends JFormattedTextField" to "SudokuTextBox extends JTextField" it works like a charm. But i cant set the size of JTextField so that it is square and I can not enforce only one integer per text box.
Am I missing something really obvious?
Ok so now I found it, "One of the shortcomings of the mask formatter is that as of the current implementation (Java 5), it has no support for letting a user revert a field to the blank value (the initial value of the field prior to any user input) once they have left the field at any point."
So since I am using a MaskFormatter I cannot clear the field.
Although not the identical question, I was searching through the (too many) questions like this one. In my case I wanted to be able to fill two other fields (jtfStarePatReq and jtfStarePatFound which are JTextFields) either by looking up an index directly or by using some spinners and creating a string and then looking that string up (okay, maybe that is too vague but I think it is enough context). What I wanted is that if the user deleted or cleared out the value in the JFormattedTextField jftfStareOpsIndex, then the other two fields would be cleared as well. I was using the .isEmpty() method on the JFormattedTextField to decide if I should use that field OR use the longer computed search method. So I NEED it to be empty if someone goes from looking up their own index to letting the software search for the index. Anyway, I tried catching the commitEdit() exception and setting the value to null and it seems to do the trick.
Here's an example of a resizable component that might be suitable for such a game. Although it contains no game logic, it handles input reasonably well. Clicking the mouse or pressing the space bar pop's up a menu, and the tab and number keys work as expected. In particular,
Digit.EMPTY
is a valid value.