How to add an image dynamically at runtime in java - java

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.

Related

How can I add picture as a JButton background?

I'm trying to add an image to JButton so there will be some kind of icon. And I'm not sure where is my mistake. When I run the following code, there is no changes in how button looks.
ImageIcon img = new ImageIcon("img.bmp");
JButton button = new JButton(img);
frame.add(button);
I've already tried to debug my code, although there was nothing useful.
Where is img.bmp stored relative to the
"working directory"?
ImageIcon (String) expects to find a
file on the disk, in this case, in the root of
the "working directory". If you don't know
the working directory, add
System. out.println(System.getPro
perty("user.dir")); to your code,
the image you're trying to load should be
stored there. The problem with this though,
is the working directory can change. You'd
be better of using embedded resources

Unable to set icon for java application using setIconImage() method

I'm trying to create one simple GUI based testing tool in Java using Eclipse. I have been trying to add icon to my application. Images are present inside the project in a folder. Could you please suggest what mistake I'm doing.
I'm used below two ways, unfortunately both are not helping me. -
1.) frame.setIconImage(image).
2.) setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(Filepath)));
Below is the setup of my project in Eclipse -
Below is code which i'm using -
public static void main(String[] args) {
JFrame frame = new JFrame("Testing Tool");
// setting close operation
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// sets 500 width and 600 height
frame.setSize(500, 600);
try {
Image image = new ImageIcon("/Project_T/Images/biplane.jpg").getImage();
frame.setIconImage(image);
} catch(Exception e) {
System.out.println("Application icon not found");
}
// uses no layout managers
frame.setLayout(null);
// makes the frame visible
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
Since i'm going to create an .exe file for this project using lunach4J, is this the way of keeping files (placing them in a folder of project since I would be using multiple images and files) that ensures the application running on any machine.
This is the code I used with a Swing application packaged in an executable JAR file. The JFrame has the icon image.
private static final String APP_ICON_PATH = "myapp/icondirectory/report.png";
ImageIcon icon = new ImageIcon(ClassLoader.getSystemResource(APP_ICON_PATH));
frame.setIconImage(icon.getImage())
The "myapp" is the root of my package structure; e,g., the GUI class using the frame is in the package myapp.gui package. The image PNG files are within the application's executable JAR file (as you see in the code within a separate folder).
Also, look at the Oracle's Java Swing tutorials explain the usage of icons.
I fiddled a lot and finally found a way out , since my explanation was a bit long so I thought of writing an answer. Also please suggest that is this a good way since we would be exporting our project.
Java gives you the power to change the ICON for your application with the help
of setIconImage(image), but this method is not that direct, since we are
dealing with multiple files those should be present while executing the code so we
would have to ensure that their paths are correct and accessible in order to run smoothly.
Hence we save our files inside the src by creating another folder and from there
we can import the files easily. Follow these steps
Step - 0 - Place the files inside src folder of the project
Put the files inside the scr folder by creating another folder, here I created another folder by the name of images and placed my files there, hence the file path would be
"Images/biplane.png",
please ensure that there are no "/" placed before Images (our folder name)
Step - 1 - Place the file path inside a URL variable
Step - 2(Optional) - Print this URL variable to cross check that this is not null. If this is null check your path again and repeat the activity so that this value is not null.
Step - 3 - Now pass this URL to ImageIcon method.
Step - 4 - Call the setIconImage method with that image.
Code Used -
URL url = test.class.getClassLoader().getResource("Images/biplane.png");
System.out.println("Path for file is :- \"" + url + "\"");
Image image = new ImageIcon(url).getImage();
frame.setIconImage(image);

How can I disable a dialog in ImageJ?

I'm using ImageJ a lot to look at image stacks composed of a number of single images sitting in one folder. I can just drag and drop the respective folder into the ImageJ GUI and it creates a scrollable visualization, which is very convenient. It could be even more convenient though since each time I do it, a dialog appears asking whether I want to open all images in the folder as a stack. Is it possible to make it default to "Yes"? Would I need to change the source code and compile it myself..? If that is the case, where could I start looking?
A suggestion would be to make a feature request to the author of Imagej Wayne rasband, e.g., at the Github repository:
https://github.com/imagej/imagej1
Or you can write a small macro (use the macro recorder with the menu actions!) which can be also be installed in ImageJ. Something like:
run("Image Sequence...", "open=C:\\images\\ sort");
Here the macro docs:
https://imagej.nih.gov/ij/developer/macro/macros.html
https://imagej.nih.gov/ij/docs/guide/146-14.html
To disable the dialog in the source code: Find the source file ij>plugin>DragAndDrop.java. From its openDirectory method, delete the dialog-related lines and assign boolean values to convertToRGB and virtualStack, both of which are normally defined by check boxes in the now defunct dialog window. The code should now look like this:
private void openDirectory(File f, String path) {
if (path==null) return;
if (!(path.endsWith(File.separator)||path.endsWith("/")))
path += File.separator;
String[] names = f.list();
names = (new FolderOpener()).trimFileList(names);
if (names==null)
return;
convertToRGB = false;
virtualStack = false;
String options = " sort";
if (convertToRGB) options += " convert_to_rgb";
if (virtualStack) options += " use";
IJ.run("Image Sequence...", "open=[" + path + "]"+options);
DirectoryChooser.setDefaultDirectory(path);
IJ.register(DragAndDrop.class);
}
I did this with ImageJ 1.51p. The source code can be downloaded here. After making these changes, just run the build.xml ant script.
Note that writing a macro might provide a cleaner and more portable way to achieve this--refer to Marcel's answer for further reading.

Cannot create image from getResourceAsStream() in JavaFX projects

I cannot create an image in any of my JavaFX projects using the following kind of code:
final String url = "line.jpg";
Image image = new Image(Config.class.getResourceAsStream(url));
because there is always a null pointer exception pointing to the second line. Obviously, I have checked that the image file is in the correct directory. I have tried example programs, some directly copied from these boards, but these also fail for the same reason.
I suspect I lack a resource in Netbeans or JavaFX but I can't figure out what is missing.
The only workaround appears to be to include the image file in a css stylesheet and link it to the program by setting the gui components id like this:
Button homeButton = new Button();
homeButton.setId("homebutton");
In the stylesheet there is:
#homebutton {
-fx-background-image: url("images/homebtn.jpg");
-fx-pref-width: 30;
-fx-pref-height: 30;
}
Its not ideal being forced into this solution and Swing seems far better at dealing with image files. I assume a bug in JavaFX that always causes the following to fail:
Image image = new Image(Config.class.getResourceAsStream(url));

