Java in Brainstorm
Author: Martin Cousineau
Java is a multi-platform and object-oriented programming language. Matlab supports its execution in order to facilitate writing more complex graphical user interfaces and applications.
You have to keep in mind that not every Matlab versions ship with the same version of the Java Virtual Machine (JVM). See this Wikipedia page for specific JVM versions for each release of Matlab. With the general objective of supporting older Matlab versions (2008 to today), we need therefore to support Java 6 to 8.
The main Brainstorm repository only ships with a compiled JAR file as the raw Java code is not of use to regular users. To access to the raw Java code used by Brainstorm, refer to this repository: https://github.com/brainstorm-tools/bst-java
It also includes the necessary project files to open the repository as a project in the popular Java IDE Netbeans which we recommend for writing and testing your Java code.
Pushing your changes to Matlab
Once you are satisfied with and tested your changes in your Java IDE, you need to push your changes to MATLAB.
First, you need to compile a JAR file of your changes. In Netbeans, go to Run -> Clean and build project.
You can find your compile JAR file under <java repository>/bst-java/brainstorm/dist/brainstorm.jar
- Then, you need to make sure Brainstorm and Matlab are shut down.
Copy your newly created brainstorm.jar file to overwrite <brainstorm repository>/brainstorm3/java/brainstorm.jar
- Start Matlab and Brainstorm, and your new Java code is now available.
Calling Java functions in Matlab
Calling Java functions is extremely easy from Matlab, as documented here on the official Mathworks website.
- First, make sure the JAR file you need to access is in the Java classpath. If your changes are in the brainstorm.jar, this is already loaded when Brainstorm starts.
- Then, in the Matlab function are writing, you need to first import all required Java classes you are going to use. You can import all classes of a package using the start (*). Make sure the import process is the line(s) of code of your Matlab function.
import org.brainstorm.dialogs.HotkeyDialog; import org.brainstorm.dialogs.*;
- You are then free to instanciate and call any public functions of your imported classes in the Matlab code as if this was Java code. Just make sure to feed inputs of the appropriate format to the functions (i.e. if it expects a string, feed it a string).
dialog = HotkeyDialog(12); res = dialog.getKey();
Creating Java Swing elements for GUIs
To create Java objects for GUIs, Brainstorm already has wrappers in place to simplify and harmonize the process accross the program. Refer to the gui_component() function to do this. Also, have a look at the CreatePanel() function of any panel_ file to see examples of creating Swing GUI elements in Matlab.