2012-07-16 44 views
1

我在java swing中創建了一個GUI,但是我爲該GUI的功能製作了很多python腳本,有沒有可以使用我的python腳本在Java Swing GUI界面中顯示內容?謝謝!在Java GUI中使用Python

回答

3

退房的Jython(http://www.jython.org/

這是Java中的一個Python實現。

從理論上說,你不應該有改變你的Python代碼(如果它「品質優良」),但在實踐中,我建議你將不得不在這裏和那裏做一些改變。我不親自使用Jython,但所有各種python實現通常或多或少兼容,但不完全相同。您將無法使用依賴於C ABI的Python庫,但純Python腳本應該可以工作。

+0

我需要轉換所有腳本嗎? – enginefree 2012-07-16 15:50:05

+0

@ user1510602這是Java中的python實現。查看他們記錄的差異。 – Marcin 2012-07-16 15:51:48

+0

@ user1510602:在已編輯的回覆中回答。 :) – Arafangion 2012-07-16 15:52:26

0

您可能不想爲此應用程序的最終版本執行此操作,但對於快速而骯髒的方法,您可以在java中運行外部程序並捕獲輸出。 (之前我曾經使用過這個功能,當時我正在將一個程序從python移植到java的過程中,並希望在java後端完成之前查看java前端是否工作,而不用擔心替換CPython模塊。)這個示例程序運行Python程序test.py並打印輸出:

import java.io.*; 

class Jexec{ 
    public void Jexec(){} 

    private String exec(String execStr){ 
    try{ 
     // run process and capture stdout 
     Process p = Runtime.getRuntime().exec(execStr); 
     InputStream s = p.getInputStream(); 

     // convert stdout to a string 
     BufferedReader br = new BufferedReader(new InputStreamReader(s)); 
     StringBuffer sb = new StringBuffer(); 
     String line; 
     while ((line = br.readLine()) != null) { 
     sb.append(line).append("\n"); 
     } 
     String output = sb.toString(); 

     p.destroy(); 
     return output.toString(); 

    }catch(Exception e){ 
     //actually handle the error here 
     e.printStackTrace(); 
     return String.format("*** Running \"%s\" failed. ***",execStr); 
    } 
    } 

    public static void main(String[] args){ 
    Jexec je = new Jexec(); 
    System.out.println(je.exec("python test.py")); //in your case, you would use the output instead of just printing it 
    } 
} 

這是超級片狀,所以,再一次,我只用它來臨時測試目的。但對於這些情況,這真的很有幫助。

+0

我發現了一個更好的解決方案,jymatisse,一個Swing GUI生成器,但可以在Python的支持代碼,http://javaforge.com/project/11 – enginefree 2012-07-16 18:20:15