Code covered by the BSD License  

Highlights from
FindJObj - find java handles of Matlab graphic objects

4.91667

4.9 | 55 ratings Rate this file 359 Downloads (last 30 days) File Size: 36.7 KB File ID: #14317
image thumbnail

FindJObj - find java handles of Matlab graphic objects

by

 

17 Mar 2007 (Updated )

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

| 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 case insensitive property pairs. PropName may also be named -PropName. Supported properties:
  - '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)

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;

(Many more examples in the utility's help section)
 
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 can't be found using 'property',{'Text','string'} notation

Technical description:
 * http://UndocumentedMatlab.com/blog/findjobj-find-underlying-java-object/
 * http://UndocumentedMatlab.com/blog/findjobj-gui-display-container-hierarchy/
 
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)

See also:
java, handle, findobj, findall

Acknowledgements

Uiinspect Display Methods Properties Callbacks Of An Object inspired this file.

This file inspired Copy Paste, Probability Distribution Plotter, Dynamic Search Box, Reorderable Listbox, Check Version Check For A Newer File Version On The File Exchange, Fixuilabels, Programmatically Scroll Variables Editor, Realtime Trading With Matlab Presentation Files, Regexp Builder, Figs2tabs Move Figures Into A Single Tabbed Gui, Dicom Operator Esme Process, Sim.I.Am, Set Desktop Visibility, Virtual Tackball, Uhelp, Command Window Text, Enable/Disable Figure, Get J Frame Retrieves A Figure's Underlying Java Frame, Statusbar, Manage And Dock Figures Into Group, Colorize Document Bar, Maximize, Uiinspect Display Methods Properties Callbacks Of An Object, Embeddedmethodsviewer Show Functions And Methods Within Matlab Editor, Tortoise Svn Toolbar Integration, and Graphical Wrappers.

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)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (114)
04 Apr 2014 Sara

How to put matlab on steroids! Very useful to have more control of your GUI.

06 Mar 2014 Kim

Very useful and very cool

02 Dec 2013 Yair Altman

Sebastian - perhaps the nested panels cause the reported pixel position of the mtable to be slightly different than the jtable, causing the jtable not to be found at the expected position/size. This would not surprise me since each uipanel ads a 1-2 pixel border on each side so the more uipanels that you nest the larger the probability of a position mismatch.

17 Nov 2013 Pooya89  
27 Oct 2013 Sebastian

Dear Yair;
Sorry about the confusion - my comments doesn't seem to have posted correctly.
I have used your excelent findobj on many occasions but today discovered a strange behaviour. When nesting many panels inside each, findjobj does not seem to be able to find that underlying java table handle. As a simple example:

subpanel1 = uipanel('Parent', gcf, 'units','normalized','Position',[0 0 1 1]);
subpanel2 = uipanel('Parent', subpanel1, 'units','normalized','Position',[0 0 1 1]);
subpanel3 = uipanel('Parent', subpanel2, 'units','normalized','Position',[0 0 1 1]);
subpanel4 = uipanel('Parent', subpanel3, 'units','normalized','Position',[0 0 1 1]);

% This works correctly
mTable= uitable('Parent',subpanel3,'Units','normalized',...
'Position',[0.02 0.14 0.96 0.84]);

jHandle = findjobj(mTable)

% This does not work - findjobj returns empty
mTable2= uitable('Parent',subpanel4,'Units','normalized',...
'Position',[0.02 0.14 0.96 0.84]);

jHandle2 = findjobj(mTable2)

Any thoughts?
Best regards
Sebastian

27 Oct 2013 Sebastian  
27 Oct 2013 Sebastian

Dear Yair;
Adding to my previous comment, I have noticed that findjobj(gcf,'class','uitable') correctly finds the handle also in the later case. The trouble with this in my case is that I have several tables in the GUI and this returns a vector of all tables and all I have found no way to distinguish between these to extract the particular one that I want.
Best Regards
Sebastian

24 Oct 2013 Andrew Bytheway

Yair - I've found one issue that should be resolved:

