How to change background color of edit box while entering data by user?
조회 수: 24 (최근 30일)
이전 댓글 표시
I have some edit boxes and user must enter only positive numbers. I want the background color of edit boxes turns to red if user enters non-numeric or negative numbers. How can I do this? This must be done while entering data in edit box, not after clicking on a push button.
댓글 수: 1
Rik
2023년 6월 27일
편집: Rik
2023년 6월 28일
If you want to check the number while the user is typing: that is not possible with a normal edit field. If you insist, you will have to create an edit field that the user cannot interact with. Then you need to capture clicks and key presses (don't forget clicking on the middle of the string, or backspace, or pasting).
In short, it is much easier to have a callback to check the value. Callbacks respond to the enter key (and tab key).
Alternatively, you could create a timer that checks the value of the field every few seconds. If you store the previously checked string in a persistent, you can avoid rechecking the same over and over again. That way you can minimize the performance loss.
채택된 답변
Ronit
2023년 6월 27일
Hi,
Use the following function to create a box that turns red for non-negative integers.
function positiveNumberCheck()
fig = figure('Position', [200, 200, 300, 100]);
editBox = uicontrol('Style', 'edit', 'Position', [10, 40, 280, 30]);
set(editBox, 'Callback', @checkInput);
function checkInput(src, ~)
enteredValue = str2double(get(src, 'String'));
if isnan(enteredValue) || enteredValue <= 0
set(src, 'BackgroundColor', 'red');
else
set(src, 'BackgroundColor', 'white');
end
end
end
You can run the "positiveNumberCheck" function to create a figure window with an edit box.
댓글 수: 2
Rik
2023년 6월 27일
Which is why I suggested using a function activated by a timer. Live checking is not possible (as far as I'm aware) with Matlab natively, unless you implement everything from scratch.
추가 답변 (1개)
N A POORNA CHANDRA
2023년 6월 27일
hi rmpirooz, here is the code to change the background color of edit boxes for your requirement
function positiveNumbersGUI()
fig = figure('Position', [300, 300, 250, 100]);
editBox = uicontrol('Style', 'edit', ...
'Position', [20, 40, 100, 20], ...
'Callback', @validateInput);
function validateInput(~, ~)
userInput = str2double(get(editBox, 'String'));
if ~isnumeric(userInput) || isnan(userInput) || userInput < 0
set(editBox, 'BackgroundColor', 'red');
else
set(editBox, 'BackgroundColor', 'white');
end
end
end
also refer to this documentation for further understanding
참고 항목
카테고리
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!