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

2 visualizzazioni (ultimi 30 giorni)
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?

Risposte (1)

Arabarra
Arabarra il 16 Feb 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 Commenti
Arabarra
Arabarra il 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 il 30 Giu 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!

Accedi per commentare.

Categorie

Scopri di più su Interactive Control and Callbacks in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by