RFR: 5032471: JFormattedTextField does not use editformatter on initial focus with setText() [v2]
Alexey Ivanov
aivanov at openjdk.org
Fri Aug 4 20:08:31 UTC 2023
On Fri, 28 Jul 2023 19:40:26 GMT, Alexey Ivanov <aivanov at openjdk.org> wrote:
> I wonder what happens if `setText` is called with a value that cannot be interpreted by the current formatter and how it plays with different policies on focus lost as outlined in [the javadoc](https://docs.oracle.com/en/java/javase/17/docs/api/java.desktop/javax/swing/JFormattedTextField.html).
~~It should be safe because `commitEdit` is guarded by `isEditValid`.~~
I was about to write the above but I looked deeper in the code, and my opinion has changed dramatically.
Let's see what's happening when `setText` is called. The first thing that's done is `super.setText` is called. So far, so good.
The call `super.setText` mutates the text model, `Document`; as the result, the `edited` flag is set to `true` by `DocumentHandler` and its `insertUpdate` and/or `removeUpdate` methods.
When is the text validated? When is `isEditValid` set to `true` or `false`? The comment for the `setEditValid` method says, “This will invoked by `AbstractFormatter` as the user edits the value.” I can't see where and when `AbstractFormatter` gets called in this case.
Things aren't as clear now…
The documentation for [`JFormattedTextField`](https://docs.oracle.com/en/java/javase/17/docs/api/java.desktop/javax/swing/JFormattedTextField.html#) suggests the `setValue` method should be used to set the value.
When you edit the value, the `setText` method is used to change the displayed text as the `JFormattedTextField` switches into editing mode and back. As such, changing the implementation of `setText` (and `setDocument`) adds an overhead.
It looks as if `setText` and `setDocument` as well as methods of `Document` may mutate the text bypassing the formatter, thus breaking the invariants provided by the `JFormattedTextField` class. Perhaps, if it were possible, the direct access to `setText`, `setDocument` and `getDocument` should be restricted.
---
Taking into account everything I said above, I strongly believe the fix is not necessary and the bug should be closed as either *Not an Issue* or *Won't Fix*.
**The correct fix** to the sample provided is to *use the `setValue` method instead of `setText`*.
In `JFormattedTextProblem.java`, replace the lines
dateField.setText(displayDate.format(new Date()));
timeField.setText(displayTime.format(new Date()));
with
dateField.setValue(new Date());
timeField.setValue(new Date());
and both formatted text fields, `dateField` and `timeField`, behave as expected.
-------------
PR Comment: https://git.openjdk.org/jdk/pull/14993#issuecomment-1666117578
More information about the client-libs-dev
mailing list