How to change background color of edit box while entering data by user?
24 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Rik
il 27 Giu 2023
Modificato: Rik
il 28 Giu 2023
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.
Risposta accettata
Ronit
il 27 Giu 2023
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 Commenti
Rik
il 27 Giu 2023
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.
Più risposte (1)
N A POORNA CHANDRA
il 27 Giu 2023
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
Vedere anche
Categorie
Scopri di più su Environment and Settings in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!