开发者

How to add an image dynamically at runtime in java

开发者 https://www.devze.com 2022-12-26 17:08 出处:网络
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

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


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.


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(...);


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号