'FocusGainedCallback' doesn't work once figure has axes 2015b

2 vues (au cours des 30 derniers jours)
Daniel
Daniel le 18 Mai 2016
I am using this article by Yair to add a 'FocusGainedCallback' onto a MATLAB figure.
The following code works correctly.
plotFigHandle = figure();
jFrame = get(plotFigHandle,'JavaFrame');
jAxis = jFrame.getAxisComponent;
set(jAxis.getComponent(0),'FocusGainedCallback', @(caller, event) disp('This works great'));
However, as soon as I add a MATLAB axis using the axes() command, the functionality stops working.
plotFigHandle = figure();
% adding axes will make this code not function
axes('Parent',plotFigHandle);
jFrame = get(plotFigHandle,'JavaFrame');
jAxis = jFrame.getAxisComponent;
set(jAxis.getComponent(0),'FocusGainedCallback', @(caller, event) disp('This works great'));
My question is how to I keep the FocusGainedCallback even after I add an axes to my MATLAB figure?

Réponses (1)

Arabarra
Arabarra le 16 Fév 2017
Hi Fabio, the code below (I've pasted it to the Yair's article you mention) did work for me in R2016b, but it's mainly created by trial and error. At least it works if a single axis is defined in the figure. In any case, if you have come across a better solution for the general case, please let me know.
Daniel
hFig = figure;
h = axes(hFig);
plot(rand(100,1),'Parent',h);
jFig = get(hFig, 'JavaFrame');
jAxis = jFig.getAxisComponent;
n = jAxis.getComponentCount;
disp(n);
jAxis.grabFocus();
drawnow; % will not work without this
n = jAxis.getComponentCount;
disp(n);
set(jAxis.getComponent(n-1),'FocusGainedCallback',@(x,y)disp('in focus'));
set(jAxis.getComponent(n-1),'FocusLostCallback',@(x,y)disp('... out'));
  2 commentaires
Arabarra
Arabarra le 1 Mar 2017
damn... just saw that it only works when the figure gains focus through direct interaction with it. If you click on the axis, the figure does gain focus, but the callback doesn't get triggered.
Nikolaus Koopmann
Nikolaus Koopmann le 30 Juin 2022
nice, thanks 1billion!
this is exactly what i needed: a callback when the chosen tab in a tiled figures window changes! works like a charm!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Interactive Control and Callbacks dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by