Java Swing dependent field validation
During a focus transfer, is there a way to validate dependent fields such that a focus transfer among JComponents (a, b, c开发者_StackOverflow中文版) is not vetoed but a focus transfer to some external element (say, d) is vetoed?
The most natural place to do such a thing seems to be in InputVerifier.shouldYieldFocus()
; however, I don't see a way to obtain the (next) focus target at that time.
Not supported by the InputVerifier mechanism. And probably shouldn't at that level of granularity because it might lead to giving focus to d with invalid data in a.
Assume an InputVerifier which does know the opposite component (that is the potential next focusOwner) and its data is invalid
- in shouldYieldFocus it tests the opposite
- for b it allows the transfer
- transferred focus to b
- transfer focus to d (allowed)
(same overall effect with Rob's suggestion, btw, except that the a's InputVerifier is never run)
On the whole, the built-in validation support isn't very strong - lots of work left for the developer. Some things you would need to do
- can use InputVerifiers on the per-component level to actually do the validation, shouldYield returns true always
- have some "InputVerifierController" which checks whether the focus is going "to the outside"
- if going "outside" with any invalid data anywhere "inside" prevent the transfer
Using a framework like f.i. JGoodies Validation might be easier.
For the dependent components you should be able to use:
component.setVerifyInputWhenFocusTarget( false );
精彩评论