4.94444

4.9 | 18 ratings Rate this file 391 downloads (last 30 days) File Size: 32.23 KB File ID: #14317

FindJObj - find java handles of Matlab graphic objects

by Yair Altman

 

17 Mar 2007 (Updated 27 Oct 2009)

Code covered by BSD License  

Find java objects contained within a specified java container or Matlab GUI handle

Download Now | Watch this File

File Information
Description

Find all java objects contained within a java container or Matlab GUI handle

If no output parameter is specified, then an interactive GUI window will be displayed with a tree-view of all container components, their properties and callbacks.

Syntax:
[handles,levels,parentIds,listing] = findjobj(container,'PropName',PropValue(s),...)
 
Inputs:
- container - optional GUI handle. If unsupplied then current figure will be used
- 'PropName',PropValue - optional list of property pairs (case insensitive). PropName may also be named -PropName
- - 'position' - filter results based on those elements that contain the specified X,Y position or a java element
- - - Note: specify a Matlab position (X,Y = pixels from bottom left corner), not a java one
- - 'size' - filter results based on those elements that have the specified W,H (in pixels)
- - 'class' - filter results based on those elements that contain the substring (or java class) PropValue
- - - Note: filtering is case insensitive and relies on regexp, so you can pass wildcards etc.
- - 'property' - filter results based on elements that possess the specified case-insensitive property string or have property values in cell array format: {'propName', 'propValue'}. Example: findjobj(...,'property', {'Text','click me'})
- - 'depth' - filter results based on specified depth. 0=top-level, Inf=all levels (default=Inf)
- - 'flat' - same as: 'depth',0
- - 'not' - negates the following filter: 'not','class','c' returns all elements EXCEPT those with class 'c'
- - 'persist' - persist figure components information, allowing much faster results for subsequent invocations
- - 'print' - display all java elements in a hierarchical list
- - - Note1: optional PropValue of element index or handle to java container
- - - Note2: normally this option would be placed last, after all filtering is complete.
- - 'list' - same as 'print'
 
Outputs:
- handles - list of handles to java elements
- levels - list of corresponding hierarchy level of the java elements (top=0)
- parentIds - list of indexes (in unfiltered handles) of the parent container of the corresponding java element
- listing - results of 'print'/'list' options (empty if 'print'/'list' were unspecified)

Examples:
>> handles=findjobj; %get list of all java elements in current fig (inc. menus, toolbars, ...)
>> findjobj('print'); %list all java elements in current figure
>> findjobj('print',6); %list all java elements in current fig, contained within 6th element
>> handles=findjobj(hButton); %hButton is a matlab button
>> handles=findjobj(gcf,'position',getpixelposition(hButton,1)); %as above but also return hButton's panel
>> handles=findjobj(hButton,'persist'); %as above, persist info for future reuse
>> handles=findjobj('class','pushbutton'); %get all pushbuttons in current figure
>> handles=findjobj('class','pushbutton','position',123,456); %get all pushbuttons at the specified position
>> handles=findjobj(gcf,'class','pushbutton','size',23,15); %get all pushbuttons with the specified size
>> handles=findjobj('property','Text','not','class','button'); %get all non-button elements with 'text' property
>> handles=findjobj('-property',{'Text','click me'}); %get all elements with 'text' property = 'click me'
 
Sample usage:
>> hButton = uicontrol('string','click me');
>> jButton = findjobj(hButton,'nomenu'); % or: jButton = findjobj('property',{'Text','click me'});
>> jButton.setFlyOverAppearance(1);
>> jButton.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.HAND_CURSOR));
>> set(jButton,'FocusGainedCallback',@myMatlabFunction); % some 30 callback points available...
>> jButton.get; % list all changeable properties...

