Smarter code for multiple pushbutton selection
1 view (last 30 days)
Show older comments
I'm writing a GUI where I can control plot color by pushbutton and uisetcolor() which also color the pushbutton and handle (store) the color code to be used for plot color in a PlotFcn. I have 60 pushbutton and code each separately as in my code below. But is there a way to reduce my code to less lines and make it smarter and still be able to control the color of each pushbutton?
My code is:
% --- Change color on plot 1 colorbutton1.
function colorbutton1_Callback(hObject, eventdata, handles)
rgb = uisetcolor();
set(handles.colorbutton1, 'BackgroundColor', rgb);
guidata(hObject, handles);
ColorFcn(handles)
% --- Change color on plot 2 colorbutton1.
function colorbutton2_Callback(hObject, eventdata, handles)
rgb = uisetcolor();
set(handles.colorbutton2, 'BackgroundColor', rgb);
guidata(hObject, handles);
ColorFcn(handles)
% --- Change color on plot 3 colorbutton1.
function colorbutton3_Callback(hObject, eventdata, handles)
rgb = uisetcolor();
set(handles.colorbutton3, 'BackgroundColor', rgb);
guidata(hObject, handles);
ColorFcn(handles)
function ColorFcn(handles)
X=handles.X;
col=zeros(numel(X(1,:)),3)
for i = 1:numel(X(1,:))
col(i,:)=get(handles.(sprintf('colorbutton%d',i)),'BackgroundColor')
end
handles.col=col
guidata(gcbo, handles);
PlotFcn(handles)
0 Comments
Answers (1)
Walter Roberson
on 28 Sep 2017
function colorbutton1_Callback(hObject, eventdata, handles) process_color_button(hObject, handles);
(code all of the buttons with that same line of code)
function process_color_button(hObject, handles) rgb = uisetcolor(); set(hobject, 'BackgroundColor', rgb); ColorFcn(handles)
Note: the
guidata(hObject, handles);
is not needed. Setting the BackgroundColor of a graphics object does not change the handles structure.
You can get away without defining those 60 different colorbuttonN_Callback functions if you remove all of those and add to your gui OpenFcn:
buts = findall(gcf, '-regexp', 'tag', '^colorbutton\d+');
set(buts, 'Callback', @process_color_button)
and use
function process_color_button(hObject, ~)
rgb = uisetcolor();
set(hobject, 'BackgroundColor', rgb);
handles = guidata(hObject);
ColorFcn(handles);
0 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!