0

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

Brandon
  • 41
  • 2
  • 5

3 Answers3

2

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.

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.

Community
  • 1
  • 1
Kris
  • 14,426
  • 7
  • 55
  • 65
  • 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 Apr 14 '10 at 22:18
2

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(...);
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
camickr
  • 321,443
  • 19
  • 166
  • 288
  • +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 Apr 15 '10 at 00:09
0

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

npinti
  • 51,780
  • 5
  • 72
  • 96