Block Console Display When Creating Figures in Java
This example shows how to use waitForFigures
from a Java® application that you create using MATLAB®
Compiler SDK™. The object encapsulates MATLAB code that draws a simple plot.
Create a MATLAB function named
drawplot.m
with the following code:drawplot.m function drawplot() plot(1:10);
Build the Java package with the Library Compiler app or
compiler.build.javaPackage
using the following information:Field Value Library Name examples
Class Name Plotter
File to Compile drawplot.m
For example, if you are using
compiler.build.javaPackage
, type:buildResults = compiler.build.javaPackage('drawplot.m', ... 'PackageName','examples', ... 'ClassName','Plotter');
For more details, see the instructions in Generate Java Package and Build Java Application.
Create a Java program in a file named
runplot.java
with the following code:import com.mathworks.toolbox.javabuilder.*; import examples.Plotter; public class runplot { public static void main(String[] args) { try { plotter p = new Plotter(); try { p.drawplot(); p.waitForFigures(); } finally { p.dispose(); } } catch (MWException e) { e.printStackTrace(); } } }
In MATLAB, copy the generated
examples.jar
package into your current folder.If you used
compiler.build.javaPackage
, type:copyfile(fullfile('examplesjavaPackage','examples.jar'))
If you used the Library Compiler, type:
copyfile(fullfile('examples','for_testing','examples.jar'))
In a command prompt window, navigate to your work folder.
Compile the application using
javac
.On Windows®, type:
javac -classpath "
matlabroot
\toolbox\javabuilder\jar\javabuilder.jar";.\examples.jar runplot.javaOn UNIX®, type:
javac -classpath "
matlabroot
/toolbox/javabuilder/jar/javabuilder.jar":./examples.jar runplot.java
Replace
with the path to your MATLAB or MATLAB Runtime installation folder. For example, on Windows, the path may bematlabroot
C:\Program Files\MATLAB\R2024b
.Run the application.
On Windows, type:
java -classpath .;"
matlabroot
\toolbox\javabuilder\jar\javabuilder.jar";.\examples.jar runplotOn UNIX, type:
java -classpath .:"
matlabroot
/toolbox/javabuilder/jar/javabuilder.jar":./examples.jar runplot
The program displays a plot from 1 to 10 in a MATLAB figure window. The application ends when you dismiss the figure.
To see what happens without the call to
waitForFigures
, comment out the call, rebuild the application, and run it. In this case, the figure is drawn and immediately closes as the application exits.