这是我用于按钮点击事件的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();
}
答案 0 :(得分:0)
您收到该错误是因为args[0]
和args[1]
只能在主方法中使用Java访问:
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!
}
}