- Undocumented Matlab - https://undocumentedmatlab.com -

Matlab-Java interface using a static control

Posted By Yair Altman On October 13, 2010 | 27 Comments

I would like to welcome guest blogger Karthik Ponudurai. Today, Karthik will introduce an interesting technique for interfacing Java GUI to a Matlab application.
The current method of interfacing Java GUI controls and Matlab is by retrieving the underlying Java callback and assigning it to a Matlab callback, as shown in the following example:

% Create a Java button
jButton = javacomponent(javax.swing.JButton('click me'), [20,20,60,20], gcf);
% Assign a Matlab callback
hButton = handle(jButton, 'CallbackProperties');
set(hButton, 'ActionPerformedCallback', @myCallback);
% Matlab callback function
function myCallback(hObject, hEventData)
    % Insert your code here
end

This approach works fine for simple pure-Java GUI created using an IDE (for example, NetBeans [1] or Eclipse [2]) that only have a small number of controls. You can retrieve all the Java controls in Matlab and set the callbacks as shown in the above example.
Unfortunately, practical GUIs often contain numerous controls. Assigning each control a different Matlab callback can be quite tedious.

Using a callback switchyard function

A workaround to this problem can be achieved using an invisible/hidden static Java JButton. During Matlab initialization, assign a single callback for the static Java JButton:

% Return a reference to the GUI's static trigger button
triggerButton = statictrigger.triggerCls.getTrigger();
% Assign Matlab switchyard callback for triggerButton
buttonProps = handle(triggerButton, 'callbackproperties');
set(triggerButton, 'ActionPerformedCallback',@TriggerCallback);

When an event is triggered by any monitored control in the Java GUI, then within the Java code set the static button’s action command string to the desired Matlab callback name (a String) and invoke the static button’s doClick() method to trigger the Matlab TriggerCallback callback. Based on the action command string, this callback invokes the appropriate Matlab function. In this manner, Matlab’s TriggerCallback() acts as a switchyard function [3] to the actual callback functions:

function TriggerCallback(hObject, hEventData)
   actionCmd = char( hObject.getActionCommand() );
   hgfeval(actionCmd, hObject, hEventData);
end

Note how the char function converts the Java action command (a java.lang.String object) into Matlab char array. The requested Matlab function is then dynamically invoked using Matlab’s semi-documented hgfeval function [4], which Yair will describe in another article later this month.
The next few sections will look into the sample application in more detail. This application can be downloaded from here [5].

Java GUI

Firstly, let’s look into the Java GUI:

Main Java GUI
Main Java GUI

When the “Show Result in Matlab Dialog Box” button is clicked, the form information’s (Name, Age, Sex etc…) is saved in a hash map. This hash map is then serialized to a local file (C:\streamdata). Next, the static button’s action command string is set to ‘show’ and finally its doClick() method is invoked.
Below is the Java code corresponding to button click event:

private void showActionPerformed(java.awt.event.ActionEvent evt)
{
    // Add form values to hash map
    hMap.put(name.getName(), name.getText());
    hMap.put(age.getName(), age.getValue());
    hMap.put(sex.getName(), (String)sex.getSelectedItem());
    hMap.put(address.getName(), address.getText());
    hMap.put(email.getName(), email.getText());
    // Serialize hash map
    WriteObject(hMap);
    // Set trigger
    triggerCls.setTrigger(evt.getActionCommand());
}

Matlab callbacks

The Java GUI sources are compiled and packaged in the statictrigger.jar file. The Matlab StaticButtonTriggerExample.m source file adds the Java library to the dynamic Java classpath:

% Add dynamic java class path
javaclasspath([pwd '\javalib\statictrigger.jar']);

The main.m function contains the code for creating the Java GUI and assigning the static button callback:

% create the statictrigger object
app = statictrigger.app();
% Set static trigger button listener
triggerButton = statictrigger.triggerCls.getTrigger();
buttonProps = handle(triggerButton,'callbackproperties');
set(buttonProps,'ActionPerformedCallback', {@StaticButtonTriggerCallback, app});
% Show the Java Frame
app.setVisible(1);

