How to change background color of edit box while entering data by user?
23 次查看(过去 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!