There are several issues with the code.
- The "valueBox" is not reflecting the current counter value.
- There is also a typo in the "valueBox_callback" function: instead of using "handles.resultBox", it should be "hObject", and the counter variable should be "handles.counter".
- Furthermore, the "valueBox_callback" is not the appropriate place to update the display, as it only activates when the user interacts with the "valueBox". Instead, you should update the "valueBox" within the plus and minus button callbacks.
function counter()
hfig = figure();
% Set counter default value to 1 and store handles
handles = struct('counter', 1);
guidata(hfig, handles);
plusPushButton = uicontrol('Parent', hfig, 'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.1 0.5 0.2 0.1], ...
'String', '+', ...
'Callback', @plusPushButton_callback);
minusPushButton = uicontrol('Parent', hfig, 'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.4 0.5 0.2 0.1], ...
'String', '-', ...
'Callback', @minusPushButton_callback);
handles.valueBox = uicontrol('Parent', hfig, 'Style', 'edit', ...
'Units', 'normalized', ...
'Position', [0.25 0.3 0.2 0.1], ...
'String', '1', ... % Initialize with the starting value of counter
'Callback', @valueBox_callback);
% Update the guidata with the correct handles
guidata(hfig, handles);
end
function plusPushButton_callback(hObject, ~)
handles = guidata(hObject);
handles.counter = handles.counter + 1;
set(handles.valueBox, 'String', num2str(handles.counter)); % Update display
guidata(hObject, handles);
end
function minusPushButton_callback(hObject, ~)
handles = guidata(hObject);
handles.counter = handles.counter - 1;
set(handles.valueBox, 'String', num2str(handles.counter)); % Update display
guidata(hObject, handles);
end
With these changes, the GUI should correctly display and update the counter value in the "valueBox".
As GUIDE has been deprecated from MATLAB R2021a, it is recommended to use App Designer for the latest releases.
Hope this helps!
