Smarter code for multiple pushbutton selection

6 ビュー (過去 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 Center および File ExchangeGrid 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