If after calling findjobj with the "persist" option the main GUI window is moved, then subsequent calls to findjobj will fail to return the object handle. This is because the container (or pContainer) is one of the persisted variables, and the processPositionArgs function uses container.getX and container.getY to filter the java objects.

To make matters worse, a subsequent call to findjobj without the "persist" argument does not disable persistence. The way I read the code, the only way to force findjobj to recalculate all of the positions is to call it first on a separate figure with the "persist" argument and then on the desired figure without the "persist" argument. (I haven't tested this so I could be wrong). I think this could be fixed fairly easily with a few code changes around line 237.

The complete fix will be a little more involved though.

It looks like others (i.e. Kesh Ikuma) have had similar issues. I've rated this as a 4 for an awesome tool. This would be a 5 if the "persist" option could be made to reset if the figure is moved or resized.

16 Oct 2013 Daniel  
11 Oct 2013 Kesh Ikuma

Yair - What do you think of adding a flag 'repersist' (or whatever name you think best describes the feature) to rescan the container to update the persistent data?

I run into a problem by calling findjobj(...,'persist') multiple times as the GUI is constructed. I've modified line 240 to

"if isequal(pContainer,container) && ~paramSupplied(varargin,'persist')"

for the time being but would love to have an official feature to account for this case.

Thanks, Kesh

03 Oct 2013 Yair Altman

@Dan - maybe, it should be simple enough to test

03 Oct 2013 Dan K

Yair,
Thanks for the feedback.... Would it work if I were to undock the figure, find the object, and then re-dock? Or would the act of re-docking the figure change the handles?

02 Oct 2013 Yair Altman

@Dan K - This is correct: findjobj is not expected to work for docked figures since the Java components hierarchy in this case is entirely different - a docked figure is merely an internal panel within the Desktop window, not a standalone Frame/window as in the undocked case.

Maybe one day I'll upload a fix for this, but I don't expect it in the near term.

02 Oct 2013 Dan K

Yair,
Thank you for the great utility. One item I noticed. It doesn't work with figures that are docked. If I use:

hButton = uicontrol('string','click me');
jButton = findjobj(hButton,'nomenu');

On an undocked figure, it finds the handle, but if I dock the figure, it returns an empty matrix. Thoughts?

02 Oct 2013 Vassilis

Thank you Yair!
By using this function I was able to work around a problem in some code I am writing, that has been bugging me for days!

10 Sep 2013 Yair Altman

@Satwik - you can tell findjobj to search by position and/or class, not just size - read the findjobj help.

In my experience, the position sometimes changes by a few pixels on different systems but the size remains the same - it's odd that you find that size changes.

09 Sep 2013 Satwik

First off, thanks for all the great submissions. They greatly extend the utility of MATLAB GUIs.

I ran into a strange problem using findjobj, which has its origin upstream, but comes from findjobj finding elements by position.

On a GUI created by a colleague, findjobj works perfectly on windows machines, but fails intermittently on linux.

I have traced this back to the fact that the size detected seems to change sometimes in linux, despite the fact that these are hardcoded in the gui. For example the height component of contentSize in getRootPanel changes and this causes the baseDeltas for the height to go out of the accepted range.

I realize this is likely not an issue with findjobj, but I was wondering if you had run into this issue before and/or could offer some suggestions on how to ensure reliable detection of gui size.

11 Jun 2013 Matthew  
04 Jun 2013 Ricardo V. R.

Ok thanks, that was it.

If I change any uicontrol's (edit box) properties after I've changed its pointer (I have done a calendar of which days are edit boxes and I want its hover pointer set to default arrow and not |), it seems to malfunction the setCursor.

What I want to know is if an uicontrol's propeties are being constantly changed do their setCursor property reset to default or I just have to change it once.
Summing up, what I want is to change a calendar's edit boxes days pointer to the default arrow.

Thank you.

04 Jun 2013 Yair Altman

Ricardo - the button is probably not visible at the time that you call findjobj. It has to be visible to work

03 Jun 2013 Ricardo V. R.

First of all, thank you for all your contributions. I've read you a lot.

I can't get the fidjobj working on R2012b, it returns me always []

e.g.

>> hButton = uicontrol('string', 'Hello');
jButton = findjobj(hButton);
jButton

jButton =

[]

29 May 2013 ismirbrille

UPDATE:
It works now. I had to re-set the callback function after b = findjobj(handle2).
It seems that the second call to findjobj, deactivates the callbacks for object a.

Thanks for your help.

29 May 2013 Yair Altman

There is no real reason that it should not work. Perhaps one of the tables was not visible at the time that findjobj() was called. place a breakpoint on both lines to check whether this is in fact the case.

29 May 2013 ismirbrille

Thanks for your answer. I don't mean vectorization.

I have problems using
a = findjobj(handle1)
b = findjobj(handle2)

Both calls were made from different functions, handle1 and handle2 are different tables in the same GUI. call_1 XOR call_2 works fine. Any suggestions?

29 May 2013 Yair Altman

@ismirbrille - findjobj only works on a single component at a time, it is not vectorized. To get the underlying Java objects of multiple Matlab controls you would need to call findjobj separately for each of the controls.

29 May 2013 ismirbrille

@Yair Altman - Thank you for this code, very useful, good job!
Do you currently work at a version which supports multiple container objects?
I have to use 2 tables with java functionality at a time.

23 May 2013 Martin Lechner

Sad, that Matlab doesn't support modern GUI development.
Thanks for the great work to overcome the limitations!

23 May 2013 Martin Lechner  
27 Feb 2013 Katana13

Ok, Thank you!!!! Yair Altman

26 Feb 2013 Yair Altman

@Katana13 - Java customizations are not saved in FIG files. See here for a discussion and workaround: http://undocumentedmatlab.com/blog/figure-toolbar-components/#comment-13897

26 Feb 2013 Katana13

Extremely useful toolbox for creating GUIs. I don't know if it's a limitation (Matlab R2012a). Example:
h = figure('Menubar','none', 'Toolbar','none','Tag','figure');
str = ' je suis vraiment le plus beau de la planete terrrer de la foucv oeufe fz ozfz efz fvousf zefzf ouvzfz ozfz fouz fz fzo ufzf zouz fozufozf uzo fzoufzo fuziofz fzofiuzfoiz fouzfo ';
hEdit = uicontrol('Parent',h, 'Style','edit', 'FontSize',9, ...
'Min',0, 'Max',2, 'HorizontalAlignment','left', ...
'Units','normalized', 'Position',[0 0 1 1], ...
'String',str,'Tag','hEdit');

%# enable horizontal scrolling
jEdit = findjobj(hEdit);
jEditbox = jEdit.getViewport().getComponent(0);
jEditbox.setWrapping(false); %# turn off word-wrapping
jEditbox.setEditable(false); %# non-editable
set(jEdit,'HorizontalScrollBarPolicy',30); %# HORIZONTAL_SCROLLBAR_AS_NEEDED

%# maintain horizontal scrollbar policy which reverts back on component resize
hjEdit = handle(jEdit,'CallbackProperties');
set(hjEdit, 'ComponentResizedCallback','set(gcbo,''HorizontalScrollBarPolicy'',30)')

saveas(h,'test','fig');

No problem, if you directly run the script (horizontal + vertical scrollbar available). But if you launch the saved file : 'test.fig', the horizontal scrollbar becomes unavailable.

Thanks

22 Feb 2013 Raz Shimoni  
22 Feb 2013 Raz Shimoni

Extremely useful function that helped me alot. Just excellent!

22 Feb 2013 Fred Holt

Thanks for the support!

I used findjobj to update a table position, and it works well, but there are some rendering artifacts as a result of the update - hopefully seen here: http://imgur.com/uJYps3Y .
Apologies, as I am not too familiar with java, but a simple drawnow doesn't seem to help.

19 Feb 2013 Yair Altman

@Georgios - the control must be visible for findjobj to work. You can make the figure visible in the OpenFcn using the commands
set(hObject,'Visible','on'); drawnow;

If you don't want the figure to physically appear onscreen, you can set its position to [-300,-300,200,200] or some other off-screen location. The figure will become visible but hidden... You can later move it to your screen center in the OutputFcn.

19 Feb 2013 Voulgarakis Georgios

Hallo and congrats for the excellent code!

My issue is the following:
I need to use the findjobj, before the uicontrol is properly rendered.
Is there a way to achieve this?

(I need to set some attributes of the uicotnrol, in the OpenFcn function of the GUI.) Which means that the uicontrols are not yet rendered.

18 Feb 2013 Yair Altman

@Echidna - findjobj works out-of-the-box and does not require any additional installation or file, including in deployed (compiled) apps. So I am 99.99% certain that the problem is in your code. It could be due to one of several possibilities:

1) perhaps your editbox has not become visible onscreen long enough before your call to findjobj. Findjobj must have the control visible before it can find its underlying Java component. Place calls to pause(0.1) and drawnow before your call to findjobj, to ensure that this is indeed so.

