views:

260

answers:

3

I've been trying to load up an image dynamically in runtime for the longest time and have taken a look at other posts on this site and have yet to find exactly the thing that will work. I am trying to load an image while my GUI is running (making it in runtime) and have tried various things. Right now, I have found the easiest way to create an image is to use a JLabel and add an ImageIcon to it. This has worked, but when I go to load it after the GUI is running, it fails saying there is a "NullPointerException". Here is the code I have so far:

p = Runtime.getRuntime().exec("python C:\\FaceVACS\\roc.py " + "C:/FaceVACS/OutputCMC_" + target + ".txt " + "C:/FaceVACS/ROC_" + target + ".png");
Icon graph = new ImageIcon("C:\\FaceVACS\\OutputCMC_" + target + ".png");
roc_image.setIcon(graph);
panel.add(roc_image);
panel.revalidate();
gui.frame.pack();

I tried panel.validate(), panel.revalidate(), and I've also tried gui.getRootPane(), but I can't seem to find anything that will work.

Any ideas would be helpful! Thanks

+2  A: 

getRuntime().exec is for launching an external program. To simple load a file to use in your Java application you can simply treat it like any other file. Indeed if you are using Swing, the ImageIcon constructor will take a String containing the file path as an argument.

http://stackoverflow.com/questions/299495/java-swing-how-to-add-an-image-to-a-jpanel

The above question explains how to add an image to a JPanel and this can be done at runtime by an event handler.

Kris
I was sort of giving context for why I'm adding an image with the p.Runtime.getRuntime().exec()...that is just running a python script that saves out the image I am looking to post. It has nothing to do with the image except for generating it.
Brandon
A: 

You can also use labels to display images. This tutorial shows you how.

npinti
roc_image is a label...therefore it's already being added to a label.
Brandon
+2  A: 

that is just running a python script that saves out the image I am looking to post

Sounds like the problem is that the code is trying load the image before the python script finishes creating the image. Try:

Process p = Runtime.getRuntime().exec("...");
p.waitFor();
Icon icon = new ImageIcon(...);
camickr
+1 for `waitFor` The whole processing ( invoking the script and waiting for the result ) should be run in a separate thread though. Otherwise it will freeze the UI. Later it should call `SwingUtilities.invokeLater` to update the UI
OscarRyz