straits
straits

Reputation: 415

Swapping property values between objects

I have created two textboxes via annotation(.) in a figure. Most of their properties have been defined; and the callback function enables drag and drop motion in the window. I created a uicontextmenu for the boxes. On right click a list of functions can be chosen from for subsequent action.

One of the actions I am trying to add involves swapping strings between the two boxes. I need to get the string of the box I currently right-clicked, which should swap with the string in the box I subsequently left-click. Can I get advice on how to go about extending the uimenu function so that it registers the subsequent left-click?

Upvotes: 1

Views: 119

Answers (1)

Amro
Amro

Reputation: 124563

You will need to manually store the last clicked box. If you are using GUIDE to design your GUI, use the handles structure which gets passed around to callback functions. Otherwise if you programmatically generate the components, then nested callback functions have access to variables defined inside their enclosing functions.

EDIT

Here is a complete example: right-click and select "Swap" from context menu, then choose the other textbox to swap strings with (left-click). Note that I had to disable/enable the textboxes in-between the two steps to be able to fire the ButtonDownFcn (see this page for an explanation)

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

screenshot

Upvotes: 1

Related Questions