Set control focus from code

Is there any way to set focus to a particular control using code? What I’m trying to do is check the value of a numeric text field after it’s been changed. If it exceeds a certain value, warn the user and check they want to continue. If they don’t, set the focus back to the control and set its value back to zero (or even better highlight the existing value).

Al,

Try something like this:

event.source.parent.getComponent('Text Field 1').requestFocusInWindow()

Hi MickeyBob,

I had previously tried the following code attached to the propertyChange event of a numeric text field:if event.propertyName == "intValue": if event.source.intValue > 350: if not fpmi.gui.confirm("Excess weight - are you happy to proceed?","Confirm"): event.source.intValue = 0 event.source.requestFocusInWindow()but it didn’t seem to work - the focus just goes to the next available control.

If I remove the confirm statement, the focus and cursor do go back to the control, but you also get a second cursor in the next available control! Any ideas?

Al,

I was able to duplicate you scenario.

In digging into the JComponent object model (http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComponent.html), the setInputVerifier() method caught my eye.

I’m thinking that creating a class based on the InputVerifier class (http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/InputVerifier.html) and assigning it to the numeric input component might do the trick.

In my mind, the class would have the “shouldYieldFocus” method defined, instead of the “verify” method, so that you could change the intValue property.

I would give it a try but I’ve got to go eat some turkey. Happy Thanksgiving.

Try putting the request focus command in an invokeLater

Thanks Carl. I got this working with the following code:if event.propertyName == "intValue": if event.source.intValue > 350: if not fpmi.gui.confirm("Excess weight - are you happy to proceed?","Confirm"): event.source.intValue = 0 def resetFocus(textbox = event.source): textbox.requestFocusInWindow() fpmi.system.invokeLater(resetFocus)Would you give me the one line dummies guide to why this is necessary (again!)?

Your code is being executed directly on the property change of the text field. This property was changed by virtue of the focus being lost, so deeper in the event call stack is a focus change event being processed. You’re trying to set focus, but you’re actually in the middle of a previous focus change. Your focus change gets clobbered by the one that is currently being processed. The “invoke later” says “do this after the event stack is done processing the current event”, thus it is safe again to alter the focus.