Simple turn on Lamp with switch in app designer

33 次查看(过去 30 天)
I am trying to learn about app designer and have tried to make a basic app that turn the lamp GREEN if the switch is ON, and RED if the switch is OFF. For some reason there is no change in color of the lamp? I am using R2023a version of matlab.
function SwitchValueChanged(app, event)
disp('SwitchValueChanged callback triggered'); % Confirm function call
value = app.Switch.Value;
disp(['Switch value: ', value]); % Display switch value
if strcmp(value, 'on')
disp('Setting lamp color to green') % Debugging message
set(app.Lamp,'Color','green')
elseif strcmp(value, 'off')
disp('Setting lamp color to red') % Debugging message
set(app.Lamp,'Color','red')
end
end

回答(2 个)

Shivani
Shivani 2024-6-11
Hello @keaton,
I am not able to reproduce the issue with the given code snippet, so I may not be able to provide the most accurate solution. However, upon analyzing the code snippet shared, it is my understanding that the property to set the color of a lamp is not directly set using `set(app.Lamp, 'Color', 'green')` as you would in traditional MATLAB GUI programming (using set/get with handles). Instead, you work directly with the property of the component.
You can refer to the following code snippet for an example on how this can be done:
function SwitchValueChanged(app, event)
disp('SwitchValueChanged callback triggered'); % Confirm function call
value = app.Switch.Value;
disp(['Switch value: ', value]); % Display switch value
if strcmp(value, 'On')
disp('Setting lamp color to green') % Debugging message
app.Lamp.Color = 'green'; % Directly set the Color property
elseif strcmp(value, 'Off')
disp('Setting lamp color to red') % Debugging message
app.Lamp.Color = 'red'; % Directly set the Color property
end
end
I referred to the following documentation to understand the implementation details of sharing data within App Designer: https://www.mathworks.com/help/matlab/creating_guis/share-data-across-callbacks-in-app-designer.html
Hope this helps!

Adam Danz
Adam Danz 2024-6-11
编辑:Adam Danz 2024-6-25
The problem is that the values the switch returns are On and Off with capital letters. Your string comparison is case sensitive so On (upper case O) does not match on (lower case o) and Off does not match off.
if strcmp(value, 'on')
^
elseif strcmp(value, 'off')
^
Change the values to
if strcmp(value, 'On')
^
elseif strcmp(value, 'Off')
^
or use strcmpi which ignore case.

类别

Help CenterFile Exchange 中查找有关 Develop Apps Using App Designer 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by