Paint Math expression using JXGraph - Java 2D Graphics

Java examples for 2D Graphics:JXGraph

Description

Paint Math expression using JXGraph

Demo Code

import java.awt.Color;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;
import org.jdesktop.swingx.JXGraph;
import org.nfunk.jep.JEP;
import org.nfunk.jep.function.Round;
import org.jdesktop.swingx.JXGraph;

public class GraphJX extends JFrame implements Runnable {

    public GraphJX(ExpressionPlot exp) {
        createGraphDemo(exp);//from  www. j  av  a 2  s.co  m

    }

    private void createGraphDemo(ExpressionPlot exp) {

        Point2D origin = new Point2D.Double(0.0d, 0.0d);
        Rectangle2D view = new Rectangle2D.Double(-10.0d, -10.0d, 20.0d,
                20.0d);
        JXGraph graph = new JXGraph(origin, view, 5, 5, 3, 3);
        //JXGraph.Plot d = new ExpressionPlot("x^4-((7*x)^3)+(18*x)-(20*x)+8"); 
        //JXGraph.Plot d = new ExpressionPlot("(cos(x))^2 + 6 -x");           // anhi lang try ug butang sa expression like sin(x), polynomials
        JXGraph.Plot d = exp;
        graph.addPlots(Color.red, d);

        getContentPane().add(graph);
        pack();
        setVisible(true);
        setTitle("The Graph");
    }

    public static void main(String args[]) {
        GraphJX graph = new GraphJX(new ExpressionPlot("cos(x)-x"));
        Thread worker = new Thread(graph);
        worker.start();
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub  
    }
}
/*
 * ExpressionPlot.java
 *
 * Created on 16 mars 2006, 15:44
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */


class ExpressionPlot extends JXGraph.Plot {
    private final String expression;
    private final JEP parser;
    private int precision;

    public ExpressionPlot(String expression) {
        this.expression = expression;

        parser = new JEP();
        parser.addStandardConstants();
        parser.addStandardFunctions();
    }

    public double compute(double value) {
        parser.addVariable("x", value);
        parser.parseExpression(expression);

        return Round(parser.getValue(), 6);
    }

    //wa ni labot test rani
    public static void main(String args[]) {
        //test
        ExpressionPlot e = new ExpressionPlot("x^2");
        System.out.print(e.getValue());
    }

    private String getValue() {
        // TODO Auto-generated method stub
        return this.expression;
    }

    public static double Round(double d, int Rpl) {
        float p = (float) Math.pow(10, Rpl);
        d = d * p;
        float tmp = Math.round(d);
        return (double) tmp / p;
    }

}

Related Tutorials