statictrigger.triggerCls.getTrigger() is a static Java public method that returns the static button object, for which we assign our callback switchyard function.
The following is the StaticButtonTriggerCallback.m code, which displays the information in a Matlab message-box:

Matlab message-box triggered by the Java GUI
Matlab message-box triggered by the Java GUI

% Get action command string
actionCommand = src.getActionCommand();
% Read in serialized hash map
hashMap = app.ReadObject();
% Convert hash map to Matlab structure
data = Hash2Struct(hashMap);
% Display data in Matlab dialog box
msg = ['Name: ' char(hashMap.get('name')) ...
       ', Age: ' num2str(hashMap.get('age')) ...
       ', Sex: ' char(hashMap.get('sex')) ...
       ', Address: ' char(hashMap.get('address')) ...
       ', Email: ' char(hashMap.get('email')) ];
uiwait(helpdlg(msg, 'Form Details'));

You can download the example’s files from here [5]. Extract the zip file, cd to the newly-generated StaticButtonTrigger folder, then invoke the StaticButtonTriggerExample.m function to run the example.

Categories: Guest bloggers, GUI, Java, Low risk of breaking in future versions


27 Comments (Open | Close)

27 Comments To "Matlab-Java interface using a static control"

#1 Comment By Mikhail On October 14, 2010 @ 08:17

I have tried similar technique

[12]

in a more general scenario, not directly bound to UI events to replace this older JMI-based approach


[13]

But somehow it has not worked for me …

#2 Comment By Yair Altman On October 14, 2010 @ 11:57

Welcome aboard Mikhail 🙂
Haven’t seen you around CSSM in a very long time – you’ve been missed…

Funny that the MathForum link you posted doesn’t appear on CSSM – I was under the impression that MathForum was a simple CSSM mirror

-Yair

#3 Comment By Karthik Ponudurai On October 21, 2010 @ 06:08

Hi Mikhail,

I have also tried the JMI solution from

[13]

and I realise quickly how complicated it is to get it working, and running MATLAB as a server is not a good option for us.

We code and deploy MATLAB application to users, and the above solution enable us to develop a nice looking front end with a simple communication protocol.

Thanks.
Karthik

#4 Comment By Mikhail On October 27, 2010 @ 14:21

@Karthik: you misunderstood me. See my first link – the solution I tried three years ago very is similar to yours! Bur I encountered problems with it and had to stay with JMI which works fine. I will try your solution on this weekend!

#5 Comment By Karthik Ponudurai On October 28, 2010 @ 02:52

Hi Mikhail, got you now. Let me know how it goes. Good luck!

#6 Comment By Eric Klumpp On October 21, 2010 @ 01:13

Very nice example !
Is it possible to have also the java source code, to see all interactions between java and matlab ?

Thanks
Eric

#7 Comment By Karthik Ponudurai On October 21, 2010 @ 06:10

Hi Eric,

Thanks for the comment. The Java source code is now included in [14].

Karthik

#8 Comment By Eric Klumpp On October 22, 2010 @ 02:04

Hi Karthik,

Sorry to disturb you again, but the zip file only include the .jar file.
In fact I would like to see the .java file if it’s possible.

I’m new in developping Java GUI inside Matlab, and I would like to use it as a base for my GUIs. I read on the web that it’s important to focus on EDT management between Matlab and Java, but it isn’t well documented. And it seems that your example can be a good base for any GUI development, isn’t it ?

Eric

#9 Comment By Yair Altman On October 23, 2010 @ 11:20

@Eric – the Java source files are included in [14], in the StaticButtonTrigger\javalib\ folder

– Yair

#10 Comment By Karthik Ponudurai On October 24, 2010 @ 02:42

Hi Eric,

To build a pratical Java GUI in MATLAB you still need to keep the main Window as MATLAB figure and use Yair’s UISpiltPane ( [15]) to divide MATLAB figure into sub panels. The reason for using MATLAB figure is because currently you still need a MATLAB’s uipanel to add a plotting axes ( [16]).

You can then use JControl ( [17]) to integrate Java components (example java JPanel, JDesktopPane, etc…) to the sub panels.

