Focus issues


#1

I’m finding that keyboard focus is a surprisingly complex beast to tame lately.

I have a component that has several layers of children within it. When any of the children get clicked on, the device as a whole should get focus. There are visual indicators to show whether or not it has focus.

What is the way I should go about this? If i give the component focus, that’s fine - it can respond with its focusGained. However, if I click on one of its children, (e.g. in a contained list - some row components of which also require focus) how am I supposed to let the main component know it should show focus?

Should i just deny all children direct keyboard focus, and instead forward keyPressed() calls to them if they’re not swallowed higher up? Or do I have to at each level notify upwards to the parent so that it might reach the main component? I guess I was a bit naive in thinking that a lot of this was done automatically - either that or i’ve just gone about it the wrong way!

this is the sort of structure i’m working with:

[Outer] - needs left/right keypresses

  • [viewport style component] - needs no keypresses
    – [listbox] - needs up/down/enter
    — [row component] - certain rows require specific keypresses

#2

Hmm. Focus can be a bit tricky. But there’s an easy way to do this - have a look at the FocusChangeListener, which will tell you whenever the focus changes globally.


#3

i looked at that, hoping it was what i was looking for - but surely listening for focus changes globally is overkill? i imagined that it would allow me to attach to a Component and listen to whenever focus changes in that. Any chance of such an addition?

Perhaps an alternative approach would be to make the children keyListeners instead, and make sure that only the outer component wants focus. that way i can avoid the children ever having focus.

What sort of approach would you recommend?


#4

It’s not really overkill. Focus change doesn’t happen very often, and it’s quick to test whether your component is the one that’s involved. I don’t think it’d be any more efficient to have a component-specific callback.


#5

that’s cool, just wanted your own opinion on the matter :slight_smile:


#6