# Create Math formula image

The other day I came across an example where a formula written in a Java program could be represented as a standard equation on the screen.  I thought this was brilliant.  I recall back in my Uni days using the formula editor in Microsoft Word to present formulas.   Now I don’t have a use for this in Java yet but, you never know.  However, in case anyone out there does have a requirement to produce a formula from within their Java program then maybe this will help.

The challenge is to produce an output that looks like this:

So let’s take a look at this.

First off this example makes use of the third party library “JLaTeXMath – A Java API to render LaTeX” which is available under GNU licence and can be obtained from http://forge.scilab.org/index.php/p/jlatexmath/.

I chose to download the “JLaTeXMath minimal built for GeoGebra and MathGraph32” version which is a zip file and then extracted the JAR file and added this as an external library to my project.

Once in place then it’s a simple case to build a program to display the result.  Create a new class extending the JFrame class and include a main() method.

Assigned The formula to a string where the Java formula using the JLaTexMath controls is “L = \\frac {1}{2}[x^2 + y^2]^\\frac{1}{2}”.

Pass the formula string as a parameter when creating a TeXFormula object.  From the TeXFormula object call the createTeXIcon method passing the STYLE_DISPLAY constant from the TeXConstants class and the font point size which in this case I’m using 40.   There are other styles which can be used such as STYLE_SCRIPT so feel free to try out some of the options.

Create a BufferedImage and pass it width, height and the constant “BufferedImage. TYPE_4BYTE_ABGR”

Then call the paintIcon method of the TeXIcon object passing a container, a graphics object and zeros for the other two parameters which are used to adjust the size of the image in some cases.  For the container pass a new JLabel, for the graphics object pass the output of the getGraphics method from the BufferedImage.

To display our formula, create a JLabel and call the setIcon method for the label passing the TeXIcon object.

Finally we create a JPanel  to use as the main panel within our Frame and add the JLabel to the panel.  This panel is then added to our application frame, the frame is set as visible and the containers packed to use auto resizing.

That’s it, our formula is displayed within our Java application like this: