Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

Using pure Java GUI in deployed Matlab apps

July 10, 2014 27 Comments

I would like to welcome repeat guest blogger Karthik Ponudurai, who has previously written here about the JTattoo look-and-feel, and about integration of Java controls’ events with Matlab callbacks. Today, Karthik discusses a problem when we wish to use pure-Java GUIs in deployed Matlab programs, and the undocumented simple solution.
Reminder: I will be visiting several US cities (Minneapolis, Boston and New York) in July 22-31 (details). Let me know if you’d like to meet me there.

Introduction

Using a pure-Java Swing-based Graphical User Interface (GUI) has several important advantages compared to using a pure-Matlab GUI:

  • Java GUI widget toolkit provides a large collection of components (scrollbar, slider, etc…) and layouts (card, spring, etc…)
  • Multiple event handling options
  • Mature third-party Java Swing IDEs for quick and easy GUI development (Netbeans, Eclipse, etc…)
  • Supports pluggable look and feel that allows applications to have a look and feel that is unrelated to the underlying platform.
  • Java Swing’s window icon can be modified, whereas Mathworks apparently places an [entirely unreasonable] license restriction on modifying the Matlab figure window icon.

When Matlab is in development (non-deployed) mode, we can load and display a Java JFrame using the following Matlab code:

% Add Java library to dynamic Java classpath
javaaddpath([pwd '\ExampleWindow.jar']);
% Get example Java window from the library
jFrame = examplewindow.JavaWindow();
% Get Java buttons
% Note: see http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events-in-r2014a
plotMeshButton = handle(jFrame.getPlotMeshButton(),    'CallbackProperties');
showWarnButton = handle(jFrame.getShowWarnDlgButton(), 'CallbackProperties');
% Set Java button callbacks
set(plotMeshButton, 'ActionPerformedCallback', @myPlotMeshCallback);
set(showWarnButton, 'ActionPerformedCallback', @myShowWarnCallback);
% Display the Java window
jFrame.setVisible(true);

% Add Java library to dynamic Java classpath javaaddpath([pwd '\ExampleWindow.jar']); % Get example Java window from the library jFrame = examplewindow.JavaWindow(); % Get Java buttons % Note: see http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events-in-r2014a plotMeshButton = handle(jFrame.getPlotMeshButton(), 'CallbackProperties'); showWarnButton = handle(jFrame.getShowWarnDlgButton(), 'CallbackProperties'); % Set Java button callbacks set(plotMeshButton, 'ActionPerformedCallback', @myPlotMeshCallback); set(showWarnButton, 'ActionPerformedCallback', @myShowWarnCallback); % Display the Java window jFrame.setVisible(true);

Java JFrame created in Matlab (click for full-size image)
Java JFrame created in Matlab (click for full-size image)

The problem

All this works great when ran within the Matlab environment. However, when the Matlab source code file (.m) is compiled as a Windows standalone executable application, when running the resulting executable the Java window appears for a short period and then terminates (exits). Without a visible Matlab figure, the compiled Matlab application does not retain the Java window open. The JFrame flashes on for a split-second, and then vanishes.

The solution

To fix this problem, it turns out that we only need to add the Matlab waitfor command after making the Java window visible:

% (earlier code as above)
% Display the Java window
jFrame.setVisible(true);
if isdeployed
    waitfor(jFrame);
end

% (earlier code as above) % Display the Java window jFrame.setVisible(true); if isdeployed waitfor(jFrame); end

Java JFrame in deployed Matlab (click for full-size image)
Java JFrame in deployed Matlab (click for full-size image)

The waitfor command holds the Java window open, but still enables full interactivity with the window: When a control event is triggered, the specified callback is executed, and then Matlab returns to the waitfor.
A zip file containing the Matlab source-code and its resulting executable can be downloaded from here. You might get a security notification when downloading the zip file, due to the contained exe file. Also note that to run the executable, you need to install Matlab MCR R2012b (8.0) or later, otherwise you will get a run-time error.
Finally, note that closing the Java GUI exits the JVM and by extension the entire containing program (Matlab). Naturally, this has no impact in deployed mode, but to prevent it from exiting the Matlab environment in non-deployed mode, don’t close the Java window by clicking its “X” button etc., but rather by calling jFrame.dispose(); in your Matlab code or the Matlab Desktop’s Command Window.

