I made a GUI in java swing, however I have made many python scripts for the functions of that GUI, is there anyway that I can use my python scripts to display the content in the Java Swing GUI interface? Thanks!
2 Answers
Check out Jython ( http://www.jython.org/ )
It's a python implementation in Java.
In theory you shouldn't have to change your python code (if it "good quality"), but in practice I suggest that you will have to make some changes here and there. I don't personally use Jython, but all the various python implementations are usually more-or-less compatible, but not identical. You won't be able to use python libraries that rely on the C ABI, but pure python scripts should work.
2 Comments
You probably wouldn't want to do this for a final version of your app, but for a quick and dirty approach you can run external programs in java and capture the output. (I've used this before when I was in the process of porting a program from python to java and wanted to see if the java frontend was working before the java back end was finished, without worrying about replacing CPython modules.) This example program runs the python program test.py and prints the output:
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
}
}
This is super patchy, so, again, I'd only use it for temporary testing purposes. But for those cases, it is really helpful.