>> hEditbox = uicontrol('style',edit');
>> jEditbox = findjobj(hEditbox,'nomenu');
>> jEditbox.setCaretColor(java.awt.Color.red);
>> jEditbox.KeyTypedCallback = @myCallbackFunc; % many more callbacks where this came from...
>> jEdit.requestFocus;
 
Known issues/limitations:
- Cannot currently process multiple container objects - just one at a time
- Initial processing is a bit slow when the figure is laden with many UI components (so better use 'persist')
- Passing a container Matlab handle is currently found by position+size: should find a better way to do this
- Matlab uipanels are not implemented as simple java panels, and so they can't be found using this utility
- Labels have a write-only text property in java, so they can't be found using the 'property',{'Text','string'} notation
 
Warning:
This code heavily relies on undocumented and unsupported Matlab functionality. It works on Matlab 7+, but use at your own risk!
 
Bugs and suggestions:
Please send to Yair Altman (altmany at gmail dot com)

Change log: see bottom of this page

See also:
java, handle, findobj, findall

Acknowledgements
This submission has inspired the following:
enable/disable figure, statusbar, setDesktopVisibility, GetJFrame - Retrieves a figure's underlying Java frame, UIINSPECT - display methods/properties/callbacks of an object, Virtual Tackball
MATLAB release MATLAB 7.1.0 (R14SP3)
Other requirements Java should be enabled (duh!) Works on Matlab 7.1+ (reportedly also works on Matlab 7.0 but this is untested)
Zip File Content  
Other Files findjobj.m,
license.txt
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (38)
31 Mar 2007 Mikhail Poda Razumtsev

It is the best piece of code on Matlab/Java I have ever seen in Matlab Central. I am very grateful to the author for sharing his knowledge.

15 Jun 2007 YP P

On MATLAB Version 7.0.4.365 (R14) Service Pack 2 I get following error when findjobj is run (with and without arguments)

>>finjobj
??? findjobj: Function name must be a string.

18 Jun 2007 YP P

Hello Yair!
Sorry for typing mistake in the post. The matlab command issued is "findjobj" and not "finjobj". I have not renamed the file. The file name is kept "findjobj.m" only. I ensure that script is run by setting breakpoints in the m-file.
So here I restate the problem.
If I issue the command, the figure window is created and I get following error message

>> findjobj
findjobj
??? findjobj: Function name must be a string.

If I set breakpoint for error,the error is reported at line 234 of the code. The value of error variable is

K>> err

err =

message: 'findjobj: Function name must be a string.'
identifier:'MATLAB:cellfun:InvalidFirstInput'

The Java version is

Java 1.5.0 with Sun Microsystems Inc. Java HotSpot(TM) Client VM (mixed mode)

with regards,
YP
--

18 Jun 2007 Yair Altman

the cellfun behavior has changed in Matlab 7.1 - unfortunately FINDJOBJ relies on the new behavior, so you must have version 7.1+ to run. Sorry about the confusion...

10 Nov 2007 Bob W

This is interesting, would it be easy to organize the objects the way as they are thought of in the Child/Parent as the handle graphics user would see them?

12 Nov 2007 Yair Altman

Bob - the bottom tree branch that FindJObj displays is the Handle Graphics hierarchy - only the top branch is the Java hierarchy. If you don't see it, perhaps you're not using the latest version of FindJObj.

06 Jan 2008 Dennis Olly

Using Matlab 7.5 (R2007b) and doing

1 hSlider = uicontrol('style','slider' );
2 jSlider = findjobj(hSlider);
3 jSlider.AdjustmentValueChangedCallback = @FollowSliceSlider_Callback;

I get:
No public field AdjustmentValueChangedCallback exists for class handle

Using:

set(jSlider,
'AdjustmentValueChangedCallback', @FollowSliceSlider_Callback );

I get no error, but the callback function is never reached.

Am I missing something here?
Thanks for any help
Dennis

06 Jan 2008 Dennis Olly

I found out that

jSlider = findjobj(hSlider)
ans = <1x0>

eventhough just doing

findjobj

lists all java-objects including the slider.
Also, when just using the Command Window, it works find: I can create figure with a slider with a callback that continuously calls an .m file.

Dennis

08 Jan 2008 Yair Altman

Thanks for your feedback Dennis.

Please ensure you're using the latest version of FindJObj (currently dating 2007-11-13). Also, when calling findjobj immediately after creating a UI control, you must let the Matlab/Java engine time to fully render the control. This can be done with a simple drawnow command, possibly followed by a small pause(0.01).

Yair

08 Jan 2008 Dennis Olly

Thanks for the reply, Yair!

I am using: % $Revision: 1.9 $ $Date: 2007/08/14 23:03:04 $ which is the version I get when clicking the .m button on Mathworks (this page). Is there indeed I later version?

Nevertheless, you provided the solution saying the control has to be rendered. I created both the uicontrol AND the javacallback in the OpeningFcn.
I left the creation of the uicontrol in place but now I moved the below lines of code to the OutputFcn (not sure if that's a proper place for such purposes though):

jSlider = findjobj( handles.sliceSlider );
drawnow;
jSlider.AdjustmentValueChangedCallback = {@FollowSliceSliderCallback,guidata(gcbo)};

Now it works perfectly. Thanks again!
Dennis

01 Jul 2008 Peter Li

Is it just me or does everyone who uses this script have problem on initialization.

Whenever start my own script which uses findjobj, "it" scrolls through the top menu ('file', 'edit','view','insert',...'help'). This is a little annoying

24 Jul 2008 Yair Altman

Peter - all you need to do to prevent scanning the menu-bar is to add the '-nomenu' option. For example: jObj=findjobj(hObj,'-nomenu'); Unfortunately, I could not find a way to scan the menu-bar without actually activating all menu options.

20 Aug 2008 Jack Zheng

a great piece of work! thanks!

Yair, is that possible for you to make it compatible with 08a? it causes a bunch of thread error/warning in 08a.

thank you!

21 Aug 2008 Johnny Smith

I guess, ln 257 should be

set(0,'ShowHiddenHandles','on');

instead of

set(0,'ShowHiddenHandles','off');

thanks!

20 Nov 2008 Jesse Hopkins

Running this in R2008a brings up the warning:
Warning: figure JavaFrame property will be obsoleted in a future release. For more information see the JavaFrame resource on
the MathWorks Web site.
> In findjobj>getRootPanel at 266
  In findjobj at 164

16 Dec 2008 Yair Altman

The R2008 warnings can be eliminated by typing:

warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
warning('off','MATLAB:uitreenode:MigratingFunction');

I'll add it to a new version soon, but you can simply use this in your startup file or your Matlab Command Window.
Yair

10 Jan 2009 ucd puri

HI All, One more stupid question if you dnt mind. I am an intermidiate user of matlab, and learning more. I did not exactly understood the difference between
1) jControl function
2) findjObj function, and
3) uiComponent function.
Regards n Thanks for help. Tanuj

