How to accept only numbers in this case?
12 次查看(过去 30 天)
显示 更早的评论
Hello, I want to improve the text box "caja_lonsat" by forcing that only numbers can be inserted, how could I do it? Thanks for this.
---------------------------
global caja_lonsat lonsat
caja_lonsat= uicontrol('style','edit','Units','normalized','pos',tex(29,:),...
'ForegroundColor','black','String',num2str(lonsat,'%4.2f'),...
'Horizontalalignment','left',...
'Backgroundcolor','white','Fontsize',12);
lonsat=str2num(get(caja_lonsat,'string'));
---------------------------
2 个评论
Walter Roberson
2017-12-18
When you say that only numbers can be inserted, do you mean only the digits '0' to '9', or do you include positive and negative signs, and do you include decimal points, and do you include exponential floating point format, and do you include complex numbers?
回答(2 个)
Walter Roberson
2017-12-18
In order to accept only a limited set of characters in a uicontrol style edit, you need to use the uicontrol KeyPressFcn callback. The callback needs to look in its eventdata to determine which key was pressed. If the key pressed is to be rejected, the callback must change the String property to remove the key.
Now, there is a difficulty involved: when you use a KeyPressFcn callback, then when you fetch the String property, even though some internal buffer is seeing the keystrokes, the String property returned will only reflect what was in the String property as of the time the user clicked in the field to start editing, and the String property will not be properly updated until the user pressed Return on the field or the user clicks outside the field.
It can be tricky to properly use both the KeyPressFcn and the Callback on the same field.
You will probably need to keep track of deletions as well. You will need to keep a buffer of keys outside of the String property and you will need to detect the return or newline and set the String property at that time with the validated data. Oh, and notice that the display may not be updated as you type...
All in all, it is usually much easier to instead wait until the user has typed in the entire field and then check to see if what they typed in is numeric, by fetching the String property in the Callback function, and using str2double(), and testing to see if that came out NaN. In other words, it is much easier to not prevent anything non-numeric from being entered, and to instead complain after the user has completed entering the non-numeric item.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!