I don't quite understand the difference between these two methods. In what situation would forceFocus()
be better than setFocus()
?
According to SWT: The Standard Widget Toolkit, Volume 1, forceFocus():
Forces the control to receive keyboard events. Controls that do not normally accept keyboard input will take focus using this method. If focus cannot be assigned for any reason, false is returned.
also:
Generally speaking, forcing focus is something that you never want to do. For example, forcing focus to a label is not very useful because labels don't draw in a manner that indicates they can accept input. Forcing focus to a control that does not expect it can confuse users because they have no idea where their keystrokes are going. Application programs should always use setFocus() to assign focus.
Coming in way late on this one, but I just finished a prolonged head-beating-against-wall session on something related to this and thought I'd do a quick report:
If your control has children, the setFocus(myControl)
will do a depth-first search down the child tree and set focus to the lowest first child. On the other hand, forceFocus(myControl)
will just set focus to myControl and have done with it.
I had a situation with a modeless dialog with a GridLayout, where most of the grid cells were a set of Canvas subclassed objects that needed focus. (Yes, this is a bit odd, but I wanted to be able to hover over a cell and type stuff into it.) The last control in the grid was a "done" button, which I set as the default selection.
When the mouse left the canvas cells, I was doing a setFocus(myDialogShell)
, which instantly set focus to the first canvas element, preventing the "done" button from receiving the \r and disposing of the whole sordid business. On the other hand, forceFocus(myDialogShell)
did the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With