使用Jtextfield的值作为java代码

Uni*_*rse 0 java jtextfield textfield

我正在开发一个小应用程序,我希望得到一个数学函数,并且x(a,b)的范围显示它的图形.

在某些方面,我调用一个执行x函数的方法.我正在堆栈,我从TextField获得函数(例如f(x)= 2*x + 1)并将其用作Java代码

让我们说:

class Myclass extends JFrame{
    blah blah ...
    JLabel lblFx =new JLebel("f(x=)");
    JTextfield Fx = new JTextField();

    //and lets say that this method calculate the f(x).
    //get as argument the x
    double calculateFx(double x){
        return  2*x+1; // !!!!BUT HERE I WANT TO GET THIS 2*x+1 FROM TextField!!!!!
    }

}
Run Code Online (Sandbox Code Playgroud)

任何的想法?

ass*_*ias 5

您可以使用ScriptEngine.请参阅下面的示例,您可以调整以使用JTextField的内容.

注意:"2x+1"不是有效的表达式,您需要包含所有运算符,因此在这种情况下:"2*x+1".

public static void main(String[] args) throws ScriptException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");

    String formula = "2 * x + 1"; //contained in your jtextfield

    for (double x = 0; x < 10; x++) {
        String adjustedFormula = formula.replace("x", Double.toString(x));
        double result = (Double) engine.eval(adjustedFormula);
        System.out.println("x = " + x + "  ==>  " + formula + " = " + result);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

x = 0.0  ==>  2 * x + 1 = 1.0
x = 1.0  ==>  2 * x + 1 = 3.0
x = 2.0  ==>  2 * x + 1 = 5.0
x = 3.0  ==>  2 * x + 1 = 7.0
x = 4.0  ==>  2 * x + 1 = 9.0
x = 5.0  ==>  2 * x + 1 = 11.0
x = 6.0  ==>  2 * x + 1 = 13.0
x = 7.0  ==>  2 * x + 1 = 15.0
x = 8.0  ==>  2 * x + 1 = 17.0
x = 9.0  ==>  2 * x + 1 = 19.0
Run Code Online (Sandbox Code Playgroud)