Smarter code for multiple pushbutton selection

조회 수: 3 (최근 30일)
JB
JB 2017년 9월 28일
답변: Walter Roberson 2017년 9월 28일
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)

답변 (1개)

Walter Roberson
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);

카테고리

Help CenterFile Exchange에서 Grid Lines, Tick Values, and Labels에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by