问题
I am searching for a function that is notified when a MATLAB figure moves, i.e. when the figure changes its position.
In MATLAB since the beginning there was the callback which triggers when a figure has been "resized", but this doesn't help.
Any ideas or even solution?
Regards, Domenico
回答1:
Neither the newer 'SizeChangedFcn' callback or the no-longer-recommended 'ResizeFcn' callback appear to respond to movements of the figure, only resizing. One solution, as suggested by excaza in a comment, is to create a property listener, which ties a callback to a change in a given object property. For example:
hFigure = figure(...); % Create a figure
hListener = addlistener(hFigure, 'Position', 'PostSet', @your_fcn);
And your_fcn
will be a function you create which will perform whatever actions you want taken when the figure is moved. This function should be written to accept at least 2 arguments: a handle to the object invoking the callback and a structure of event data (often empty). For example:
function your_fcn(hSource, eventData)
% Your code ...
end
回答2:
Edited 06/08/2017
Don't use my initial solution in the first two paragraphs. It doesn't work.
Don't bother to find a callback function regarding triggering by the move of your figure window. Try use this callback WindowButtonUpFcn, which executes when you release the mouse button, after having pressed the mouse button in the figure.
The approach is then very straightforward. Simply implement a function in "WindowButtonUpFcn" windows callback that detects the change of first two elements in Position
property in your figure.
New approach
I tested myself. Like it's mentioned by @Domenico, my initial approach doesn't work. So, I looked around and searched for a similar solution. I finally found it on this post from undocumentedmatlab.
Basically, you have to be able to access callbacks in Java control to trigger a proper event.
Consider the following implementation
a = figure;
pause(0.2) % Wait for the figure construction complete.
jFig = get(a, 'JavaFrame'); % get JavaFrame. You might see some warnings.
jWindow = jFig.fHG2Client.getWindow; % before 2011a it could be `jFig.fFigureClient.getWindow`. Sorry I cannot test.
jbh = handle(jWindow,'CallbackProperties'); % Prevent memory leak
set(jbh,'ComponentMovedCallback',{@(~,~)(fprintf('Check\n'))});
After testing, it works on 2014b and up. I hope it's useful for someone.
来源:https://stackoverflow.com/questions/44209576/matlab-figure-callback-move