MATLAB-Java Programming book

Undocumented Secrets of Matlab-Java Programming book
CRC discount promo code

Quick links:     Reviews     Table of Contents     Book organization     FAQ     About the author     Errata list

For a variety of reasons, the Matlab-Java interface was never fully documented. This is really quite unfortunate: Java is one of the most widely used programming languages, having many times the number of programmers and programming resources as Matlab. Also unfortunate is the popular claim that while Matlab is a fine programming platform for prototyping, it is not suitable for real-world, modern-looking applications.

Undocumented Secrets of Matlab-Java Programming (CRC Press, ISBN 9781439869031) aims to correct this.

This book shows how using Java can significantly improve Matlab program appearance and functionality. This can be done easily and even without any prior Java knowledge.

Readers are led step-by-step from simple to complex customizations. Within the book’s 700 pages, thousands of code snippets, hundreds of screenshots and ~1500 online references are provided to enable the utilization of this book as both a sequential tutorial and as a random-access reference suited for immediate use.

Click here to get your book copy now!
Use promo code MZK07 for a 25% discount and free worldwide shipping on crcpress.com

This book demonstrates how:

  • The Matlab programming environment relies on Java for numerous tasks, including networking, data-processing algorithms and graphical user-interface (GUI)
  • We can use Matlab for easy access to external Java functionality, either third-party or user-created
  • Using Java, we can extensively customize the Matlab environment and application GUI, enabling the creation of visually appealing and usable applications

No prior Java knowledge is required. All code snippets and examples are self-contained and can generally be used as-is. Advanced Java concepts are sometimes used, but understanding them is not required to run the code. Java-savvy readers will find it easy to tailor code samples for their particular needs; for Java newcomers, an introduction to Java and numerous online references are provided.

No toolbox, Simulink or Stateflow is necessary for using this book – only the core Matlab product. These extra tools indeed contain many other Java-based aspects, but they are not covered in this book. Perhaps a future book will describe them.

This book shows readers how to use and discover the described components, using nothing but Matlab itself as the discovery tool. In no case is illegal hacking implied or necessary for the discovery or usage of anything presented in this book. As far as I know, everything in this book is legal and within the bounds of the Matlab license agreement.

Reviews

Amazon reviews - Undocumented Secrets of Matlab-Java ProgrammingReviews of the book on ComputingReviews

Reviews of the book on matlab.developpez.com (French)

Reviews of the book on Amazon

Table of Contents

PREFACE

CHAPTER 1: INTRODUCTION TO JAVA IN MATLAB
   1.1 Creating Java Objects
   1.2 Java Object Properties
   1.3 Java Object Methods and Actions
   1.4 Java Events and Matlab Callbacks
   1.5 Safe Java Programming in Matlab – A How-to Guide
   1.6 Compiling and Debugging User-Created Java Classes in Matlab
   1.7 Compatibility Issues
   1.8 Java Versions in Matlab
   1.9 Java.opts

CHAPTER 2: USING NON-GUI JAVA LIBRARIES IN MATLAB
   2.1 Complex Data Structures
   2.2 Database Connectivity
   2.3 Miscellaneous Other Uses
   2.4 A Short Pause for Reflection

CHAPTER 3: RICH GUI USING JAVA SWING
   3.1 Adding Java Swing Components to Matlab Figures
   3.2 Matlab’s Main Thread and the Event Dispatch Thread (EDT)
   3.3 Customizing Java Components
   3.4 Component Callbacks
   3.5 Using 3rd-Party Libraries in Matlab
   3.6 System-Tray Icons
   3.7 Drag and Drop
   3.8 Adding Matlab Components to Java Swing Containers
   3.9 Alternatives to Swing

CHAPTER 4: UITOOLS
   4.1 Uitable
   4.2 Uitree
   4.3 Uitab
   4.4 Uiundo
   4.5 Toolbars
   4.6 Menus
   4.7 Status Bar

CHAPTER 5: BUILT-IN MATLAB WIDGETS AND JAVA CLASSES
   5.1 Internal Matlab Java packages
   5.2 MWSwing package
   5.3 MWT package
   5.4 MLWidgets package
   5.5 Widgets package
   5.6 MLServices package
   5.7 JIDE
   5.8 Miscellaneous other internal classes

