I'm trying to make a simple function drawer in Java. I'm using the ScriptEngine API to parse the equation from a string, but it gets very slow while drawing. Is there another way to do the same thing? Here is the code:
private String v;
@Override
public void init(){
setSize(600,600);
v = JOptionPane.showInputDialog("Input function:");
}
@Override
public void paint(Graphics g){
drawQuadrants(g);
drawEquation(g);
}
private void drawEquation(Graphics g) {
g.setColor(Color.BLUE);
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
v = v.replace("sin", "Math.sin")
.replace("cos", "Math.cos")
.replace("sen", "Math.sin")
.replace("tan", "Math.tan")
.replace("tg", "Math.tan")
.replace("log", "Math.log")
.replace("Log(x)","(Math.log(x)/Math.LN10)");
for(double x0 = -10;x0<=10;x0+=0.001){
engine.put("x", x0);
try {
double y0 = (Double)engine.eval(v);
drawPoint(g,x0,-y0);
} catch (HeadlessException | ScriptException e) {
e.printStackTrace();
}
}
}
private void drawQuadrants(Graphics g) {
g.setColor(Color.BLACK);
g.drawLine(0, 300, 600, 300);
g.drawLine(300, 0, 300, 600);
g.setFont(new Font("Arial",Font.BOLD,15));
g.drawString("x", 580, 320);
g.drawString("y", 280, 20);
for(int l = 0;l<=600;l+=30){
g.drawLine(l, 297, l, 303);
}
for(int l = 0;l<=600;l+=30){
g.drawLine(297, l, 303, l);
}
}
private void drawPoint(Graphics g, double x0, double y0) {
int newx0 = (int)map((float)x0, (float)-10, (float)10, (float)0.0, (float)600.0);
int newy0 = (int)map((float)y0, (float)-10, (float)10, (float)0.0, (float)600.0);
g.drawOval(newx0, newy0, 1, 1);
}
public static final float map(float value, float start1, float stop1, float start2, float stop2)
{
return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1));
}
g.setFont(new Font("Arial",Font.BOLD,15));would better beg.setFont(new Font(Font.SANS_SERIF,Font.BOLD,15));since a) It provides compile time checking and b) It will select an undecorated font on whatever system it is running, as opposed to those systems that have Arial font installed.