Get handle of clicked element in GUI

6 Ansichten (letzte 30 Tage)
Lask
Lask am 30 Jun. 2017
Kommentiert: Lask am 30 Jun. 2017
Hi people,
I'd like to know how to get the handle of the current axes I am clicking in GUI so another callback function can perform some action.
Thanks in advance.
  2 Kommentare
Adam
Adam am 30 Jun. 2017
Bearbeitet: Adam am 30 Jun. 2017
Assuming you are in some mouse click callback then you can just do
hAxes = gca;
and then do what is required with hAxes by passing it on to wherever it is wanted. I'm not putting this as an answer as I don't like suggesting anything that involves using gca in proper code, it is just the first solution that comes to my head. I assume there are better ones.
In this case though, gca should be reliable because clicking on an axes does make it the current axes (certainly as far as I am aware and from my past experience) so as long as you grab that straight away and assign it to a more reliable static handle it should behave fine.
In general though using gca is bad practice for serious code as relying on which axes happens to be the one currently in focus is brittle and prone to often surprising behaviour.
Lask
Lask am 30 Jun. 2017
That seems to fit my solution. Thanks Adam!

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Jan
Jan am 30 Jun. 2017
Bearbeitet: Jan am 30 Jun. 2017
Define a callback for the axes during the creation:
axes('ButtonDownFcn', @AxesCallback);
...
function AxesCallback(hAxes, EventData)
handles = guidata(hAxes);
handles.ClickedAxes = hAxes;
guidata(hAxes, handles);
end
Now handles.ClickedAxes contains the handle of the last clicked axes. Note that the callback is not triggered, if you click on an object in an axes, which catches click. Then either add the update of the "handles.ClickedAxes" in the callback of the object or disable the sensitivity of the objects by setting 'HitTest' to 'off'.
Another much simpler solution:
get(FigureHandle, 'CurrentAxes')
is the last axes, which has been drawn to or clicked in. Using the ButtonDownFcn has the advantage, that you could mark the axes visibly, e.g. by:
set(hAxes, 'Selected', 'on')
or by increasing the line width of the box. Then you need some additional code to deselect the former axes.
function AxesCallback(hAxes, EventData)
handles = guidata(hAxes);
set(handles.ClickedAxes, 'selected', 'off');
handles.ClickedAxes = hAxes;
guidata(hAxes, handles);
end
Initialize handles.ClickedAxes = [] in the OpeningFcn then.
  1 Kommentar
Lask
Lask am 30 Jun. 2017
I'll consider this alternative in case Adam's solution delivers surprising results. Thanks anyway Jan!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Creating, Deleting, and Querying Graphics Objects finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by