Get image from relative path

In my project I have 2 packages.
images - contain images and
notification - contain java files
In notification/main.java I get Image object from image using this code
Image image = Toolkit.getDefaultToolkit().getImage("/images/key-16x16.png");
and I can't get image.
How can I fix this bug.
I'm using Netbeans to develop Java desktop application and I have solved my problem.
Image image = new ImageIcon(this.getClass().getResource("/images/bell-icon16.png")).getImage();
"this" is a class extends JFrame
/ means an absolute path, save Java web-apps where / means relative to context. So, I would suggest to use relative URL, means get rid of that / in front, and then provide the right path.
In case, even then you can't solve it, try to create a file on the same path you are looking for image. This way you will know that where you are looking exactly and where you should look.
You could also try
Image image = new ImageIcon(path).getImage();
Incase the solution above doesn't work, try this (which worked for me):
Image image = Toolkit.getDefaultToolkit().createImage(this.getClass().getResource("/Images/bell-icon16.png"));
i've also been on this and it turns out that you need to create a package inside of your src folder.
for instace if you create a package called images inside of the src folder, your relative path will be
/images/yourimage.png.
Notice that the slash(/) must be there!
more info here http://forums.macrumors.com/showthread.php?t=533922
it worked for me
Toolkit tk = Toolkit.getDefaultToolkit();
Class<? extends JFrame> j = YOURJFRAME.getClass();
Image image = tk.createImage(j.getResource("/images/bell-icon16.png"));
Try that code, if you have a JFrame that will work.
If you have an Applet, then just use
Toolkit tk = Toolkit.getDefaultToolkit();
Image image = tk.createImage("images/bell-icon16.png");
With applets you never want to use the / in the beginning, but if you have a JFrame, and you are using getResource, you need the / in the beginning of the Path.
SwingResourceManager.getImage(YourClass.class,"key-16x16.png");
The getIcon method will return Icon as similar
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("../resources/MainIcon.png")));

Categories

Resources