I have a dialog where each entry in a JTree has its corresponding options in a different panel, which is updated when the selection changes. If options for one of the entries is set to an invalid state, when the user attempts to change to a different entry in the tree, I want there to be an error dialog and have the selection not change.
I tried doing this with a valueChangeListener on the JTree, but currently then have to have the valueChanged method call ‘setSelectionRow’ to the old selection if there is an error. So that I don’t get a StackOverflow, I set a boolean ‘isError’ to true before I do this so that I can ignore the new valueChanged event. Somehow I have the gut feeling this is not the best solution. 😉
How would I go about it instead? Is there a good design pattern for situations like this?
Not sure it’s best practice, but maybe you could put a FocusListener on the component(s) you want to validate… call your validation when the event is called and then consume then event if you don’t want the focus to be moved because the validation fails?
Later Edit:
At least with java 8 (I didn’t check earlier versions) this solution won’t work, because the FocusEvent appears not to be a low-level event. Hence it cannot be consumed. See Method AWTEvent.consume()