Main Content

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.

  1. Create a MATLAB function named drawplot.m with the following code:

    drawplot.m
    function drawplot()
    plot(1:10);
  2. Build the Java package with the Library Compiler app or compiler.build.javaPackage using the following information:

    FieldValue
    Library Nameexamples
    Class NamePlotter
    File to Compile drawplot.m

    For example, if you are using compiler.build.javaPackage, type:

    buildResults = compiler.build.javaPackage('drawplot.m', ...
    'PakageName','examples', ...
    'ClassName','Plotter');

    For more details, see the instructions in Generate Java Package and Build Java Application.

  3. 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();
        }
      }
    }
  4. 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'))
  5. In a command prompt window, navigate to your work folder.

  6. Compile the application using javac.

    • On Windows®, type:

      javac -classpath "matlabroot\toolbox\javabuilder\jar\javabuilder.jar";.\examples.jar runplot.java
    • On UNIX®, type:

      javac -classpath "matlabroot/toolbox/javabuilder/jar/javabuilder.jar":./examples.jar runplot.java

    Replace matlabroot with the path to your MATLAB or MATLAB Runtime installation folder. For example, on Windows, the path may be C:\Program Files\MATLAB\R2024a.

  7. Run the application.

    • On Windows, type:

      java -classpath .;"matlabroot\toolbox\javabuilder\jar\javabuilder.jar";.\examples.jar runplot
    • On 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.