Attach click-event to Figure

39 views (last 30 days)
Oliver Köhn
Oliver Köhn on 18 Aug 2018
Edited: Brian Wolin on 1 May 2019
I want to update a Figure in a loop and attach a mouse-click-event. The following code works fine:
Function:
function OnMouse(hObject,~)
axes_handle = gca;
pt = get(axes_handle, 'CurrentPoint');
clicked_x=pt(1,1)
clicked_y=pt(1,2)
Main:
im = rand(500,500);
f=figure(1);
set(f,'WindowButtonDownFcn',@mytestcallback)
imshow(im)
But if I update the figure in a loop, the click is (nearly) never detected:
for i = 1:100
im = rand(500,500);
f=figure(1);
set(f,'WindowButtonDownFcn',@mytestcallback)
imshow(im)
%pause(1)
%pause(0.001)
end
Including a pause of 0.5 seconds solves this problem, but I cannot afford to make pause-time > 5 ms. How can I update my figure through a loop and attach a click-event which always will be detected?

Answers (1)

Walter Roberson
Walter Roberson on 18 Aug 2018
f=figure(1);
set(f,'WindowButtonDownFcn',@mytestcallback)
for i = 1:100
im = rand(500,500);
imshow(im)
drawnow(); %allows display to update _and_ allows button callback to be processed
end
  1 Comment
Brian Wolin
Brian Wolin on 1 May 2019
Edited: Brian Wolin on 1 May 2019
I found that when running Walter's code, I get unusual behavior of when the callback executes or not. When clicking on the image, the callback executes maybe 25% of the time. When clicking inside the figure, but outside the image, the callback executes every time.
Any ideas why this might be the case and/or how to ensure the callback executes every time when clicking on the image/axes?
Here is my specific the callback function code, but I don't think this part matters for the behavior I describe.
function mytestcallback(src,~)
pt = get(gca,'CurrentPoint');
fprintf('Clicked: %d %d\n', pt(1,1),pt(1,2));
end
Edit: Also note that this behavior only manifests while the loop is running. Afterwards, clicking on the image is just as reliable as clicking elsewhere.

Sign in to comment.

Categories

Find more on Environment and Settings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!