How do I detect focus loss from a text edit object?

戏子无情 提交于 2019-12-22 06:57:38

问题


This is my first attempt to create a GUI in MATLAB. I haven't been able so far to find a way to detect when focus is moved from a text edit to some other object. I need such functionality so I can test "on the spot" the user input and change the text edit's background color to red, if the input is formed in an incorrect way.

In other words, it would be very convenient for the end-user to be able to write his expression in a text edit, then press tab to move to the next text edit, and at the same time see a red background in the first text edit in case of some problem with the input.

I have thought of several alternatives to check the user input but they are not as convenient as the above. How might I implement something like this?


回答1:


When you press tab to move the focus from an editable text box to another uicontrol object, the callback function of the editable text box will be invoked. So, you would just have to put the code for checking the text and alerting the user to a problem in the callback function of your editable text uicontrol.

Note that the documentation states that the callback for a uicontrol will also be invoked under these other conditions:

  • Clicking another component, the menu bar, or the background of the GUI.

  • For a single line editable text box, pressing Enter.

  • For a multiline editable text box, pressing Ctrl+Enter.

For example, here's a very simple callback implementation which will set the text background color to the default gray value if the string is either 'yes' or 'no', or red if the string is anything else:

function callback_fcn(hSource, eventData)
  if ismember(get(hSource, 'String'), {'yes', 'no'})
    set(hSource, 'BackgroundColor', [0.941176 0.941176 0.941176]);
  else
    set(hSource, 'BackgroundColor', 'r');
  end
end


来源:https://stackoverflow.com/questions/9830207/how-do-i-detect-focus-loss-from-a-text-edit-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!