10 Jan 2009 ucd puri

I implemented this function Dennis's way. it works perfect. Thanl all. but i did not understand how did you figured out AdjustmentValueChangedCallback attribute in line below

jSlider.AdjustmentValueChangedCallback = {@FollowSliceSliderCallback,guidata(gcbo)};

Which all other attributes i can use with jSlider.(.....)
and how to find ot about them.
Regards n Thanks for tips
Tanuj

12 Jan 2009 Yair Altman

ucd puri - jControl and uiComponent are simply Matlab functions that enable easy access and usage of Java controls, which in general are more powerful than the basic Matlab controls. The FindJObj function is useful for finding the handle of a Java control within a Matlab figure, similarly to Matlab's basic findobj function.

Java control functionality can be googled (e.g., "java jslider") , or you can read any good book or online tutorial about Java Swing (e.g., java.sun.com/docs/books/tutorial/uiswing/components/). Alternately, you can use my uiInspect submission on the Matlab File Exchange to see exactly which properties/methods/callbacks are available for any component (Java, Matlab or COM) - http://www.mathworks.com/matlabcentral/fileexchange/17935

Yair Altman

17 Jan 2009 ucd puri

thanks

20 Feb 2009 Sebastian Hölz

Info for MATLAB 7.5.
An inconsistency in uitreenode.m (%MATLAB%\toolbox\matlab\uitools\uitreenode.m) prevents "findjobj" to work properly. You have to change the first line in "uitreenode.m" from ...

  function node = uitreenode(value, string, icon, isLeaf)

