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
Related
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);
I'm using a Jlabel imageIcon to display my image
when I set the path of the image in a local machine it works perfectly but when I change the path to an image which is located in an other machine(NAS Server in my case) nothing displays and yet no problem is raised can any one help me.
here is a code snippet:
ImageIcon imic= new ImageIcon(new ImageIcon(path).getImage().getScaledInstance(imgshow.getWidth(), imgshow.getHeight(), Image.SCALE_SMOOTH));
imgshow.setIcon(imic);
Any help I'll be thankful
You said "NAS Server in my case". Could we assume it's a normal "Samba" share ?
I am working on GUI java project which contains FileChooser(combined with JLabel it becomes ImageChooser) and JTextArea (inside of JScrollPane). Both of these components are inside of JPanel.
When ever I ran it inside of IntelliJ Idea (version 2017.2.4)everything works fine:
UI when executed from IDE
But if I build Artifacts and create .jar file, then image inside of JLabel is not initialized and the size(height) of JTextArea becomes minimal(though minimal value is set to 200):
IU when executed from .jar file
I suspect that ImageIcon cannot be initialized due to relative path I provide:
...
imagePath = "src/main/resources/" + item.getImageName();
//item.getImageName() returns a proper image name, tested with
//System.out.println() and there is a proper image in that folder.
ImageIcon img = new ImageIcon(imagePath);
img = ImageManager.resize(img);
...
//Resize function in ImageManager class
public static ImageIcon resize(ImageIcon imageIcon, int size){
return resize(imageIcon, size, size);
}
public static ImageIcon resize(ImageIcon icon){
return resize(icon, defaultSize);
}
However, I've tried options with relative path like main/resources/ and /main/resources/ , but none of them worked both in IDE and .jar executable.
Is it a problem with a path?
If yes, why does it affect JTextArea's size?
P.S.
JTextArea's size becomes normal if there is an image in JLabel.
You are right, the way you fetch resources is problematic in a jar.
The way you should access them:
ImageIcon img = new ImageIcon(this.getClass().getClassLoader().getResource(item.getImageName()));
This method supports relative paths. Just make sure your src/main/resources directory is properly marked as a 'Resource Root' in IntelliJ IDEA.
I am using the NetBeans GUIBuilder to make a JPanel Form. I added a JLabel and used NetBeans' interface to give it an icon from an external image (.png). The path is verified and the image shows up on the GUIBuilder screen. It even shows up when I click the "Preview Design" button. It DOES NOT show up when I RUN the project. The rest of the GUI appears as it should. Do any of you know why this happening and/or how to fix it?
A lot of you have been asking for an SSCCE. Since the code is generated by the NetBeans Form Builder, I have instead included the steps I took to make the JLabel. The areas of focus are circled in red.
Drag and drop a JLabel into the Form Builder.
Open up the JLabel's properties menu. Enter the empty string ("") for the text field. Click the ellipsis next to icon.
Select External Image and click the ellipsis.
Select the image of choice. In my case it's a .png.
Notice that the image appears in the icon preview.
Close the icon menu and the properties menu, and notice that the image appears as the JLabel's icon on the Form Builder.
Thank you for accepting an unorthodox SSCCE and thank you in advance for your help.
I found out the hard way that relying on Netbeans GUI builder to do everything for you is a mistake.
Just create an icon fetching class like the one below, put the icons in it's package, and use "Custom code" instead of "Image chooser". Sure the icons will not be visible inside NB. But if they show up when the app is running, who cares about that.
package com.example.resource.icons;
import javax.swing.ImageIcon;
public class IconFetch {
private static IconFetch instance;
private IconFetch(){
}
public static IconFetch getInstance() {
if (instance == null)
instance = new IconFetch();
return instance;
}
public ImageIcon getIcon(String iconName) {
java.net.URL imgUrl = getClass().getResource(iconName);
if (imgUrl != null) {
return new ImageIcon(imgUrl);
} else {
throw new IllegalArgumentException("This icon file does not exist");
}
}
public static final String MINESWEEPER_ONE = "one.png";
}
Usage:
IconFetch.getInstance().getIcon(IconFetch.MINESWEEPER_ONE);
If the icon still doesn't show up after trying this, then something might be wrong with the way you layed out components in your form (the label is there but you can't see it).
Hope this helps even though it's a long shot.
I had the same problem, and predi's solution wasn't working either. Then I created a package instead of a folder, and added the images there, and it works now.
I do have a same problem also. But I found the solution.
I create the package in project and put the images inside there.
When I build the project, Netbeans will create 'target' folder and build .class files.
I found that the images that I copied to the package, did not transfer to the 'target' folder.
Interim solution.
4. I copy all image to target folder with the same structure. Then I can run the project directly from Netbeans.
5. Incase you clean the project. Do no.4 again.
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.