File Exchange

image thumbnail

Using Java Swing components in MATLAB

version (20.6 KB) by Malcolm Lidierth
A custom class that eases the use of Java AWT and Swing components in MATLAB


Updated 06 Oct 2011

View License


For up-to-date copy and many more GUI tools (split panes, scroll panes, tabbed panes, accordions etc) for MATLAB see Project Waterloo

Cite As

Malcolm Lidierth (2020). Using Java Swing components in MATLAB (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (32)

The demo is in the @jcontrol folder and needs to be copied from there (as described in the Readme,txt; Not ideal I know, but it stops me forgetting it in nearly every update).

Axes are MATLAB HG objects. To reposition Swing objects relative to MATLAB axes you would need to code a ResizeFcn callback for the container - Swing knows nothing about the the axes and the axes are rendered at a low level by MATLAB (probably using Java Graphics2D in the end, but I don't know). There is no way to connect the two that I know of except by hard-coding via ResizeFcn.

Watch out though for a new post in the next couple of months. It may suit your purpose. "Project Waterloo" includes a MATLAB compatible extension to the SwingX JXGraph which allows data to be plotted ala MATLAB (instead of functions) and allows Swing components to be positioned in the axes using axis coordinate space - in fact Swing components can replace MATLAB's 'markers'. Waterloo has a lot more in it than this (watch this space).

Hi Malcolm,
thanks for this software again. Two things:

1. The last update doesn't have the example again.

2. Is it possible to position jcontrol objects to axes instead of to the window? I have an application that has three axes, the bottom one with many jcontrol objects. When a user resizes this axis or the one immediately on top, the jcontrol objects are not repositioned correctly. I think I should mention that the axes are inside a uiextras.GridFlex layout manager. I appreciate your input (or the input of any other reader).


This does not look like a jcontrol problem - then you would see jcontrol (x instances).
If there are references to the audioplayer objects in the onCleanup declarations, or any other callbacks, that might explain the problem. Explicitly clearing those references in the DeleteFcn for your windows should solve the problem.

Nice piece of work!

I have issues with audioplayer and jcontrol, and I was hoping someone could give me some insight.

I created a search object that pops up in a different window when the user uses a combination of keys (i.e., ctrl+f) in the main window. The main application instantiate one audioplayer, and several text labels, and the search object look into the labels for a give text.

if I run 'clear classes' after I've opened the main file and closed it without calling the search object, it doesn't report anything.

but if I open the main file, invoke the search object and close the application (even having done no operations in the search object), the 'clear classes' command reports that:

Warning: Objects of 'onCleanup' class exist. Cannot clear this
class or any of its super-classes.
Warning: The following classes still have existing instances
that cannot be cleared:
audioplayer (3 instances)

I'm in MacBook Pro running Matlab 7.11 (R2010b)

The JPanel in the jcontrol is housed in an hgjavacomponent - an undocumented MATLAB container.
The JPanel size and position are linked to the hgjavacomponent and controlled by MATLAB using its Position proprty.
Within the JPanel, the layout is not managed by MATLAB but by the Java layout manager. Change that using j.setLayout(...).

I was mistakenly trying to add another jcontrol object to the JPanel. Makes sense that it didn't work.

Thanks for the help!

>> hFig=figure;
>> j=jcontrol(hFig, javax.swing.JPanel(), 'Position', [0.2 0.2 0.6 0.6]);
>> j.add(javax.swing.JButton('Does this work?'));
>> j.getComponentCount()

ans =


Maybe you could post a code snippet.
A "j.revalidate()" might help or MATLAB "drawnow()" if the Java event queue might be blocked??

Hi Malcolm,

first of all thank you for this amazing code, it makes my life much easier!

I am trying to use a JPanel and add components to it (via the .add(component) method) but it doesn't seem to have any effect (getComponentCount() returns 0). Do you know how I can fix this issue?


If you would like more examples, take a look at the sigTOOL project where I have made extensive use of jcontrol

The sigTOOL code also includes some 'middle' and 'higher' level functions that call the low level jcontrol methods so you do not have to reinvent the wheel for every GUI. These are specific to the sigTOOL code but may provide a useful illustration. In the longer term I hope to provide a drop-and-drag GUI Builder that allows MATLAB and Java UIs to be mixed. This is half-written but is presently on hold.


thanks for including jcontrolDemo again.
Especially the linking of the various ui elements was very useful for me.


Any rounding is done by the Java Look and Feel - so it will depend on the L&F you are using. If you mean rounding in the titled borders, that is standard to the Windows L&F when using javax.swing.Border.createTitledBorder(...).
j=jcontrol(parent, 'javax.swing.JPanel',....);



It would be really great if your upcoming demo could illustrate how you did these nice panels with rounded corners as seen on the image (or if you could give me a hint of how to do so !). Thanks and congratulation on your submission


Richard. Thanks for that. I'll post an update when the new demo is done.

Very very nice. Couldn't get a decently functional scrollbar with the built-in MatLab UI widgets, with this it's very straightforward. Along the way I found a bug in isappdata, which needs an output value and currently doesn't have any.

That was deliberate - but I should have removed the reference to it in the help. Thanks for pinting this out. I'll be posting a better demo shortly.
Note also that transparency support is 'on' by default - not 'off' as the help text states.

After last update jControlDemo was omitted from zipfile?

Regards Han

You need to construct your tree in the usual way for Java. E.g.
root.add(javax.swing.tree.DefaultMutableTreeNode('Node 1'));

j=jcontrol(figurehandle, tree, 'Position', [0 0 .1 1]);

See the Sun Java Tutorials for details of how to set the tree icons etc or any good Java book



I am using jcontrol to create a tree in matlab. However, I am stuck with the task of how to add elements to my tree. I have typed the following code

obj = jcontrol(gcf,'javax.swing.JTree');

How to populate the tree ? My Data is in a Struct. Please help.

hgjavacomponents can parent other hgjavacomponents.
However, javacomponent.m will always use the hgjavacomponents' peer as parent. Therefore hgjavacomponents created via javacomponent become siblings in the same figure.

You will get Java exceptions if you try to create a JFrame ('adding a window to a container') so jcontrol does not allow that.

You can however, build very complex GUIs using a MATLAB figure or uipanel as parent and I hope to include tabbed panes once TWM provide full support for these. An advantage of using MATLAB containers is that you can mix and match jcontrols and MATLAB components including graphics in a single figure/panel.

Apart from using a java window, there are few restrictions. You can for example create a uipanel, add a swing JPanel to it, populate that with a JScrollPane and add a JTree to it along with a set of JButtons in the JPanel.

Great work! I have a question about the problems with the containers in R2008b onwards. As you comment before, hgjavacomponent may not parent other hgjavacomponent. Does this mean I cannot use Jframe as parent for my Javacomponents in R2008b onwards?

Therefore the only one way to contain JavaComponents is a figure, isn’t it? Is there any restriction in terms of including Javacomponent if I use a figure as parent? Can I build complex GUI’s using figure as parent?

Thanks in advance

See the undocumented MATLAB uitab and uitabgroup functions for tabbed panes
For widgets, I may have misunderstood. Jcontrols can be positioned using normalized units 0 to 1. MATLAB then does the work.

PS That should be uitab + uitabgroup

Ritesh Sood

I have only run the demo so far (which worked well), but it's surely a very useful contribution and I would like to thank the author for the same.

Although I haven't programmed awt/swing, or even much java, I recently wrote a fairly complex gui in perl-Gtk2, and I've some experience in gui programming.

My first question is if it's possible to have tabbed panes like we do in web browsers and a number of other guis? I don't think Matlab has it natively, and I'm sure swing has it. So how about our jobjects?

Second, one very desirable (even essential) feature in gui toolkits is widget packing. One programs the relative layout of the widgets and the toolkit computes the absolute positions and dimensions. I mean why should I be bothered with the arithmetic, let the computer do the math. Now that we can access swing via jobjects, is it possible to do automatic widget packing?

Thanks for your help!


way too much effort required to integrate within guide created GUIs. can't be asked.

Thierry. Many thanks. Demo file now restored to zip.

I could not find any demo in the package.(jControldemo missing?)

Mathias Ortner

I like this work : however I got a problem when trying the demo,

here is my udate of the javacomponent.m that made it work

if ( isa(hParent, 'figure') || ...
isa(hParent, 'uicontainer') || ...
isa(hParent, 'uiflowcontainer') || ...
isa(hParent, 'uigridcontainer') ||...
isa(hParent, 'hgjavacomponent'))
parentIsFigure = true;
peer = get(ancestor(parent,'figure'),'JavaFrame');
elseif isa(hParent, 'uitoolbar')
peer = get(parent,'JavaContainer');
if isempty(peer)
peer = get(parent,'JavaContainer');
error('MATLAB:javacomponent:InvalidParentHandle', 'Invalid parent handle\n%s', usage)

Nick Clark

Wonderful work! The author emailed me with a fix to get this working if you're a 7.0.1 user. See the following:

*In your copy of MATLAB's javacomponent.m , change lines 66-68 to this:
if isa(handle(parent), 'figure') || isa(handle(parent), 'uicontainer')
parentIsFigure = true;
peer = get(ancestor(parent, 'figure' ), 'JavaFrame');

*In jcontrolDemo:
Comment out lines 46-48
and save/run it

Yair Altman

Excellent submission. Simple, easy to understand, richly documented and very effective. A great source of knowledge and examples for anyone interested in Java-Matlab integration as well as in object-oriented Matlab programming. This submission is one of, if not the, best that I've seen in fully utilizing Matlab's class properties (with some undocumented Matlab functionality), subscripted referencing & assignment, and method overloading. Aside from class methods which are missing here, this is a great example for Matlab OOP.


Update description

Update link

Now accepts pre-constructed java objects as input to jcontrol constructor.
Subsref speed substantially improved

Fixes in subsref and setappdata.
Ancestor method added

MATLAB Release Compatibility
Created with R2007a
Compatible with any release
Platform Compatibility
Windows macOS Linux