... to ...
  function node = uitreenode(dummy,value, string, icon, isLeaf)

... , then everything initializes just fine.

After fixing that, it's SWEET! I've just spend hours and hours writing down the hirarchy of objects and was just starting to think, how nice it would be to have everything at hand in "file"-browser ... well, you know it: it's all on the FEX, ... somewhere ...

Thanks,

Sebastian

24 Feb 2009 Sebastian Hölz

Another suggestion (valid for Matlab 7.5):

If you want to inspect the Editor-container, you will need to change lines 175-176 from

origContainer = container;
contentSize = [container.getWidth, container.getHeight];

to

origContainer = container;
if strcmp(container.getName,'Editor');
   container=container.getInternalFrame;
end
contentSize = [container.getWidth, container.getHeight];

Sebastian

24 Feb 2009 Jveer  
24 Feb 2009 Jveer

brilliant!

25 Feb 2009 USTC ÁÔ

Great work!

02 Mar 2009 Husam Aldahiyat  
27 Mar 2009 Matthias Höller

Awesome tool to find the underlying java objects of MATLAB objects! Works great!

30 Mar 2009 Dennis Olly

ucd puri,

> but i did not understand how did you figured out
> AdjustmentValueChangedCallback attribute in line below

I just used findjobj itself:

hSlider = uicontrol('style','slider' );
findjobj( hSlider )

Dennis

btw: did I mention findjobj is excellent !?

22 May 2009 Qun HAN

Great work, Yair! I have refferenced it in my spaces.
Only one suggestion: To be compatible with future versions of ML, the use of "JavaFrame" in your function should be avoid. The "JavaFrame" is a com.mathworks.hg.peer.FigurePeer Object, it can be easily obtained using a JAVA approach instead of the get(hfig,'JavaFrame'). For example, you can get if from the mde's Client.

03 Jul 2009 Leonardo Glavina

Great file! i just have one doubt using it: if I can chance the order of some structures. I have some check boxes and using 'tab' to select them is completely out of order, and using this function I found that it's following the specific order that is on the tree.

So, can I change the place of my tree's items?

thanks for the code

05 Jul 2009 Yair Altman

@Leonardo - FindJObj does not enable modifying the displayed object hierarchy - perhaps I will add this feature in a future version. You need to update the hierarchy outside FindJObj and then click on the <Refresh Tree> button.

21 Jul 2009 Jesse Hopkins

I've been using this file for about a year now (great work Yair!), and a very weird issue has crept up now that I've upgraded from R2007b to R2008b.

What happens to me is that I have a few custom java-objects instantiated (they are a modified version of the java-swing table), with userdata and function callbacks associated with them via calls like: set(myTableObj,'MouseReleasedCallback',@callbackfcn);
set(myTableObj,'userdata',data);

After findjobj returns, all of the userdata and callbacks have been cleared out. I've stepped through findjobj line by line, and cannot find a culprit. In fact, when I get to the "return" line on 279, the userdata and function callbacks are still properly associated with the java-objects. However, once findjobj returns, all userdata and function callbacks of my java-objects are cleared to an empty matrix.

Any thoughts on this?

21 Jul 2009 Jesse Hopkins

I've actually solved my problem. After reading this page: http://undocumentedmatlab.com/blog/uicontrol-callbacks/,
I tried changing the way I set the callbacks. Before, I set the callbacks directly on the java-object. However, when I used the handle() function and then set the callbacks the problem disappears.

In summary:
before:
set(myJavaObject,'MouseReleasedCallback',@callbackfcn);