2) maybe your callback function became invalid for some reason. For example, if you modify the editbox from multi-line to single-line or other similar changes, then the underlying Java control may have changed, forcing you to re-set your callback

3) maybe your update callback is being called but runs into a bug when updating the listbox for some reason. Place debug printouts in your callback to check this.

18 Feb 2013 Echidna

This code works great when I run my GUI directly in Matlab BUT when I compile it into an executable using deploytool, it does not always work. More specifically it works the first time I change the text in the edit box, sometimes the second time but somewhere thereafter (always at a different point), it does not seem to work anymore (i.e. no update of my listbox when I type in the edit-field and some other strange stuff sometimes happens as freezing of the list box, not finding the text string even though I know it is there and such).

Is this a known bug and how can I solve this? Is there another file that I need to include in the "Shared resources and helper files" section besides the findjobj.m file which I of course have included?

04 Nov 2012 Yair Altman

@Peter - as far as I could test, the latest findjobj works correctly on R2012b. try running your two lines in a new figure and see for yourself. Perhaps in your specific GUI findjobj cannot find the slider control for some reason. One possible explanation is that the uicontrol is not fully rendered (displayed) when findjobj is being run. In this case, placing a short pause(0.05) and drawnow(), might help. Also ensure that the slider is actually displayed onscreen (Visible=on, valid Position and Value).

