Adjust Axis Limit by Callback Function

8 vues (au cours des 30 derniers jours)
Jyun-you Liou
Jyun-you Liou le 9 Août 2016
Modifié(e) : Walter Roberson le 10 Août 2016
I am designing a small GUI to allow users to press any key to quickly move xlim range to the next page. However, I found, in certain conditions, MATLAB only allows me to use key-press once unless I manually click the figure again. Here is the example code
f= figure('KeyPressFcn',@(~,~) xlim(get(gca,'XLim') + 10));
plot(rand(100,1));
L = legend('Sample signal');
Now when I press any key, the axis moves by 10
However, if I right click the legend (L), open its default UIContextMenu, only the first key-press moves the axes. The second & third strokes do not even trigger the Callback function.
This is very different if the Callback function is not trying to move axes limits. For example,
f= figure('KeyPressFcn',@(~,~) disp(clock));
plot(rand(100,1));
L = legend('Sample signal');
Now right clicking the legend does not affect the Callback function at all. My MATLAB is 2015b. Does anyone have the same problem?

Réponses (1)

Walter Roberson
Walter Roberson le 9 Août 2016
The answer is easy if you
Take it logically
I'd like to help you in your struggle
To be free
There must be fifty ways
To leave your axes
You Just click on the back, Jack
Make a new pan, Stan
You don't need a ploy, Roy
Just get yourself free
Drop on the bus, Gus
You don't need to discuss much
Just click on the key, Lee
And get yourself free
  3 commentaires
Walter Roberson
Walter Roberson le 9 Août 2016
You left your axes. gca() no longer refers to what you think it should. You should rarely use gca in callbacks; you should use something derived from the hObject parameter or you should use a known handle or you should findobj() to get the right handle.
gca() can change between lines of code (e.g., debugger; or timer objects; and some callbacks can interrupt other callbacks) so you should always supply explicit axes to graphics calls or explicit Parent objects for graphics calls.
Jyun-you Liou
Jyun-you Liou le 9 Août 2016
Modifié(e) : Walter Roberson le 10 Août 2016
No, I used the code as an example and in my full code, it does not use gca at all. Try this one, you will see the same problem.
f = figure;
ax = axes;
f.KeyPressFcn = @(~,~) xlim(ax, ax.XLim + 10);
plot(rand(100,1));
L = legend('Sample signal');
Try to right click the legend once. Then the hotkey will only work once, not continuously.
Interestingly, if you just delete the legend, the hotkey can work continuously again

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by