It’s also worth looking at Infonode ( [18]) Java GUI inplementation which allows docking windows. I have implemented Infonode in MATLAB and it does extend the MATLAB’s GUI capability.

Karthik

#11 Comment By Suganya On February 12, 2011 @ 00:16

Hi Karthik

I am working in a project similar to what you have said above . We are using NetBeans to create our own web application and we need to interface Matlab with JSP and servlets. Since servlets is the Java code, will we be able to interface it with Matlab in the way you have said above?

Regards
Suganya

#12 Comment By Karthik Ponudurai On April 8, 2011 @ 01:03

Hi Suganya,

I personally have not worked with Servlets or web application. I don’t think MATLAB includes the java libraries for servlets in the static library path, but you could add the libraries to the dynamic path during runtime and then access all the classes within MATLAB.

Sorry for the late reply as I did not receive a notification email. If you have any further question, email me at [19]

Karthik

#13 Comment By Anubhav Jain On August 22, 2011 @ 03:46

Hi,
I want to enquire about the events generated upon opening or closing a dialog box(e.g-Function Block Parameters or Source Block Parameters). Is there any way I can get these events and register their listeners.
Thanks & Regards
Anubhav Jain

#14 Comment By Yair Altman On August 23, 2011 @ 11:16

@Anubhav – you need to get the dialog handle before you can register any listener on it…

#15 Comment By Anubhav Jain On August 23, 2011 @ 21:34

Hi,
Thanks a lot for your immediate response.
Actually I wanted to get the name of an event associated with closing of function parameter dialog box for example if I change threshold value of a switch block and apply it then I should be able to listen to the event of closing of that parameter box. Can you please help me out with this.
Thanks & Regards
Anubhav Jain.

#16 Comment By Yair Altman On August 24, 2011 @ 00:30

@Anubhav – you can perhaps trap the dialog figure’s [20].

#17 Comment By Donn Shull On August 25, 2011 @ 12:55

@Anubhav – This is a complicated area and you will have to do a lot of reasearch on your own to accomplish what you are looking for. The first thing to know is that the Simulink editor is not java based so none of the java techniques are going to be of use to you. Simulink to a certian extent is UDD based. There are two primary UDD packages you will need to study using the techniques from the series of articles on UDD. The first package is the ‘DAStudio’ package. The second is the ‘Simulink’ Package. DAStudio to a certian extent is the base package as it contains an object called DAStudio.Object which is the Superclass for Simulink.Object which in turn is the Superclass for most of the rest of the Simulink classes in the Simulink package. To a certian extent the uses for these packages can be divided as follows. Models are built from classes in the Simulink Package while Dialogs come from the DAStudio package. The parameter dialogs you are looking at are of tyoe DAStudio.Dialog. They do not generate any events on their own. They are however hierarchical children of DAStudio.ToolRoot. So in theory you can monitor an instance of DAStudio.ToolRoot for the events ‘ObjectsChildAdded’ and ‘ObjectChildRemoved’ using the methods in the Hiearchical Systems with UDD and UDD events posts.

Good Luck,

Donn

#18 Comment By Rob Cranfill On October 4, 2012 @ 08:21

I think there’s a typo in the original code – in the 2nd code block, the first one after the heading “Using a callback switchyard function”. It says

get(triggerButton, 'ActionPerformedCallback',@TriggerCallback);

but I’m pretty sure that should be

set(triggerButton, 'ActionPerformedCallback',@TriggerCallback);  % set, not get

At least, the first one doesn’t work for me, and the second one does. (I’m using Matlab 2012a, but I don’t think that’s the issue.)

Thanks for lots of great Matlab help!

/rob

#19 Comment By Yair Altman On October 4, 2012 @ 11:16

@Rob – thanks for the correction. I fixed the article accordingly.

#20 Comment By George Brennan On October 26, 2012 @ 10:00

Well done.

I would add that as you are passing the Matlab instantiated app object around couldn’t you change the hMap to public and access it without the file I/O?

Although getters/setters are probably a more acceptable route.

#21 Comment By nikhil On April 17, 2013 @ 02:45