04 Nov 2012 Peter Corke

I've used this module successfully for many years, thanks.

With R2012b I've got problems:

jh = findjobj( slider, 'nomenu');
jh.AdjustmentValueChangedCallback = @(src,event)sliderCallbackFunc(src);

and the second line results in an error

Incorrect number of right hand side elements in dot name assignment. Missing [] around left hand side is a
likely cause.

Anybody else had related problems under R2012b.

17 Oct 2012 Alexander Kosenkov  
17 Oct 2012 Alexander Kosenkov  
26 Jul 2012 Yair Altman

@Changshun Deng - I believe that the latest version of FindJObj that I uploaded yesterday solves this issue

08 Jan 2012 Changshun Deng

Hi, I run this programe findjobj(jEditor) as http://undocumentedmatlab.com/blog/accessing-the-matlab-editor/
I can not get the objects of editor.
an error: ??? findjobj: There is no 'UserData' property in the 'javax.swing.JTable$1' class.

my matlab version is: MATLAB Version 7.4

12 Dec 2011 Martin Lechner  
22 Nov 2011 Yair Altman

@Ward - thanks - I believe that you may be right. This has no effect unless there are several overlapping/similar results in the filtering process, which is very rare. But in such rare cases, your fix would solve a problem of returning both the parent and the child handles.

22 Nov 2011 Ward

On lines 646-649 you discard the first if in the original handles the first is the parent of second. Is this correct after Args processing or should the first line be

if length(foundIdx) > 1 && isequal(handles(foundIdx(1)).java, handles(foundIdx(2)).getParent)

17 Nov 2011 David Thompson

This is a very cool tool, but I'm running into the same problem that Michael had - if I compile the code, I get a metric ton of "file is empty" messages. Everything works fine, it just gets in the way of other things I'd like to use the output window for. Any hope of an update to address this?

22 Aug 2011 Yair Altman

@HaveF - you don't need to use the 'nomenu' parameter when you specify an input handle such as hButton.

