Matlab GUI - Edit text only allow numbers and '.'

I would like to create an edit text that only allows to introduce numbers and '.' . If another letter is pressed it should write nothing.
Using KeyPressFcn I am able to detect the letter pressed and compare to the valid ones but I do not know what to do in order to not to write the character if it is not valid.
Any idea?

 채택된 답변

Daniel Shub
Daniel Shub 2011년 7월 1일

0 개 추천

If the key is invlaid you want to set the string of the edit box to be whatever the string is minus the last element
x = get(h, 'String')
set(h, 'String', h(1:end-1))

댓글 수: 1

Jan
Jan 2011년 7월 13일
This wil fail if a string is copied by Ctrl-V.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2011년 7월 1일

7 개 추천

This behaviour will annoy the user. The limitation of the keyboard feels sticky. Better let the user write anything and check the input in the callback function only, e.g. by:
function myNumberCheck(ObjH, EventData)
S = get(ObjH, 'String');
% Exclude characters, which are accepted by sscanf:
S(ismember(S, '-+eEgG')) = ' ';
% Convert to one number and back to a string:
S2 = sprintf('%g', sscanf(S, '%g', 1));
set(ObjH, 'String', S2);
% Perhaps a small warning in WARNDLG or inside the GUI:
if ~all(ismember(S, '.1234567890'))
...
end

카테고리

도움말 센터File Exchange에서 Environment and Settings에 대해 자세히 알아보기

질문:

2011년 7월 1일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by