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

2 Ansichten (letzte 30 Tage)
Daniel
Daniel am 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?

Antworten (1)

Arabarra
Arabarra am 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 Kommentare
Arabarra
Arabarra am 1 Mär. 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 am 30 Jun. 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!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Interactive Control and Callbacks finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by