12/31/2006

完成GUI的畫面程式!

要使前述之介面可以執行,必須先將程式起始化,然後才能順利使用,其中必須考慮下述幾項:

所用單位必須正規化,以取得大小一致。這可利用'Units'屬性宣告為 'normalized'之狀態。此時所有元件均會隨GUI圖面之大小呈比例變化。正規化之單位其圖會以左下角為視窗的(0,0)點,而右上角則落在(1.0,1.0)之上。其餘要做的事項則包括:

  • 產生繪圖所需之資料。本例中需要三組資料:peaks_data, membrane_data與 sinc_data。每組資料必須與跳出式選單之項目匹配。
  • 在圖軸上顯示起始圖表。
  • 將此介面賦于一名稱,此名稱會在視窗之上方標題格出現。
  • 將介面視窗移至螢幕之中央。
  • 打開 GUI介面顯示開關。

依據上述各點,程式中尚需增加的部份如下:

% Initialize the GUI.
% Change units to normalized so components resize automatically.
set([f,hsurf,hmesh,hcontour,htext,hpopup],'Units','normalized');
% Generate the data to plot.
peaks_data = peaks(35);
membrane_data = membrane;
[x,y] = meshgrid(-8:.5:8);
r = sqrt(x.^2+y.^2) + eps;
sinc_data = sin(r)./r;
% Create a plot in the axes.
current_data = peaks_data;
surf(current_data);
% Assign the GUI a name to appear in the window title.
set(f,'Name','Simple GUI')
% Move the GUI to the center of the screen.
movegui(f,'center')
% Make the GUI visible.
set(f,'Visible','on');

綜合前節之內容,完整個的GUI程式如下,可以存檔後直接執行:

function simple_gui2
% SIMPLE_GUI Select a data set from the pop-up menu, then
% click one of the plot-type push buttons. Clicking the button
% plots the selected data in the axes.

% Create and hide the GUI figure as it is being constructed.
f = figure('Visible','off','Position',[360,500,450,285]);

% Construct the components
hsurf = uicontrol('Style','pushbutton','String','Surf',...
'Position',[315,220,70,25]);
hmesh = uicontrol('Style','pushbutton','String','Mesh',...
'Position',[315,180,70,25]);
hcontour = uicontrol('Style','pushbutton',...
'String','Countour',...
'Position',[315,135,70,25]);
htext = uicontrol('Style','text','String','Select Data',...
'Position',[325,90,60,15]);
hpopup = uicontrol('Style','popupmenu',...
'String',{'Peaks','Membrane','Sinc'},...
'Position',[300,50,100,25]);
ha = axes('Units','Pixels','Position',[50,60,200,185]);
align([hsurf,hmesh,hcontour,htext,hpopup],'Center','None');

% Create the data to plot
peaks_data = peaks(35);
membrane_data = membrane;
[x,y] = meshgrid(-8:.5:8);
r = sqrt(x.^2+y.^2) + eps;
sinc_data = sin(r)./r;

% Initialize the GUI.
% Change units to normalized so components resize
% automatically.
set([f,hsurf,hmesh,hcontour,htext,hpopup],...
'Units','normalized');
%Create a plot in the axes.
current_data = peaks_data;
surf(current_data);
% Assign the GUI a name to appear in the window title.
set(f,'Name','Simple GUI')
% Move the GUI to the center of the screen.
movegui(f,'center')
% Make the GUI visible.
set(f,'Visible','on');

end

執行結果如下圖:

(編譯及圖示摘自mathworks.com)

不過,執行看看,按鍵時並沒有動靜,是不是錯了呢?

沒有留言:

張貼留言