Smarter code for multiple pushbutton selection
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Walter Roberson
2017-9-28
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Interactive Control and Callbacks 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!