I'm trying to set the icon image of my JFrame. I can't figure out how to get the image file as a resource to be loaded using: Toolkit.getDefaultToolkit().getImage(URL);
I've heard of Class#getResource() but it won't work in my case as my file structure is:
com.faris.test.Test.class
com.faris.test.Test2.class
res.icon.png
My Test.class is the class that extends JFrame and is trying to fetch "icon.png", but I'm not sure how to get it as my class (Test.class) is in another folder. Any solutions to this?
It doesn't matter what folder your class is in. You can just use: Test.class.getResource("/res/icon.png");.
Make sure to include the '/'
at the beginning of the path.
Have you actually tried this?
Related
Im making a game with JavaFX and want to load images into it. Im having trouble with finding the correct URL to load the image
Its supposed to be a Memory game and the image is supposed to be loaded into a button for the player to interact with. Normally when I tried working with images, I start the URL at the projects folder and it works fine but here I keep getting error messages. I only get it to work when I type in the full URL from the C: Drive but shouldnt it also be possible to access it just from projects folder?
This is the constructor of the class for the Memory Cards
public MemoryCard(String front, int picID)
{
front = new ImageView(front);
picBack = new ImageView("src/grafics/back.jpg");
setGraphic(picBack);
//...
}
I have created a folder called 'grafics' under the source folder with the correct images inside. I thought this would work but it just gives me the IllegalArgumentException message on the line where I load the image.
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 am trying to display an icon on a button using the code posted below. But at run time, the console shows an NPE and highlights the code posted despite I am sure that the icon I wish to display on the button is placed in that path.
Note: the .. in the path is just a short for writing the whole path.
Code
ImageIcon iconplay = new ImageIcon (ClassLoader.getSystemResource("L:\\..\\..\\..\\..\\..\\..\\..\\..\\..\\Play.png"));
This is not a system resource, so don't try to use the system class loader. Something more like the following will use the context class loader.:
URL url = this.getClass().getResource("/path/to/the.resource");
That path starting with a drive letter is wrong. It should be a path relative to the class-path.
I created this card game in Java. What it does it it presents one card face up and 4 more cards face down. You wager from 1 to 100 coins and try to pick a higher card from the face down cards. If you pick a higher card, your wager is doubled and you can choose to go double or nothing on another round.
The program uses 3 .java files in one package:
HigherNumber: Main class, contains the bulk of the code.
Deck: Contains definition for a class representing a deck of cards.
Card: Contains definition for a class representing an individual card.
So naturally, this program uses a lot of pictures, to represent the cards. In my original implementation, I just passed ImageIcon a string to represent the location of the cards. So like, for the icon for a face down card,
faceDown = new ImageIcon("multimedia/redBack.gif");
When I did this, the program ran perfectly when run through Eclipse. So I used Eclipse to Export to a runnable JAR file. This JAR file then ran without a problem, except if I moved the JAR file anywhere else, none of the images showed up.
So I researched and found out about using URLs to combat this. I reworked the program to use URLs, so now I have stuff like this:
//Set URL for default faceDown icon.
faceDownURL = this.getClass().getResource(pictureRoot +"redBack.gif");
//Set location for default back face of cards.
faceDown = new ImageIcon(faceDownURL);
Now it runs fine in Eclipse, but I cannot get the exported runnable JAR to work. When run from Windows, it just kinda blinks and does nothing. When I run through the command line, I get this:
C:\Documents and Settings\mstabosz>java -jar C:\Temp\HigherNumber.jar
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at higherNumber.Card.setImage(Card.java:150)
at higherNumber.Card.<init>(Card.java:36)
at higherNumber.Deck.<init>(Deck.java:22)
at higherNumber.HigherNumber.<init>(HigherNumber.java:16)
at higherNumber.HigherNumber.main(HigherNumber.java:857)
Trying to follow this code, it looks like the source of the problem is in the Card class at line 150. At line 150, the class is in the setImage() function, which is building a string called iconName to be used to set the image for each card as it is created. It then returns an ImageIcon to the Card class's constructor.
//Set up the icon for the card.
this.cardIcon = setImage();
Line 150 is the return statement. Here are the statements that create the URL cardIconURL which is used in the ImageIcon.
//Create a URL based on the constructed string.
URL cardIconURL = this.getClass().getResource(iconName);
return new ImageIcon(cardIconURL);
I just don't get what's going wrong here. The program worked fine as a runnable JAR when I was using Strings instead of URLs. It works fine when run through Eclipse. It doesn't work as a runnable JAR now.
I did read up on something called manifests, which I had trouble understanding. I did have Eclipse generate a manifest for this program:
Manifest-Version: 1.0
Main-Class: higherNumber.HigherNumber
What am I missing?
i use something like:
URL myurl = this.getClass().getResource("file.png");
myIconImage = Toolkit.getDefaultToolkit().getImage(myurl);
you're doing:
return new ImageIcon(cardIconURL);
Maybe try my second line. Also i store the images in the jar.
Okay it looks like I got the image files in the runnable JAR by dragging and dropping the "multimedia" folder which contains the pictures into the "highernumber" package in Eclipse. I'm still getting the NullPointerException though.
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")));