CHAPTER 6: CUSTOMIZING MATLAB CONTROLS
   6.1 PushButton
   6.2 ToggleButton
   6.3 RadioButton
   6.4 Checkbox
   6.5 Editbox
   6.6 Listbox
   6.7 Popup menu (a.k.a. drop-down, combo-box)
   6.8 Slider
   6.9 Text label
   6.10 Frame
   6.11 Uipanel
   6.12 Tooltips

CHAPTER 7: THE JAVA FRAME
   7.1 Java Frame Properties and Methods
   7.2 FindJObj and the Java Frame Components Hierarchy
   7.3 Important Java Frame Containers
   7.4 BeanAdapters

CHAPTER 8: THE MATLAB DESKTOP
   8.1 Desktop Functionality and Layout
   8.2 System Preferences
   8.3 Command Window
   8.4 Editor
   8.5 Keyboard Bindings
   8.6 Workspace
   8.7 Other Desktop Tools

CHAPTER 9: USING MATLAB FROM WITHIN JAVA
   9.1 Approaches for Java control of Matlab
   9.2 JMI – Java-to-Matlab Interface
   9.3 JMI wrapper – local MatlabControl
   9.4 JMI wrapper – remote MatlabControl
   9.5 Using JNI to connect Java and Matlab

CHAPTER 10: PUTTING IT ALL TOGETHER
   10.1 UISplitPane
   10.2 IDS – Integration Debriefing System
   10.3 Concluding Exercise: UIMultiListbox

APPENDIX A: WHAT IS JAVA?

APPENDIX B: UDD

APPENDIX C: OPEN QUESTIONS

INDEX

Book organization

This book is organized in chapters grouped by related functionality/usage and ordered from easiest (novice Java use) to advanced. It is NOT necessary to read the book in order: the chapters and sections are mostly independent and can stand alone. You can safely skip almost any section that you find difficult or uninteresting.

Chapter 1 (Introduction to Java in Matlab) provides a description of the internal Java engine shipped in Matlab. Chapters 2 (Using Non-GUI Java Libraries in Matlab) and 3 (Rich GUI using Matlab Swing) describe how this internal Java engine can be used to extend Matlab, both programmatically (Chapter 2) and visually (Chapter 3).

Chapter 4 (Uitools) describes a set of undocumented built-in Matlab user-interface functions which use Java components. Many of these functions are Matlab wrappers for Java components presented in Chapter 3. Using these tools and some simple customizations we can significantly improve our Matlab programs’ usability.

The notion of customizing our Matlab user-interface using Java is expanded in Chapters 5 (Built-in Matlab Widget and Java Classes), 6 (Customizing Matlab Controls) and 7 (The Java Frame).

Chapter 8 (The Matlab Desktop) discusses customization of the Matlab environment rather than that of a Matlab application.

Chapter 9 (Using Matlab from within Java) discusses the other side of the coin, namely how to call the Matlab engine from within a Java program. Unlike calling Java from Matlab, and unlike calling Matlab from C/C++/VB, the Java-to-Matlab interface is entirely undocumented and unsupported – Chapter 9 fills this gap.

This book concludes with Chapter 10 (Putting It All Together), which describes a utility and an application that tie together many issues presented in this book.

From a supportability viewpoint, progressively advanced chapters of this book are deeper in undocumented territory, are less supported, have fewer online references and are increasingly prone to change or malfunction in some future Matlab release.

A quick FAQ

  1. I do not know Java – is this book for me?
    Absolutely yes. This book is intended for Matlab programmers and users, and no Java knowledge is assumed. Java-savvy programmers will indeed find it easier to use and extend some of the more advanced topics. However, even programmers with absolutely no Java experience can still use most of this book as-is. I hope the presentation will suit both audiences equally well.
     
  2. Is everything legal?
    Yes. I am an engineer, not a lawyer, but as far as I can tell everything presented in this book is perfectly legal to use, as long as you have access to a legal version of Matlab. Still, if you have any specific concern about a particular aspect, I am sure that MathWorks will gladly answer your question.
     
  3. Does MathWorks endorse this book?
    Unfortunately not. This book often relies on undocumented and unsupported features. MathWorks allows us to use these features, but does not officially endorse or support them.
     
  4. How is this book different from the articles on this website?
    Almost all of the Java-related articles on this website are included in the book, but they constitute only a part of the book. The book’s 700 pages contain much more information than the website articles. The book is also structured in a way that enables quick discovery of the features relevant to your needs, rather than the salad of articles in this website. On the other hand, this website is continually updated with new information in articles and reader comments, and is therefore a valuable resource in its own right. You can also easily copy-paste code from the website articles, which is somewhat more difficult to do with a printed book… For these reasons, I included back-links to the relevant articles within the corresponding book sections.
     
  5. How can I help to promote this work?
    You can help by sending feedback and by promoting this book and the website to colleagues. You could write a review about the book in websites such as Amazon or Barnes & Noble. You may also support my work by hiring my services for consulting or programming work.
     

