2013-05-29 17 views
0

這是我的一個按鈕點擊事件的Java代碼。我想要做的是將一個參數傳遞給我正在調用的python文件...但是我得到的錯誤爲args[0]args[1]cannot find symbol)。將參數從Java傳遞到Python時出錯?

我該如何避免這個問題?如何將參數傳遞給我以這種方式調用的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

args沒有在這個方法中聲明,所以它不能被我引用。您想做什麼? args是數組持有Java程序的啓動參數嗎? – Djon

+0

我想參數傳遞到從Java蟒蛇,告訴我沒有辦法做到這一點.. – eddy

回答

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! 
    } 
} 
+0

公共靜態無效的主要(字符串ARGS []){ 了java.awt.EventQueue.invokeLater(新的Runnable(){ 公衆void run(){ new test1()。setVisible(true); } });如果我們的main包含這個,那麼我將如何傳遞它 – eddy

+0

您將需要獲取主方法提供的'args []'並將它們複製到您在Runnable之外聲明的'final'字符串數組中。這將允許您在創建的Runnable對象內訪問這個新的(複製的)數組。其餘的和我的答案一樣。 – Jamie

+0

看到這裏的一個(完全工作)的例子:http://pastebin.com/xKDZ3L8P – Jamie