I cannot reproduce any of the issues that you report. Perhaps try to download the latest version of the utilities.

Try adding a call to drawnow and/or pause(0.1) before you call findjobj. Also, ensure that the control is actually visible (findjobj can only detect visible components).

22 Aug 2011 HaveF

seems lost something...
When I try findjobj, something strange on my machine.
>> hButton = uicontrol('string','click me'); jButton = findjobj('property',{'Text','click me'});
it's all right as I expected.
but
>> hButton = uicontrol('string','click me'); jButton = findjobj(hButton,'nomenu')
just return *ans = <1x0>*

and another thing, I am a big fun of yours.
I use setPrompt before, but when I try findjobj, my prompt disappear.
just like this:

[18:57:11]temp_proj>>
[18:57:11]temp_proj>>
[18:57:11]temp_proj>> hButton = uicontrol('string','click me');
[18:57:16]temp_proj>> jButton = findjobj('property',{'Text','click me'});
>>

22 Aug 2011 HaveF

and another thing, I am a big fun of yours.
I use setPrompt before, but when I try findjobj, my prompt disappear.
just like this:

[18:57:11]temp_proj>>
[18:57:11]temp_proj>>
[18:57:11]temp_proj>> hButton = uicontrol('string','click me');
[18:57:16]temp_proj>> jButton = findjobj('property',{'Text','click me'});
>>

09 Aug 2011 Arturo Moncada-Torres  
05 Aug 2011 Nik F

Excellent!

07 Jun 2011 Nicolas

the above code works - often ;)
sometimes it throws:

No appropriate method, property, or field getViewport for class handle.handle.

-> class handle.handle => haha

how can i assure findjobj found the table?

currently i retry on failure:

code:

function setTableSelectedCellColor(table)
%

try
jUIScrollPane = findjobj(table, 'nomenu');
jUITable = jUIScrollPane.getViewport.getView;
jUITable.setSelectionBackground(java.awt.Color(1,1,1));
jUITable.setSelectionForeground(java.awt.Color(0,0,0));
catch
setTableSelectedCellColor(table);
end

end %function

end code

02 Jun 2011 Nicolas

Fabulous!
I use it to avoid selection induced color change for a table with white background:

code:

% create the table
table = uitable( ...
'Parent', layout,...
'ColumnWidth', {100, 150}, ...
'ColumnName', {tableTitle}, ...
'RowName', [], ...
'ColumnFormat', {'char', selectionList}, ...
'ColumnEditable', [false, true],...
'Data', tableData, ...
'CellEditCallback', @selectionChanged);

% workarount to avoid seletion induced color change
jUIScrollPane = findjobj(table);
jUITable = jUIScrollPane.getViewport.getView;
jUITable.setSelectionBackground(java.awt.Color(1,1,1));
jUITable.setSelectionForeground(java.awt.Color(0,0,0));

end code

is there a way to make the findjobj command faster?

02 May 2011 Luc  
09 Apr 2011 Yair Altman

@Evzen - for some reason, you got the handle of a uitable rather than the editbox, and of course you cannot set the page URL for uitables...

Perhaps your uitable resides at the same pixel position as the editbox?

Try to place a breakpoint on the line following the call to findjobj to determine exactly which object it found.

More information on setting rich editbox contents can be found here: http://undocumentedmatlab.com/blog/rich-matlab-editbox-contents/

08 Apr 2011 Evzen Brusle

Awsome utility. Thanks for sharing, but I have a little problem and i dont resolve it. I use a code from your webpage, but it give me this error with method setPage:

No appropriate method, property, or field setPage for class
com.mathworks.hg.peer.ui.UITablePeer$22.

hEditbox = uicontrol('style','edit', 'max',5);

jScrollPane = findjobj(hEditbox);
jViewPort = jScrollPane.getViewport;
jEditbox = jViewPort.getComponent(0);
jEditbox.setPage('http://www.google.com');

17 Mar 2011 Yair Altman

@Sean - you don't need findjobj to access specific toolbar buttons - you can use the built-in findall function, as explained here: http://undocumentedmatlab.com/blog/modifying-default-toolbar-menubar-actions/

