MATLAB: How to create a function to change the color of a pushbutton

functionsguideMATLAB

Hello, I've an application that changes the color of a pushbutton but I have 25 pushbuttons and I don't want to copy/paste the code, how can I create a function that recieves the button as a parameter and change the color? here's the code:
% --- Executes on button press in cell11.
function cell11_Callback(hObject, eventdata, handles)
color=get(handles.cell11,'BackgroundColor');
if(color==[0.94,0.94,0.94])
set(handles.cell11,'BackgroundColor',[0,0,0]);
elseif(color==[0,0,0])
set(handles.cell11,'BackgroundColor',[0.94,0.94,0.94]);
end
% hObject handle to cell11 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

Best Answer

You can simply use cell11_Callback as callback function for all buttons, but use hObject instead of the hardcoded "handles.cell11". Or if you have any reason not to do this, you can call the function from other callbacks also:
% As you have posted already, but with hObject instead of the hard-coded
function cell11_Callback(hObject, eventdata, handles)
color=get(hObject,'BackgroundColor');
if(color==[0.94,0.94,0.94])
set(hObject,'BackgroundColor',[0,0,0]);
elseif(color==[0,0,0])
set(hObject,'BackgroundColor',[0.94,0.94,0.94]);
end
% And for the next button
function cell12_Callback(hObject, eventdata, handles)
% Call the other callback, but use the current hObject:
cell11_Callback(hObject, eventdata, handles)
By the way: This is shorter:
color = get(hObject, 'BackgroundColor');
set(hObject, 'BackgroundColor', abs(color - 0.94));
Related Question