Math Formula in Java

The challenge in this tutorial is to present a mathematical formulas written in LaTeX within our application. 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 forge.scilab.org – jlatexmath. 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 included a main() method.

Download source code and art work
(you will need to provide an email address)

 

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 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.