17 Mar 2011 Andrew Bytheway

This is an awesome tool. Thanks for your sharing your work Yair.

07 Dec 2010 Sean Larkin

I'm trying to use findjobj to get the java handle for a toolbar uitogglebutton. It does not find the handles for the button. When I call the function like this:
findjobj;

it finds the toolbar button. Why is this and is there a way I can modify findjobj to directly find toolbar buttons?

23 May 2010 Michael

Works super! Nevertheless, when I compile this line:
jScrollPane = findjobj(handles.editBox)
and I execute the code, I get many times the message 'File is empty' in the command line. Anyway, the code works nevertheless!? Any ideas?

Best regards!

PS: I use your tool to extract selected text from an edit box.

01 Apr 2010 Emad Hasan

Finally got it to work, thanks a lot for the updates!

30 Mar 2010 Urs

Hi Guys,

I have written the following code in _OpeningFcn(because I have used GUIDE!),

pause(0.01);
drawnow;
jb=findjobj('class','pushbutton');
drawnow;
set(jb(2), 'MousePressedCallback', @UpVertTest);
guidata(hObject, handles);
--------------------

Up to here everything works fine,

But at the end of my m file where I define the related function(UpVertTest) I have problem,
I want to have access to normal handles and do some changes, But I get this error:

??? Undefined function or method 'toDouble' for input arguments of type 'java.awt.Dimension'.

Error in ==> opaque.double at 80
dbl = toDouble(opaque_array(1));

Error in ==> guidata at 85
if isscalar(h) && ishghandle(h)

Error in ==> RatRobot_GUI4>UpVertTest at 523
handlesData=guidata(src);

this is the code I have written:

function UpVertTest(src, evnt)
% trying to access to handles
handlesData=guidata(src);

% set new initial value in GUI
set(handlesData.VerticalPosStart,'string',handlesData.initZ-handles.Step(3));drawnow;
-----------

I think there is something wrong with my function definition,
any ideas?

19 Mar 2010 Oscar Hartogensis

I used the findjobj-function as described at http://undocumentedmatlab.com/blog/customizing-listbox-editbox-scrollbars/ to disable text-wrapping and display a horizontal scroll-bar in a GUI edit-box.
Many thanks for this fabulous tool. It works like a charm.

18 Mar 2010 Jveer

after further testing, following the use of findjobj, from time to time i get the following errors:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:886)
at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:129)
at javax.swing.text.BoxView.checkRequests(BoxView.java:918)
at javax.swing.text.BoxView.getPreferredSpan(BoxView.java:528)
at javax.swing.text.html.BlockView.getPreferredSpan(BlockView.java:345)
at javax.swing.plaf.basic.BasicTextUI$RootView.getPreferredSpan(BasicTextUI.java:1342)
at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(BasicTextUI.java:908)
at javax.swing.JComponent.getPreferredSize(JComponent.java:1622)
at javax.swing.JEditorPane.getPreferredSize(JEditorPane.java:1412)
at com.mathworks.hg.peer.EditTextPeer$hgTextEditMultiline.getPreferredSize(EditTextPeer.java:864)
at javax.swing.ScrollPaneLayout.layoutContainer(ScrollPaneLayout.java:769)
at java.awt.Container.layout(Container.java:1421)
at java.awt.Container.doLayout(Container.java:1410)
at java.awt.Container.validateTree(Container.java:1507)
at java.awt.Container.validate(Container.java:1480)
at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:670)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:124)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:633)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

is there a workaround?

17 Mar 2010 Jveer

that does make sense. thank you for clarifying that.

17 Mar 2010 Yair Altman

Jveer - FindJObj *cannot* work in the GUIDE-created *_OpeningFcn because the figure is not yet visible at this time and so the Java components have still not rendered and therefore cannot be found.

Try placing your call to FindJObj *after* the figure has become visible and all the controls have completed rendering, for example by moving your FindJObj call to the *_OutputFcn function, hopefully after a call to drawnow to ensure that everything has completed rendering.

17 Mar 2010 Jveer

i'm sorry to report it still doesn't work. downloaded it today, tried it on r2009b and r2010a. frustratingly sometimes it works sometimes it doenst.

