0

这是我用于按钮单击事件的 Java 代码。我想要做的是将参数传递给我正在调用的python文件......但我得到了args[0]args[1]cannot find symbol)的错误。

我怎样才能避免这个问题?如何将参数传递给我以这种方式调用的 Python 文件?

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

try { 
    PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
    PythonInterpreter interp = new PythonInterpreter();

    interp.set("firstName", args[0]);
    interp.set("lastName", 1);
    interp.execfile("‪C:\\Users\\aswin-pc\\Desktop\\pythontest.py");
}
catch (Exception e) {
    e.printStackTrace();
}  
4

1 回答 1

0

您收到该错误是因为args[0]并且args[1]只能在 Java 中从 main 方法中访问:

public class Test {

    public static void main(String[] args) {
        System.out.println(args[0])    // You can access it here!
    }

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
        System.out.println(args[0])    // Will throw exception, you can't access it here!
    }
}

相反,您应该尝试args在创建类时将其传递给您的类:

public class Test {

    private String[] args;

    public Test(String[] args) {
        this.args = args;    // Sets the class args[] variable from the passed parameter
    }

    public static void main(String[] args) {
        Test myTest = new Test(args);
    }

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
        System.out.println(args[0])    // You can now access the class variable args from here!
    }
}
于 2013-05-29T09:34:22.593 回答