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:

    function drawplot()
  2. Build the Java package with the Library Compiler app or using the following information:

    Library Nameexamples
    Class NamePlotter
    File to Compile drawplot.m

    For example, if you are using, type:

    buildResults ='drawplot.m', ...
    'PakageName','examples', ...

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

  3. Create a Java program in a file named with the following code:

    import com.mathworks.toolbox.javabuilder.*;
    import examples.Plotter;
    public class runplot 
      public static void main(String[] args) 
          plotter p = new Plotter();
        catch (MWException e)
  4. In MATLAB, copy the generated examples.jar package into your current folder.

    • If you used, type:

    • If you used the Library Compiler, type:

  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
    • On UNIX®, type:

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

    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.