1) run from a script - it works
2) run from opening function of a GUI created using guide - doesn't work
3) run the script from #1 after #2 failed - it doesn't work!
4) reopen matlab and run #1 - works

very strange.

17 Mar 2010 Yair Altman

Patrick, Emad & Jayveer - I have yesterday uploaded a new version of FindJObj that fixes the problem you have reported.

FYI, the problem occurred due to a slightly different implementation of the Java hierarchy for Matlab figure windows. The new code should work find on all the older Matlab 7 versions *IN ADDITION* to R2010a.

As always, I am very committed to fixing such utilities, to the best of my abilities, also in upcoming Matlab releases.

17 Mar 2010 Jveer

findjobj returns [] on r2010a !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

which makes the following tutorial useless!! - http://undocumentedmatlab.com/blog/rich-matlab-editbox-contents/#EditorKit along with everything else on the website since they all depend on finjobj!

03 Mar 2010 Kusa358 Figueredo  
24 Feb 2010 Emad Hasan

I have the same problem as 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?

08 Feb 2010 Yair Altman

Dear Malcolm - Thanks for the feedback.

ApplicationData is a hidden property which is not shown by the property inspector used by FindJObj.

To see this information, simply select the relevant object in the FindJObj hierarchy tree and click the "Inspect object" button. This opens the UIInspect utility, which does display ApplicationData (if available) in UIInspect's bottom-right ("other properties") table.

If you need more control, you can always use FindJObj's "Export to workspace" button, and get the ApplicationData from the exported object handle.

08 Feb 2010 Malcolm Lidierth

Superb tool Yair. Do you any plans to provide access to the application data areas of the objects e.g. from the context menu in the left-hand panel?

22 Jan 2010 Alexander Kosenkov

That's simply amazing how deep inside could you get into Matlab internals! That's incredibily useful if one needs to bult-in matlab into Java application. Something like this should be definetely included into Builder JA

06 Nov 2009 James

thx

29 Sep 2009 Oliver Woodford

Great function. The interactive display is a brilliant feature.

11 Aug 2009 Patrick Tai

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?

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.

02 Aug 2009 Boris  
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)

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?

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.

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

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.

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 !?

27 Mar 2009 Matthias Höller

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

02 Mar 2009 Husam Aldahiyat  
25 Feb 2009 Zhang Yanxiang

Great work!

24 Feb 2009 Jveer

brilliant!

24 Feb 2009 Jveer  
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

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

17 Jan 2009 ucd puri

thanks

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

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

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

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

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

21 Aug 2008 Johnny Smith

I guess, ln 257 should be

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

instead of

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

thanks!

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!

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.

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

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

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

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

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

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.

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?

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...

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
--

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.

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.

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

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

18 Jan 2010

Fixed uitreenode warning; found a way to display label text next to the relevant node name

18 Jan 2010

Fix to display text labels deep in HG hierarchy

04 Feb 2010

Forced an EDT redraw before processing; warned if requested handle is invisible

16 Mar 2010

Important release: Fixes for R2010a, debug listing, objects not found, component containers that should be ignored etc.

20 Apr 2010

Minor fix to support combo-boxes (aka drop-down, popup-menu) on Windows

27 Nov 2011

Fix suggested by Ward; fixes for R2011a and R2010b; fixed download (m-file => zip-file)

08 Dec 2011

Fixed 'File is empty' messages in compiled apps

25 Jul 2012

Fixes for R2012a as well as some older Matlab releases

14 Jan 2013

Improved callbacks table; improved export to workspace; fixed tree refresh failure; fixed: tree node-selection didn't update the props pane nor flash the selected component

25 Jan 2013

Fixed callbacks table grouping & editing bugs; added hidden properties to the properties tooltip; updated help section

16 May 2013

Fix for the upcoming HG2; fixed HG-Java warnings

08 Jul 2013

Additional fixes for the upcoming HG2

06 Jan 2014

Minor fix for R2014a; handled case of invisible figure container; only check for newer FEX version in non-deployed mode and only once every 12 hours

Contact us