12/31/2006

程式二部曲--回叫函數

前面所述的細節,在寫程式時均未提到回叫函數(Callbacks)的部份,顯然沒有考慮回叫函數與各元件之對應是無法將結果與按鍵相連繫在一起的。前節僅是建好GUI的門面而已,但已經花了五牛二虎之力了。雖然如此,也不能半途而廢,不是嗎?

跳出式選單的回叫函數


跳出式選單目的是讓使用者選擇所要繪製之圖檔,故當使用者選定其中之一時,程式必須讀出其String之對應值Value,以決定那一項目的對應圖要顯示。其法是將該圖之資料送至current_data參數之中,以後只要按下任何鍵,依回叫函數之current_data執行即可。

因此,上述的前部份程式中,必須增添回叫函數之功能,並以巢狀程式納入:

% Pop-up menu callback. Read the pop-up menu Value property
% to determine which item is currently displayed and make it
% the current data. This callback automatically has access to
% current_data because this function is nested at a lower level.

function popup_menu_Callback(source,eventdata)
% Determine the selected data set.
str = get(source, 'String');
val = get(source,'Value');
% Set current data to the selected data set.
switch str{val};
case 'Peaks' % User selects Peaks.
current_data = peaks_data;
case 'Membrane' % User selects Membrane.
current_data = membrane_data;
case 'Sinc' % User selects Sinc.
current_data = sinc_data;
end
end


按鈕之回叫函數


三個按鈕各別產生不同的繪圖型式,圖之資料則得自跳出式選單中之項目,其資料置於current_data參數中,可以直接作為輸入值。

下面為此三按鈕個別回叫函數,可以將其加入於前節之程式後面,但必須在主程式之end之前:


% Push button callbacks. Each callback plots current_data in the
% specified plot type.

function surfbutton_Callback(source,eventdata)
% Display surf plot of the currently selected data.
surf(current_data);
end

function meshbutton_Callback(source,eventdata)
% Display mesh plot of the currently selected data.
mesh(current_data);
end

function contourbutton_Callback(source,eventdata)
% Display contour plot of the currently selected data.
contour(current_data);
end


整合回叫函數


上述之回叫函數分別列於程式之中,但如何呼叫變成重要的環節。為此必須從原程式中之uicontrol函數指令內之參數著手。換言之,三個按鈕相對應之uicontrol指令中,必須加入一組回收函數之參數,其屬性為'Callback',對應值為回收函數之名稱,但必須採用隱函數之呼叫,如:{@surfbutton_Callback}是,故三者之uicontrol中之參數均應修改,以Surf按鈕為例:

hsurf = uicontrol('Style','pushbutton','String','Surf',...
'Position',[315,220,70,25],...
'Callback',{@surfbutton_Callback});

其他二組及跳出式選單亦需將對應之值作如下之修正:

hmesh = uicontrol('Style','pushbutton','String','Mesh',...
'Position',[315,220,70,25],...
'Callback',{@meshbutton_Callback});
hcontour = uicontrol('Style','pushbutton','String','Contour',...
'Position',[315,220,70,25],...
'Callback',{@contourbutton_Callback});
hcontour = uicontrol('Style','pushbutton','String','Contour',...
'Position',[315,220,70,25],...
'Callback',{@contourbutton_Callback});
hpopup = uicontrol('Style','popupmenu',...
'String',{'Peaks','Membrane','Sinc'},...
'Position',[300,50,100,25],'Callback',{@popup_menu_Callback});