Related posts:

  1. Removing user preferences from deployed apps – An unsupported MathWorks Technical Solution explains how to remove private information from deployed (compiled) matlab applications. ...
  2. Speeding up compiled apps startup – The MCR_CACHE_ROOT environment variable can reportedly help to speed-up deployed Matlab executables....
  3. Splash window for deployed applications – Deployed (compiled) Matlab applications take a long time to load. I present a splash window that loads immadiately, solving this problem. ...
  4. Matlab callbacks for Java events in R2014a – R2014a changed the way in which Java objects expose events as Matlab callbacks. ...
  5. Disabling menu entries in deployed docked figures – Matlab's standard menu items can and should be removed from deployed docked figures. This article explains how. ...
  6. Matlab-Java interface using a static control – The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....
Compiler GUI Java Karthik Ponudurai Undocumented feature
Print Print
« Previous
Next »
27 Responses
  1. ddli July 22, 2014 at 04:59 Reply

    uipanel not clipping child uipanel
    Asked by SK on 4 May 2014
    Latest activity Edited by Jan Simon on 4 May 2014

    h_figure = figure;
    this.h0 = uipanel('Parent', h_figure, 'Clipping', 'on');
    this.h1 = uipanel('Parent', h0);

    h_figure = figure; this.h0 = uipanel('Parent', h_figure, 'Clipping', 'on'); this.h1 = uipanel('Parent', h0);

    h1 is a uipanel that can be scrolling implemented with a slider.

    However the scrolling uipanel does not always get clipped to the parent panel.

    The clipping failure seems to occur if the scrolling panel is large (say around twice the dimensions of the figure).

    A few others have had the problem but no solutions appear to have been found. Does anyone know of one?

    added: On further experimentation, it is not the size of the panel that is the issue. For example, the clipping works when the scrolling uipanel contains line plots but fails to work when the scrolling uipanel contains bar plots.

    Regards,

    I have the same problem? Could you tell me the way to solve it ? use java GUI? thanks!~

  2. Alvaro June 4, 2015 at 08:01 Reply

    Can I use JFrame directly from Matlab? Something like:

    frame = JFrame('otr');
    frame.add(JButton('Hello'))
    frame.setVisible(true);
    frame.setSize(200,200);
    if isdeployed
        waitfor(frame);
    end

    frame = JFrame('otr'); frame.add(JButton('Hello')) frame.setVisible(true); frame.setSize(200,200); if isdeployed waitfor(frame); end

    After compiling it with Matlab Compiler and executing, nothing appears.
    I’m using matlab 2014a under MacOs.

    Kind regards.

    • Yair Altman June 4, 2015 at 09:32 Reply

      @Alvaro – did you remember to import javax.swing.*?
      Also, you cannot waitfor(frame). You’ll need to find another solution to prevent the deployed app from exiting immediately.

  3. Sanaz June 5, 2015 at 05:03 Reply

    Hi Dear Yair
    I have problem about connect java and matlab ,I have a project web based that fill some information about specifications a pump and when click next button it must go to matlab and show plot via client.jar and transfer to web page like this link

    http://blogs.mathworks.com/images/desktop/michael_katz_interactive_web_pages_part_3/interactive_web_pages_part_3_1.png
    whether it needs to jmatlink and matlab server for this connection or not??
    I thanksful very much if u Guide me!!!!!

    Best Regards
    Sanaz

    • Yair Altman June 5, 2015 at 05:48 Reply

      @Sanaz – it is not clear from your description if you want to run Matlab from within Java, or the reverse. Contact me by email (altmany at gmail) if you would like my consulting for your specific project.

  4. Karai June 27, 2015 at 09:10 Reply

    Hi Yair,
    Is it possible to download Java source code for ExampleWindow?
    I would be very grateful if you could send me a link.

    Kind regards

    • Yair Altman July 7, 2015 at 11:47 Reply

      @Karai – you can get the *.java source code from here: http://undocumentedmatlab.com/files/examplewindow.zip

      Unfortunately I do not have access to the original (commented) files, so this is a decoded version: it has all the relevant source code, but no comment text.

  5. Yumin Sun July 7, 2015 at 02:31 Reply

    Hi Yair,

    I want to write a GUI in Java first and then call it from Matlab,is that possible? Because I need to load some pictures with transparent background and then let them move, just like to do a flash. But in Matlab, I have problem with the background, when I load the png pictures, theu always have black background, I have read many articles to solve that problem, but still I feel too hard to accomplish that, many new questions come out. So I want to ask you, is that possible, i write Java code for the GUI and then call them form Matlab?

    Thanks

    BR
    Yumin

    • Yair Altman July 7, 2015 at 04:53 Reply

      @Yumin – you can create the Java GUI and then call the GUI’s main class directly from Matlab. See the relevant Matlab docs.

      You can also use transparency directly in Matlab:
      * http://undocumentedmatlab.com/blog/displaying-animated-gifs
      * http://undocumentedmatlab.com/blog/transparency-in-uicontrols

  6. Matthew Harrison November 13, 2015 at 07:46 Reply

    Ok using this method where I have a compiled jar file how do i get the CallbackProperties for the jFrame instead of a button? Do i need to write a function in Java just to return the JFrame or window to be able to get at the Callback Properties?

    • Yair Altman November 14, 2015 at 10:29 Reply

      @Matthew – if your compiled JAR is of a Matlab function, then wiithin the Matlab function you can get the window handle as follows (slightly different syntax for R2014a and earlier):

      mjf = get(handle(gcf), 'JavaFrame');
      jWindow = handle(mjf.fHG2Client.getWindow, 'CallbackProperties');

      mjf = get(handle(gcf), 'JavaFrame'); jWindow = handle(mjf.fHG2Client.getWindow, 'CallbackProperties');

      If your compiled JAR is of a pure-Java class, then you will need to modify the Java code accordingly.

  7. Marcel Pinnow January 14, 2016 at 10:00 Reply

    Hi Yair,

    thank you for that great tutorial. I love the idea of a pure Java GUI which I can bring to life by using Matlab functions. The problem for me is that I have hardly any experience with Java coding. Could you be so kind and give me the source code of your Java GUI you’re using in this tutorial? That would help me alot.

    Thank you for your great work.

    • Yair Altman January 14, 2016 at 11:50 Reply

      @Marcel – you can use any Java decompiler (partial list) to extract the Java source code from the binary ExampleWindow.jar file contained in the download zip.

      However, if you do not have any experience with Java coding, as you said, then it might be more cost effective for you to use Matlab GUI as the baseline, and simply add new Java components (using the javacomponent function), or just add Java functionality to exiting Matlab uicontrols (using the findjobj function). This blog contains numerous examples for both of these alternatives, and you can find many other examples in my Matlab-Java programming book.

      If you need expert assistance in making your Matlab GUI look professional, feel free to contact me (altmany at gmail) for a consulting offer.

  8. Nogo September 23, 2016 at 12:45 Reply

    Stop using Matlab as something it was never meant to be.

    Matlab is a pile of crap and pain in the ass to program with.
    It´s designed for people who can´t code and refuse to learn a state of the art language.
    Then those fools start to make wired things like (ab)using Swing within Matlab.

    Stop wasting time: boot Matlab & learn a proper language!

    • Yair Altman September 28, 2016 at 13:46 Reply

      answered here

  9. zb April 13, 2017 at 10:58 Reply

    Hi Yair,

    I tried to use Java Gui in Matlab and i want to know if it is possible to add a ‘ComponentResizedCallback’ to a jFrame .
    The ‘ComponentResizedCallback’ property exists for jInternalFrame but not for the jFrame.
    Do you have any idea to outpass this?

    • Yair Altman April 13, 2017 at 12:32 Reply

      @zb – there is indeed a ComponentResizedCallback event/property but to access it you need to use handle(jFrame,'CallbackProperties') rather than jFrame directly.
      See http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events-in-r2014a

    • zb April 13, 2017 at 14:32 Reply

      Sadly, even by using handle(jFrame,’CallbackProperties’) , it doesnt work :

      The name ‘ComponentResizedCallback’ is not an accessible property for an instance of class
      ‘javax.swing.JFrame’.

    • zb April 13, 2017 at 16:08 Reply

      i know what is the problem , i use matlab 2016b. My friend with matlab2013a doesn’t have the same problem and it works well.
      Do you know why there are those changes in the new version of Matlab?

      • Yair Altman April 13, 2017 at 16:36

        @zb – this is not the problem; the problem is that you try to set the callback on a naked Java reference instead of on the handle() of that reference. Read the blog post that I mentioned carefully and then fix your code.

  10. Peng Zheng August 15, 2018 at 19:45 Reply

    Hi Yair,

    I tried to run the example, and compiled the example (matlab 2017a). It works for a few minutes, but a new problem appears, the exe crashed with a error (“jframe cannot convert to double”). Do you have any idea how to solve this?
    Kind regards

    • Eddie January 30, 2019 at 01:48 Reply

      I have this same issue on r2018b.

      The line ‘waitfor(jframe)’ does not work any more, resulting in error ‘conversion to double from jframe is not possible’

    • James March 12, 2019 at 20:05 Reply

      Looks like I am seeing the same issue. I was able to work around the error in 2017a+ by just adding an invisible figure and having the program wait for it.

      fig = figure('Visible',0);
      jFrame.setVisible(true);
      if isdeployed
          waitfor(fig);
      end

      fig = figure('Visible',0); jFrame.setVisible(true); if isdeployed waitfor(fig); end

      Then we need to do a system exit, not dispose, I think to cleanly remove the figure. Hopefully there is a better implementation, but it works for now.

  11. Lukasz February 1, 2019 at 18:32 Reply

    To avoid the closing problem (closing the window also closes JVM/Matlab), it is enough to implement the WindowListener interface and overwrite the windowClosing method, so there is no EXIT_ON_CLOSE (i.e. System.exit(0)).

    E.g.

    public class JavaWindow
            extends JFrame implements WindowListener{
    ...
    @Override
        public void windowClosing(WindowEvent e) {
     
        }

    public class JavaWindow extends JFrame implements WindowListener{ ... @Override public void windowClosing(WindowEvent e) { }

    • Yair Altman February 5, 2019 at 16:41 Reply

      Alternatively, set the Java frame’s default close operation to DISPOSE_ON_CLOSE, as follows:

      jFrame.setDefaultCloseOperation(jFrame.DISPOSE_ON_CLOSE);  % rather than EXIT_ON_CLOSE

      jFrame.setDefaultCloseOperation(jFrame.DISPOSE_ON_CLOSE); % rather than EXIT_ON_CLOSE

  12. Michael February 5, 2019 at 11:31 Reply

    Hi Yair,
    thanks very much for this great site and books! This is probably the wrong place to ask a question, so sorry beforehand. I am using Matlab 2015b on Windows 7. I have a function that generates a figure with Java tables, with the standard Windows laf. I tried to change the highlight colour for the text in my figure in the following way:

    defaults = javax.swing.UIManager.getLookAndFeelDefaults();
    defaults.put('textHighlight', java.awt.Color(1, 0, 0));

    defaults = javax.swing.UIManager.getLookAndFeelDefaults(); defaults.put('textHighlight', java.awt.Color(1, 0, 0));

    As the result the text highlighting of the Matlab Command window changes to red colour, but nothing changes in any of the figures. Pausing and drawnow doesn’t help. Is there a workaround?

    • Yair Altman February 5, 2019 at 11:44 Reply

      @Michael – look here: http://undocumentedmatlab.com/blog/modifying-matlab-look-and-feel
      You’d probably want to modify the L&F only during your figure creation, and restore it back to the default immediately following the GUI creation.

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitable (6) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
Contact us
Captcha image for Custom Contact Forms plugin. You must type the numbers shown in the image
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top