Smarter code for multiple pushbutton selection

1 visualización (últimos 30 días)
JB
JB el 28 de Sept. de 2017
Respondida: Walter Roberson el 28 de Sept. de 2017
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)

Respuestas (1)

Walter Roberson
Walter Roberson el 28 de Sept. de 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);

Categorías

Más información sobre Interactive Control and Callbacks en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by