最後にクリックしたボックスを手動で保存する必要があります。GUIDE を使用して GUI を設計している場合は、handlesコールバック関数に渡される構造体を使用します。それ以外の場合、コンポーネントをプログラムで生成すると、ネストされたコールバック関数は、それらを囲む関数内で定義された変数にアクセスできます。
編集
完全な例を次に示します。右クリックしてコンテキスト メニューから [スワップ] を選択し、文字列をスワップする他のテキスト ボックスを選択します (左クリック)。ButtonDownFcn を起動できるようにするには、2 つのステップの間にあるテキスト ボックスを無効/有効にする必要があることに注意してください (説明については、このページを参照してください)。
function myTestGUI
%# create GUI
hLastBox = []; %# handle to textbox initiating swap
isFirstTime = true; %# show message box only once
h(1) = uicontrol('style','edit', 'string','1', 'position',[100 200 60 20]);
h(2) = uicontrol('style','edit', 'string','2', 'position',[400 200 60 20]);
h(3) = uicontrol('style','edit', 'string','3', 'position',[250 300 60 20]);
h(4) = uicontrol('style','edit', 'string','4', 'position',[250 100 60 20]);
%# create context menu and attach to textboxes
hCMenu = uicontextmenu;
uimenu(hCMenu, 'Label','Swap String...', 'Callback', @swapBeginCallback);
set(h, 'uicontextmenu',hCMenu)
function swapBeginCallback(hObj,ev)
%# save the handle of the textbox we right clicked on
hLastBox = gco;
%# we must disable textboxes to be able to fire the ButtonDownFcn
set(h, 'ButtonDownFcn',@swapEndCallback)
set(h, 'Enable','off')
%# show instruction to user
if isFirstTime
isFirstTime = false;
msgbox('Now select textbox you want to switch string with');
end
end
function swapEndCallback(hObj,ev)
%# re-enable textboxes, and reset ButtonDownFcn handler
set(h, 'Enable','on')
set(h, 'ButtonDownFcn',[])
%# swap strings
str = get(gcbo,'String');
set(gcbo, 'String',get(hLastBox,'String'))
set(hLastBox, 'String',str)
end
end