now:
myHandle = handle(myJavaObject,'CallbackProperties');
set(myHandle,'MouseReleasedCallback,@callbackfcn)

02 Aug 2009 Boris  
07 Aug 2009 Saidul Hasnan

Why do I get this error whenever i tried findjobj;

??? findjobj: Undefined function or variable "jcb".

I have the latest version of findjobj file.

11 Aug 2009 Patrick

I made a slider using GUIDE; its handle is hSlider.
I called jSlider = findjobj(hSlider);
I tried this with MATLAB 2007b, this worked very well, thank you.

Then I tried this with MATLAB 2009a, findjobj returned empty!
Actually, calling findjobj with any arguments all returned empty.

What did I do wrong?

29 Sep 2009 Oliver Woodford

Great function. The interactive display is a brilliant feature.

06 Nov 2009 James

thx

Please login to add a comment or rating.
Updates
04 Apr 2007

Improved performance; returned full listing results in 4th output arg; enabled partial property names & property values; automatically filtered out container panels if children also returned; fixed finding sub-menu items

19 Apr 2007

Fixed edge case of missing figure; displayed tree hierarchy in interactive GUI if no output args; workaround for figure sub-menus invisible unless clicked

23 Apr 2007

HTMLized classname tooltip; returned top-level figure Frame handle for figure container; fixed callbacks table; auto-checked newer version; fixed Matlab 7.2 compatibility issue; added HG objects tree

22 May 2007

Added 'nomenu' option for improved performance; fixed 'export handles' bug; fixed handle-finding/display bugs; "cleaner" error handling

13 Jul 2007

Fixed problems finding HG components found by J. Wagberg

03 Aug 2007

Fixed minor tagging problems with a few Java sub-classes; displayed UIClassID if text/name/tag is unavailable

15 Aug 2007

Fixed object naming relative property priorities; enabled desktop (0) container; added sanity check for illegal container arg; cleaned up warnings about special class objects

14 Nov 2007

Fixed edge case problem with class properties tooltip; used existing object icon if available; added checkbox option to hide standard callbacks

07 Feb 2009

Callbacks table fixes; better object inspection; fix update check according to new FEX website; R2008b compatibility; fixed minor bug as per Johnny Smith's comment

22 Feb 2009

Fixed compatibility problems with previous Matlab versions; updated screenshot

24 Feb 2009

Fixed update check; added dedicated labels icon; fixed description

01 Mar 2009

Indicated components visibility (& auto-collapse non-visible containers); auto-highlight selected component; fixed node icons, figure title & tree refresh; improved error handling; displayed FindJObj version update description if available

30 Mar 2009

Fixed position of some Java components; fixed properties tooltip; fixed node visibility indication

23 Apr 2009

Fixed location of popupmenus (always 20px high despite what's reported by Matlab...); fixed uiinspect processing issues; added blog link; narrower action buttons; automatic 'nomenu' for uicontrol inputs; significant performance improvement

26 May 2009

Added support for future Matlab versions that will not support JavaFrame; added sanity checks for axes items; added 'debug' input arg; increased size tolerance 1px => 2px

30 Sep 2009

Fix for Matlab 7.0 as suggested by Oliver W; minor GUI fix (classname font); fixed edge-case of missing JIDE tables

27 Oct 2009

Fixed auto-collapse of invisible container nodes; added dynamic tree tooltips & context-menu; minor fix to version-check display

Tag Activity for this File
Tag Applied By Date/Time
gui tools Yair Altman 22 Oct 2008 09:04:55
example Yair Altman 22 Oct 2008 09:04:55
handle Yair Altman 08 Feb 2009 00:52:06
java Yair Altman 08 Feb 2009 00:52:06
undocumented Yair Altman 08 Feb 2009 00:52:06
findall Yair Altman 08 Feb 2009 00:52:06
findobj Yair Altman 08 Feb 2009 00:52:06
gui Yair Altman 24 Feb 2009 11:43:45
 

MATLAB Central Terms of Use

NOTICE: Any content you submit to MATLAB Central, including personal information, is not subject to the protections which may be afforded information collected under other sections of The MathWorks, Inc. Web site. You are entirely responsible for all content that you upload, post, e-mail, transmit or otherwise make available via MATLAB Central. The MathWorks does not control the content posted by visitors to MATLAB Central and, does not guarantee the accuracy, integrity, or quality of such content. Under no circumstances will The MathWorks be liable in any way for any content not authored by The MathWorks, or any loss or damage of any kind incurred as a result of the use of any content posted, e-mailed, transmitted or otherwise made available via MATLAB Central. Read the complete Terms prior to use.

Contact us at files@mathworks.com