I know that I can see if a particular widget has control in SWT by using isFocusControl()
on it. However, when my expected widget doesn't have focus, how can I determine what does (in other words, what took the focus away)?
I'm able to handle keyboard e开发者_Go百科vents with traverse listeners, but changing focus using clicks of the mouse appears to mystify my application. I can't seem to figure out how to find the item that took the focus from the previous item.
I'm also having issues with reliably setting focus to another widget from within a FocusLost
listener if the focus is changed by a mouse event.
Any suggestions?
It is:
Display.getFocusControl();
As explained, Display.getFocusControl() tells you which Control has focus. You can associate information with widgets via the setData() methods. You can do this with every control that could possibly get focus and then getData() should help you figure out what control has the focus.
Otherwise you can just keep pointers to the controls that you created and compare the pointer to your known control pointers, no?
Since this is a tricky one, let me add something concerning the second part of the question:
I'm also having issues with reliably setting focus to another widget from within a FocusLost listener if the focus is changed by a mouse event.
When changing focus with the mouse, the mouse event is processed after the focus events. This might cause the mouse event to revoke changes you are applying in the focus events.
For example, to select the content of a text field after the textfield gains focus by a mouse click, an async call allows to delay the selection until the events are dispatched.
textfield.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
}
@Override
public void focusGained(FocusEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
if (!textfield.isDisposed()) {
textfield.selectAll();
}
}
});
}
});
Without the async call, the mouse event revokes the selection done in the focus event.
getFocusControl returns a Control and your item inherits from Control. I use a bunch of custom controls and when I get which has focus I then determine what class it really is by using a set of if( control instanceof myclass) statements (else ifs after the first) Then once I have the real class i then cast to that class and call the proper getter methods I put into my class.
Hope this helps,
精彩评论