views:

27

answers:

1

I'm trying to implement a line drawn in an axes, that when clicked on will follow the mouse so long as the button is down, and when the button is released the line will stop following. In short, reposition a line on a graph to a new position based on click and drag.

I've been able to get up the point of having the line follow the mouse pointer, the issue is getting the WindowButtonUpFcn to have the line stop following the mouse. I.e. How can I turn WindowButtonMotionFcn off?

Here is the code. It's rough because it's only a mini test program, so don't criticize too much.

function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    x = 0:.1:10;
    y = zeros(size(x))+.5;
    line(x,y, 'Tag', 'newLine');
    set(findobj('Tag', 'newLine'),'ButtonDownFcn',@button_down)
end

function button_down(src,evnt)
% src - the object that is the source of the event
% evnt - empty for this property
 set(src,'Selected','on')
 set(gcf, 'WindowButtonMotionFcn', @button_motion);
end   

function button_motion(src, evnt)
 h = findobj('Tag', 'axes1');
 pos = get(h, 'CurrentPoint');
 disp(pos);
 hndl = findobj('Tag', 'newLine');
    delete(hndl);
    x = 0:.1:10;
    y = zeros(size(x))+pos(3);    
    line(x,y, 'Tag', 'newLine');
    set(gcf, 'WindowButtonUpFcn', @button_up);
end

function button_up(src, evnt)
    %What to do here?    
end
+2  A: 

Here are a few tips:

  • Instead of deleting and replotting the line in your button_motion function, you should use the SET command to modify the 'XData' and 'YData' properties of the line object with the new position of the line. This will make for smoother animation.

  • You should move this line:

    set(gcf, 'WindowButtonUpFcn', @button_up);
    

    from button_motion to button_down.

  • In your button_motion function, you should add a drawnow call to the end to force the plot to update immediately and most importantly to give the button_up function a place where it can interrupt button_motion.

  • In your button_up function, simply set the 'WindowButtonMotionFcn' and 'WindowButtonUpFcn' properties of the figure to [] and the 'Selected' property of the line to 'off'.

gnovice
That worked out very well, thank you gnovice.
Michael
@Michael: Glad to help. Incidentally, you can mark an answer on one of your questions as the "accepted" answer by clicking the check mark under the score on the left of the answer. You can check [here](http://meta.stackoverflow.com/questions/5234/how-does-accepting-an-answer-work) for more info about how accepted answers work.
gnovice
+1 for complete solution and to compensate for lack of acceptance.
Jonas

related questions