About the author

Yair Altman Yair Altman, author of the extremely popular UndocumentedMatlab.com website, is well respected in the Matlab community as an expert on undocumented Matlab features and the Matlab-Java interface in particular. His many years of contribution on the Matlab (CSSM) forum and his website, including a multitude of useful tips never before published, are now available in this highly readable book.

Yair holds a BSc in Physics and an MSc in Computer Science, has over 20 years of programming experience at various levels of responsibility, and currently consults for
several software development projects.

Additional information can be found here.

Yair is married with three children (who would never have allowed him to write this book had they known in advance the herculean effort that it would take…).

Errata list

Last updated: 2012-07-08

ChapterSectionPageParagraphCurrent textCorrection typeCorrected textPost date
11.1.162nd from bottom(none – new paragraph)additionImportant: do not exit your Java GUI using Java’s exit() function, because this exits Matlab. This is not a bug: since the Matlab GUI is itself Java-based, exiting Java (or more precisely, the JVM), has a side effect of closing Matlab.2011-12-23
11.1.2105th from bottom(none)clarificationSee https://undocumentedmatlab.com/blog/converting-java-vectors-to-matlab-arrays/ for details about converting Java arrays into Matlab arrays.2011-12-23
11.2132nd from bottom…equivalent Java form:clarificationIn some cases there is no corresponding Java setter method – in such cases we need to use other workarounds: https://www.mathworks.com/matlabcentral/newsreader/view_thread/3144692011-12-23
11.5.4263rd from bottom…and setPropertyName.addition; use struct if possible (ref)2012-02-19
11.6333rd from bottom(none – new paragraph)additionI have never tested this myself, but theoretically one could replace any JVM or MathWorks Java class with a user-modified version, using the –Xbootclasspath JVM startup option (see http://weblogs.java.net/blog/alexfromsun/archive/2006/06/swing_testing_a.html (or: http://bit.ly/uNJYar)). This could help debugging by, for example, adding debug printouts.2011-12-23
11.8.2413rd from top…Apple Java 10.6 update 1addition… or by a java.opts fix (see https://www.mathworks.com/matlabcentral/newsreader/view_thread/314519#859363 (or: http://bit.ly/ty5B7S)).2011-12-23
1References53Refs #141, 143(none)additionhttps://www.mathworks.com/matlabcentral/newsreader/view_thread/314519#859363 (or: http://bit.ly/ty5B7S)2011-12-23
22.2.365bottomDriverManager.getConnection(fixcon = DriverManager.getConnection(2012-02-05
22.2.4663rd from bottomexecuteQuery()fixexecuteUpdate() for the DML (update) queries – (see the following correction in this table)2012-02-19
22.2.4663rd from bottom(none – new paragraph)additionSQL queries that return a ResultSet should use executeQuery(); queries that update data should use executeUpdate(), which returns the number of affected rows (ref). Some JDBC-database combinations accept executeQuery() in both cases; but in many cases this is prevented and attempting to update data using executeQuery() will result in a run-time exception informing this. If you are unsure which of the execute methods to use, you can use execute(). This method runs both kinds of SQL statements, and returns a boolean value based on the inferred statement type: true=executeQuery(); false=executeUpdate() (ref).2012-02-19
22.4733rd from top…and source-code repositories,(107)fix(the reference number should be 106, not 107)2012-02-05
2References74Ref #13…/containers_map.htmlfixhttp://www.mathworks.com/help/techdoc/ref/containers_mapclass.html (or: http://bit.ly/wtY6Wz)2012-02-19
2References75Ref #44(none)additionhttp://www.mathworks.com/matlabcentral/answers/17127-connect-to-postgres-db (or: http://bit.ly/pDnfzF)2011-12-23
33.1.1823rd from tophButton = javahandle_withcallbacks...
jButton = 158.002197265625
fixjButton = javahandle_withcallbacks...
hButton = 158.002197265625
2012-07-08
33.1.2861st from bottomJButtonJCheckBoxadditionJToggleButton – basic control – uicontrol(‘style’,’togglebutton’) – Full2011-12-23
33.2922nd from top…with the EDT,clarificationEDT deadlocks can at least be monitored and displayed using a dedicated timer thread. See for example http://elliotth.blogspot.com/2005/05/automatically-detecting-awt-event.html (or: http://bit.ly/ug6Ryd).2011-12-23
3References152Ref #151(Reference 151)fix(Reference 151 is listed twice. The second reference number should be 152, and all subsequent reference should have a value of +1, e.g. reference 152 is actually 153 etc.)2011-12-23
4Introduction1542nd from bottomSome functions (such as uitable or uitree)…fixSome functions (such as uitree)2011-12-23
44.1.11624th from bottom…with a simple DefaultTableModel:clarificationThis in itself is not enough – we also need to ensure that the uitable has an empty ColumnFormat property, because if it is non-empty then it overrides our cell-renderer.2011-12-23
44.1.31683rd from bottomjscroll.VERTICAL_SCROLLBAR_AS_NEEDED
jscroll.HORIZONTAL_SCROLLBAR_AS_NEEDED
fixjscroll.java.VERTICAL_SCROLLBAR_AS_NEEDED
jscroll.java.HORIZONTAL_SCROLLBAR_AS_NEEDED
2012-09-22
44.1.31693rd from bottomsetNonContiguousCellSelection(flag)fixsetNonContiguousCellSelection(false)2012-07-08
4References236Ref #1http://www.mathworks.com/matlabcentral/fileexchange/10045fix(Unfortunately, this submission was removed from the File Exchange)2011-12-23
55.2.12514th from topSpinners use an inner modelclarificationSpinners use an internal data model2011-02-05
55.73194th from top…not the newest 3.2.2 as of September 2011fix…not the newest 3.3.2 as of December 20112011-12-23
55.7.13213rd from top(none)clarificationThere is unfortunately no corresponding FileChooser JIDE class. This is unfortunate due to the internal JVM bug (http://bit.ly/txbDyw) that causes Swing’s JFileChooser to not show the top icons in Windows 7 on Matlab versions up to R2011b (the fix requires a JVM upgrade to 1.6_18, as described in Section 1.8.2 above). JIDE’s FolderChooser works in Windows 7 since it uses internal proprietary icons.2011-12-23
7References462Ref #10(none)additionhttp://weblogs.java.net/blog/alexfromsun/archive/2006/06/swing_testing_a.html (or: http://bit.ly/uNJYar)2011-12-23
7References462Ref #23http://www.mathworks.com/matlabcentral/fileexchange/11684fix(Unfortunately, this submission was removed from the File Exchange)2011-12-23
88.3.4.2504top…Until this bug is fixed, I suggest using only simple values.fixI suggest using only simple values in R2010a-R2011b. This bug was apparently fixed in R2012a.2012-02-05
88.4.15105th from bottom(none)additionThis functionality can be used to preserve separate editor states for different projects, and has been incorporated in the SaveCurrentEditorFiles utility on the Matlab File Exchange.2012-02-05
99.55652nd from bottom(none)additionPlace this class file on Matlab’s static Java classpath (classpath.txt file), to prevent UnsatisfiedLinkError exceptions (see ref).2012-02-05

36 Responses to MATLAB-Java Programming book

  1. Sainath M says:

    Hi Yair,

    I have a basic question like as we have Java platform where people use to develop tools, again what is the advantage we are getting by developing tools in MATLAB with/without Java concepts.
    I guess and aggrie’s there will be benefits by using MATLAB platform instead of JAVA for tool developments(GUI).
    Will you suggest me what are the benefits we are getting by developing tools in MATLAB using JAVA concepts.

    Thank you for your time,

    Regards,
    Sai.

    • @Sai – since you are already familiar with Java, it makes a lot of sense to keep your GUI in Java, but to develop the core algorithms in Matlab. Matlab is much better than Java for rapidly developing computational algorithms. Using Matlab will significantly decrease your development cycle times, and increase your code’s validity/accuracy. After being used to the power and flexibility of Java GUI you will be disappointed at the much more limited pure-Matlab GUI capabilities. But as I said, if you use Java GUI then you can benefit from both worlds.

    • Sainath M says:

      Hi Yair,

      Thank you very much for your time and information.

      Regards,
      Sainath M.

    • Sainath M says:

      Hi Yan,

      In MATLAB we can create our GUI by using GUIDE tool or by manual scripting(i.e., on figure) with or without JAVA concepts. What is the main difference between these two procedures:
      If so please suggest me which one is flexible with more functionalities for developing the GUI tool.

      Thank You for your time,

      Regards,
      Sai.

    • @Sai – GUIDE is easier to set-up and design, but harder to maintain than creating a pure GUI from scratch. GUIDE figures also have some [usually small] performance overheads compared to pure GUIs. Also, GUIDE makes it a bit more difficult to integrate Java components in the Matlab figure, although this can of course be overcome.

      Both of these routes (GUIDE and manual GUI programming) have their uses, and the ultimate decision depends on what you want your GUI to look like and how you wish it to behave (in other words, your exact requirements).

      If you would like my consulting help for your specific project, please contact me offline using the email link at the top right of this page (altmany at gmail dot com).

    • Sainath M says:

      Thank You very much Yair for your message and concern, I will let you know if I need any help.

  2. ParangBoo says:

    I purchased!!
    I’m not sure this is the right place to say this, but, I began to read the first chapter of the book and saw ‘java.lang.Thread’ and was excited. But it was saddening to see no more explanation about it because that made me wonder if it is possible to write multithreaded m-file using Java interface. If Matlab allows m-file to only use java objects, not allowing java object to use m-files, then it might not be possible. (Note: I have no experience of Java.)
    Anyway, a great purchase!!
    Thanks for the work.

    • @ParangBoo – Matlab is indeed single-threaded in its computational engine, but you can launch and use Java threads as long as they don’t access the main Matlab thread. I explain some more about this in section 3.2. If you need to access the Matlab engine and/or data, consider using Matlab timers instead of Java threads.

      As to the other part of your question, accessing Matlab from within Java is the topic of the entire chapter 9. If you just need to access the m-file (i.e., the physical source-code text file) rather than Matlab code/data, then you can easily do this from within Java using Java’s extensive I/O capabilities.

    • Peter says:

      @ParangBoo, if you’re interested in multithreading in Matlab and have C++ experience, you can fall back on mex files for this. I recommend the Theron Actors library for simpler C++ multithreading although it is a little hard to get working within Matlab. More recent versions of Theron are even easier to setup and soon you’ll be able to use C++11’s std::thread instead of boost::thread which will simplify things a lot as well.

  3. Krisada says:

    First of all. Congratulation on your effort and the book. It is very useful.

    I read through a few chapters and could not find any examples on the following.

    How to instantiate JFrame and use Java Swing without javacomponent? I can do this with non-GUI Java package.

    I intent to try using standard Swing, JIDE and other Java package via Matlab command-line without the needs for Matlab figure containers.

    Thank you.

    • Krisada says:

      You also mentioned that JIDE docs refer to the latest JIDE version, but Matlab uses an older version,(com.jidesoft.utils.Lm.getProductVersion()) for code-freeze configuration reasons.

      Is it possible to add JIDE version of my choice to co-exist with Matlab pre-installed version, and force my own function to call/use my specific JIDE version?

      In this way, I will have more control over the JIDE versions, just in case the Mathworks decide to change something later.

      Thank you.

    • @Krisada – you can use a different JIDE release with Matlab, but this has been reported to cause problems with Matlab, so use the procedure with extreme care. Naturally, it depends on how far away your selected JIDE release is from Matlab’s.

      As for your other question, you can use the JFrame‘s show() method to display the frame window. You should really consult a good Java Swing reference if you’re planning to go down this route, because your question tells me that you don’t have much experience in this. Also keep in mind that you will have much difficulty if you ever wish to integrate Matlab controls/axes in such a pure-Java container.

  4. Neha Jain says:

    Well, I have been deploying codes through Matlab Java Builder for my lab project. My applications consist of deploying a 3D simulation(a robot simulation). Although, Matlab Java Builder JA helps me deploy the code but the animation for any simulation could not be achieved through Java builder. I believe that JMI wrapper can help me achieve in remote accessing MATLAB through client. Will this require to install MATLAB at the client end..?

    I would like to buy this book for implementing the above stated purpose. I would be grateful if you could provide me some tutorials for remote accessing Matlab through Java. So, that I can convince by boss to invest in the book.

    Thank you.

    • @Neha – you’re joking right? you need to invest hours of your time and mine in order to convince your manager to buy a relevant book at $50? are you so low-paid that your time is not worth this much? I am certainly not and the few dollars in royalties that I would get from your book copy is not a very large incentive for me to give you hours-worth of free consulting, so sorry.

  5. Marco Laudisio says:

    Hello Yair!!
    I am just entering in Matlab “world”…i aim to translate a Java code to Matlab code..i am not a java developer, i am just an user of a Java based application…I think that, starting from ZERO, i could have more possibility to learn to manage a Matlab code, better than a Java one…without needing to ask all time to our java developer to make the modification i need…just make it my own. But the first step, traslate the java source code into matlab…may be the most difficult i suppose. Your book called my attention…do You think it would be useful for my purpose? THANK YOU IN ADVANCE!! Marco

  6. akash garg says:

    Hi Yair,
    sir is there any way to introduced auto-complete feature just like in google search bar. And i had one standalone application created in matlab i want to create license for that is there any way to do same. Please kindly suggest me any way.

  7. Akash Garg says:

    Hi Yair,
    Sir is there any way to run rss feeds on matlab gui

  8. Is it possible to call Java code from matlab to do some fancy parallel distributed database work?

    Matlab database handing is too slow. I also hate that long long sql in Matlab. I want to use JAVA for example Hadoop to do the database work and transfer it back to the Matlab.

    I would love to consider buy the book!! Thanks!!

    • @Hongbo – yes, it is possible to do this and the book shows how. It even has a large section showing how to directly call an external Database from Matlab using JDBC.

  9. Aim Amraam says:

    Hi Yair,

    I’ve read the book but I’m not able to modify the icon of uigetfile.

    I use for the “figure”:

    javaFrame = get(hObject,'JavaFrame');
    javaFrame.setFigureIcon(javax.swing.ImageIcon(im2java(imread('icon.jpg'))));

    How can I modify the uigetfile icon?

    Best Regards,
    Aim

  10. Akash Garg says:

    Hello sir i want to run timer function in matlab :
    m create timer in following way but it not properly executed

    handles.t = timer('TimerFcn',{@test_Callback, handles},'Period',1,'ExecutionMode','fixedRate');
    function test_Callback(handles)

    my main concern is test_Callback uses all variables aur valuse define in main program for which i pass handles but it can’t work
    please suggest me some way to do it

  11. Gaurav says:

    Sir,
    I would like to know that if I create a GUI using JAVA then on the buttons can the MATLAB code be implemented?
    Thank you

  12. Gaurav says:

    I’m getting this error. Can anyone please explain why is this happening….?

    Error using .^
    Not enough input arguments.

  13. Matt says:

    Thank you for all of your posts and your book. Great Stuff!!

  14. Trevor says:

    Hi Yair,
    I’ve been interested in learning the ins and outs of integrating java into my gui’s for a while now. This book looks great but is the content still supported by more recent matlab versions?

  15. Uche says:

    Hello Yair,

    Any plans to release a new edition of the book “Undocumented Secrets of MATLAB-Java Programming”?

    Regards,
    Uche

  16. 吕弯弯 says:

    I’m a student from China,now i want to use Matlab’s function library in java project, ask u a question, can i get a matlab library where i can use all the matlab’s functions outside matlab without using “matlab builder for ja”;by the way ,can i read your book? do u have ebook? i am astudent ,i sorry to tell u that i have not enough money to pay for the really book.

    • You can use JNI or JMI to access Matlab from Java, but you need to have Matlab installed and running in order to do that – you cannot use the Matlab libraries directly without Matlab running unless you use the Java Builder product (which uses the MCR).

      As for an ebook – you can get it from the same place that you get the print book. You can ask your university department library to order a copy of the book.

Leave a Reply

Your email address will not be published. Required fields are marked *