Search code examples
javaswingmatlabparameter-passingjtextfield

Passing a MATLAB object as an input parameter on Java


I have a GUI on MATLAB with an edit uicontrol. I’ve made a Java jar library that I'm using on my code. I want to pass this uicontrol as an input parameter to a constructor on Java. The reason is because I like change the result of the String property inside Java.

This pseudocode could be an example:

MATLAB

javaaddpath('myjar.jar'); % Adding Java library
import <packagename>.*; % Route
server = ConstructorName( handles.<myUiControl> ); % IS HERE WHERE I DON'T KNOW WHAT TO PUT

Java

ConstructorName(JTextField jTF) {
jTF.setText("whatever");

}

Is it possible? Maybe is unsupported that I want to do... In this page tells about it is possible as a Java Object, but not in the chase of MATLAB object: http://www.mathworks.es/es/help/matlab/matlab_external/passing-data-to-a-java-method.html

But I've seen I could use 'findobj' to wrap uicontrols: http://www.mathworks.com/matlabcentral/fileexchange/14317-findjobj-find-java-handles-of-matlab-graphic-objects

I'm not sure if it's valid only on MATLAB environment... Thanks so much for your help.


Solution

  • I have little experience with this, but findjobj should give you access to the underlying Java-peer handle of the "Edit uicontrol".

    The following worked for me:

    >> figure('Menubar','none', 'Position',[400 400 250 100]);
    >> h = uicontrol('Style','edit', 'Position',[30 40 200 25], 'String','')
    h =
        0.0101
    
    >> drawnow; pause(0.1);
    >> jh = findjobj(h, 'nomenu')
    jh =
        javahandle_withcallbacks.com.mathworks.hg.peer.EditTextPeer$hgTextField
    
    
    >> jedit = java(handle(jh))
    jedit =
    com.mathworks.hg.peer.EditTextPeer$hgTextField[...TRUNCATED STUFF...]
    

    This is an object of class: com.mathworks.hg.peer.EditTextPeer$hgTextField. This derives from com.mathworks.mwswing.MJTextField which itself extends the standard javax.swing.JTextField.

    Next we pass the object reference to the Java code. I had to write the constructor as accepting an Object and cast that as JTextField:

    >> javaaddpath('C:\path\to\my\java\classes')
    
    >> c = MyClass(jedit)
    c =
    MyClass@483e74d7
    
    >> c.setString('hello world!')
    

    edit_uicontrol

    MyClass.java

    import javax.swing.JTextField;
    public class MyClass {
        private JTextField jtf = null;
        public MyClass(Object obj) {
            jtf = (JTextField) obj;
        }
        public void setString(String str) {
            jtf.setText(str);
        }
    }
    

    Of course this is all undocumented and completely unsupported by MathWorks..