2

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 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Would I have to convert all my scripts?
@user1510602 It's a python implementation in Java. Check out their documented differences.
0

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.

1 Comment

I found a better solution, jymatisse, a swing GUI builder but can have the backing code in python, javaforge.com/project/11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.