Hello,

I am trying to open a UI created in Java SWT through Matlab.
But I am getting following error..

Java exception occurred:
java.lang.UnsatisfiedLinkError: Could not load SWT library. Reasons:
	no swt-win32-3833 in java.library.path
	no swt-win32 in java.library.path
	Native Library C:\Users\x_shirod\.swt\lib\win32\x86_64\swt-win32-3833.dll already loaded in another classloader
	Can't load library: C:\Users\x_shirod\.swt\lib\win32\x86_64\swt-win32.dll

Can any one help me in this…

thanking you in advance.


Nikhil

#22 Comment By Yair Altman On April 17, 2013 @ 03:01

@Nikhil – try adding C:\Users\x_shirod\.swt\lib\win32\x86_64\ to your librarypath.txt file:

edit('librarypath.txt')

#23 Comment By Jai Naresh On December 3, 2013 @ 09:42

Hi,
I am trying to launch matlab model and control its execution through Java Interface. Please let me know if their are any ways to do this.

Any response will help.

Thanks,
jai Naresh

#24 Comment By Yair Altman On December 3, 2013 @ 09:53

@Jai – take a look at JMI: [21]

#25 Comment By Abdullah On March 15, 2015 @ 16:46

So, I am trying the following:

I added a listener to a Simulink block.

When trying to execute a public function of my JAR file within the listener, I get an error.

I tried to use a timer to see if that would solve the issue. However, it didn’t work.

Any clues?

#26 Comment By Tom On September 26, 2016 @ 13:12

Why you getting a handle if you don´t use it?

% Assign a Matlab callback
hButton = handle(jButton, 'CallbackProperties');
set(jButton, 'ActionPerformedCallback', @myCallback);

#27 Comment By Yair Altman On September 26, 2016 @ 13:44

@Tom – you are correct. This was simply a typo (jButton instead of hButton). I corrected the main text accordingly.


Article printed from Undocumented Matlab: https://undocumentedmatlab.com

URL to article: https://undocumentedmatlab.com/articles/matlab-java-interface-using-static-control

URLs in this post:

[1] NetBeans: http://netbeans.org/

[2] Eclipse: http://eclipse.org/

[3] switchyard function: http://www.mathworks.com/company/newsletters/news_notes/win00/prog_patterns.html

[4] hgfeval function: http://undocumentedmatlab.com/blog/hgfeval/

[5] here: http://undocumentedmatlab.com/files/StaticButtonTrigger.zip

[6] JMI – Java-to-Matlab Interface : https://undocumentedmatlab.com/articles/jmi-java-to-matlab-interface

[7] Static Java classpath hacks : https://undocumentedmatlab.com/articles/static-java-classpath-hacks

[8] Matclipse – Eclipse-Matlab interface : https://undocumentedmatlab.com/articles/matclipse-eclipse-matlab-interface

[9] Matlab callbacks for Java events in R2014a : https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a

[10] Using Java Collections in Matlab : https://undocumentedmatlab.com/articles/using-java-collections-in-matlab

[11] Matlab-Java memory leaks, performance : https://undocumentedmatlab.com/articles/matlab-java-memory-leaks-performance

[12] : http://mathforum.org/kb/thread.jspa?forumID=80&threadID=1639114&messageID=5950848

[13] : http://www.cs.virginia.edu/~whitehouse/matlab/JavaMatlab.html

[14] : https://undocumentedmatlab.com/files/StaticButtonTrigger.zip

[15] : http://www.mathworks.com/matlabcentral/fileexchange/23073

[16] : http://www.mathworks.de/matlabcentral/newsreader/view_thread/148719

[17] : http://www.mathworks.com/matlabcentral/fileexchange/15580-using-java-swing-components-in-matlab

[18] : http://www.infonode.net/

[19] : mailto:karthik.ponudurai@gmail.com

[20] : http://www.mathworks.com/help/techdoc/ref/figure_props.html#DeleteFcn

[21] : https://undocumentedmatlab.com/blog/jmi-java-to-matlab-interface/

Copyright © Yair Altman - Undocumented Matlab. All rights reserved.