I have added an image for my button,but when I run that frame this exception will be thrown .why?please help me.
init:
deps-jar:
compile-single:
run-single:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:138)
at ClientGUI.IdAndPasswordFrame.initComponents(IdAndPasswordFrame.java:91)
at ClientGUI.IdAndPasswordFrame.<init>(IdAndPasswordFrame.java:22)
at ClientGUI.IdAndPasswordFrame$4.run(IdAndPasswordFrame.java:200)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
BUILD SUCCESSFUL (total time: 1 second)
line 138:
public ImageIcon (URL location) {
this(location, location.toExternalForm());
}
line91:
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/yahoo_1.gif"))); // NOI18N
I use this poor checking (Peter Lang recommended)which is:System.out.println(getClass().getResource("/Images/yahoo_1.gif")); and it returns null,why? please help me.
This means, that getClass().getResource("/Images/yahoo_1.gif") returns null.
JavaDoc states that this happens if
the resource could not be found or the invoker doesn't have adequate privileges to get the resource.
Check if getResource really returns null:
System.out.println(getClass().getResource("/Images/yahoo_1.gif"));
Make sure that your path is correct and that it is in your classpath.
EDIT:
I just tried it with NetBeans. I created the following structure
Source Packages
Images
yahoo_1.gif
and your code worked fine. Is this your structure?
Try to right-click on your application and select Clean and Build.
In order to fix this, the images need to be copied in the bin directory - not in src directory.
Otherwise you will get null all the time on getClass().getResource("image.png").
The path is not null and you can set it as the above - only if you copy the images that you need inside the binary directory, where .class files for your project are located.
This fixed the problem. Let me know if I helped in this.
Ioana
I had the same problem. What worked for me was:
Look into the jar file or in the bin folder(the one with .class files) and see the path of image.
List item
It looks like getClass().getResource("/Images/yahoo_1.gif") returns null i.e. the .gif cannot be found on your classpath. (Images versus images maybe?)
The URL being passed in is null from this line:
getClass().getResource("/Images/yahoo_1.gif")
From the JDK documentation:
[getResource(..) returns] A URL object for reading the resource,
or null if the resource could not be
found or the invoker doesn't have
adequate privileges to get the
resource
Maybe you meant ("Images/yahoo_1.gif") - i.e. relative path not absolute?
private class HandlerClass implements ActionListener{
public void actionperformed(ActionEvent event){
JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
}
}
After reviewing some things when trying to add an image I was presented with the same problem that usually occurs in project with maven.
I found a solution that uses the full path to be able to access the image. Also, create a function that returns an icon with the image and automatically scaled according to the dimensions that are sent to it.
Path -> directory where the image is located, width -> width of the icon, heigth-> height of the icon I hope it serves you, this is my first contribution in the community
public Icon getIcon(String ruta, int width, int heigth) {
Image image = (new ImageIcon(ruta)).getImage().getScaledInstance(width, heigth, 0);
Icon mIcono = new javax.swing.ImageIcon(image);
return mIcono;
}
Related
I've got following maven project structure as also seen in here (ProjectStructure) :
-maws20.algorithm
|-src/main/resources
|-images
|-menuBanner
|-linearSearchMenuBannerUnsorted.png
|-src/main/java
|-linearSearch.menu
|-LinearSearchMenuBanner.java
I am trying to load that .png image inside of the LinearSearchMenuBanner.java-File with the following Line:
#Override
public Image loadBackgroundImage() {
return new Image(LinearSearchMenuBanner.class.
getResource("/images/menuBanner/linearSearchMenuBannerUnsorted.png").toString());
}
Is this not the correct relative path? Because I get the following error:
...
Caused by: java.lang.NullPointerException: Cannot invoke "java.net.URL.toString()" because the return value of "java.lang.Class.getResource(String)" is null
at linearSearch.menu.LinearSearchMenuBanner.loadBackgroundImage(LinearSearchMenuBanner.java:20)
...
(Line 20 is the line shown above)
I thought I understood the relative paths in Java. ^^'
Thank you for any help.
Remove the first back slash /, which actually means absolute path not the relative path.
Try this:
#Override
public Image loadBackgroundImage() {
File resource = new ClassPathResource("images/menuBanner/linearSearchMenuBannerUnsorted.png").getFile();
return new Image(new String(Files.readAllBytes(resource.toPath()));
}
To know more, you can visit this link: spring-classpath-file-access
Thanks for all your help. I don't know what went wrong, but when i create a completly new Workspace after that create all files new and copy the source code to the new files. Then it works fine.
I dont know why...
But thank you very much :)
I guess this is related to your packaging. The image needs to be on the servers file system, the JAR resources will not work!
ClassPathResource
Supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR. Always supports resolution as URL.
You are in package search.menu and you need to access the file resource in images/menuBanner So you need to load a resource:
new ClassPathResource(“../../images/menuBanner/linearSearchMenuBannerUnsorted.png
“, LinearSearchMenuBanner
.class).getFile();
Hava a look into other options here:
https://www.baeldung.com/spring-classpath-file-access
I have checked multiple posts about why my i'm getting a error saying that there is a NullPointerException at this line
JLabel label = new JLabel(new ImageIcon(getClass().getResource("image.png")));
Every posts saying that its because it can't find the image. I have tried changing the code to absolute which does not change anything. I have moved the image into the src folder and the package for the program but nothing seems to work. Right now the image is in the src folder if that helps with someone solving why it does not work
Here is the Error.
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
Then it points to that line of code.
The getResource() call is returning null (which you're not checking) and you're then getting the NullPointerException.
When you use getResource() it looks for the file in the same directory as the class -- including the package. So if this is in a com.example package, it'll need to be in com/example/image.png.
If the file is at the root of the classes directory or jar file, then you need to prefix it with /:
JLabel label = new JLabel(new ImageIcon(getClass().getResource("/image.png")));
My project-structure:
-Project
--res
---test.jpg
---bla.xml
--src
---Main.scala
Now I want to load bla.xml in my Main.scala
object Main
{
val test = getClass.getResource("res/bla.xml")
}
Throws an IOException right into my face. Now how can I add the res-folder to the projects-searchpath?
I've already marked it as "resource folder".
If I place bla.xml at the root and load it with "bla.xml" everything is just fine, so I'm wondering how to do this in Intellij.
edit: Sascha Kolberg had it right:
Just use val test = getClass.getResource("/bla.xml") if you've added res as an resourcefolder.
My comment as answer:
afaik, all contents or resource folders are placed in the class path root. So just try
val test = getClass.getResource("/bla.xml")
Try val test = getClass.getResource("[full_path_to_bla.xml]"). If this works, slightly adjust, then you will figure out the correct relative path.
Please update us the correct one when you found it.
I wanted to test having a program with a simple png image on it. I wrote a short program that does this, but I can't seem to get the path right. I have checked, checked again, rechecked, and quadruple checked my path name as to not get it right, but this image will not display, no matter what I do. I used a short class wrote by Oracle in the ImageIcon documentation (the creaetImageIcon()) to accomplish this, but it doesn't seem to help. I'll post the entire program below, as it is very short.
package practiceImages;
import java.awt.BorderLayout;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ImageIconGUITest {
public static void main(String[] args) {
ImageIconGUITest gui = new ImageIconGUITest();
gui.display();
}
private ImageIcon createImageIcon(String path, String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
private void display() {
JFrame frame = new JFrame();
JLabel label = new JLabel(createImageIcon(
"Users/Evan/javaItems/Sprites_and_Other_Art/green.png", "the color green"));
frame.add(BorderLayout.CENTER, label);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
The getResource(String) method will only find resources that are on the run-time class-path of the application. Since this image seems like an application resource (i.e. supplied by you as part of the application) it should be put on the run-time class-path.
E.G. Most IDEs have a place you can put resources within the project structure, that will automatically be included at run-time. Move (or copy) the image to that path.
Then it becomes a matter of providing the correct String. Let us imagine your project is set up something like this:
bin
src
com
our
Application.java
resources
green.png
So Application.java is in package com.our;, while the image is in the path resources/green.png.
If accessing the image from the Application, the correct path would be (drum roll please..)
"/resources/green.png"
Notes
The leading / is important. It tells the JRE we want to look for the image from the 'root of the class-path', as opposed to using a path relative to the package of the class itself.
Correct case is also vital. A string of "/resources/green.png" will not locate an image named "/resources/Green.png" or "/resources/green.PNG".
Eclipse paths
Right click on the src directory, select Properties at the bottom of the menu.
Navigate (using the normal way you'd use without Eclipse) to the directory of the Location.
Then go to the parent directory.
You should see a bin directory that contains classes and (hopefully) the image.
Firstly, you've supplied a relative path, so the system is looking for the image relative to the location you executed the program.
Secondly, the path should have a drive spec or at least a leading /. Depending on your setup, something like 'C:/Users/Evan/javaItems/Sprites_and_Other_Art/green.png' should work (you may need to change the drive spec to meet your system)
Thirdly, make sure that the file exists in the specified location, System.out.println(new File("C:/Users/Evan/javaItems/Sprites_and_Other_Art/green.png").exists()) should return true, other wise the file is in the wrong location.
A relative path basically means a path location relative to the programs execution. So, if you were running the program from C:/Program Files/MyAwesomeApplication for example, a relative path of Users/Evan/javaItems/Sprites_and_Other_Art/green.png would become an absolute path of C:/Program Files/MyAwesomeApplication/Users/Evan/javaItems/Sprites_and_Other_Art/green.png. This describes the path from the root location to the file/folder in question.
You can test this by using System.out.println(new File("C:/Users/Evan/javaItems/Sprites_and_Other_Art/green.png").getAbsolutePath()) which will give you the full path.
Using this fixed it for me:
JButton btnBanana = new JButton("New button");
btnBanana.setIcon(new ImageIcon("D:\\Android\\Company\\images\\bananas-icon.png"));
use double slash instead of one , i had this problem and i fixed it . ill show you an example :
public Driver (){
ImageIcon us = new ImageIcon("C:\saeed.gif"); // OS cant find it
ImageIcon uk = new ImageIcon("C:\\saeed0.gif"); // OS can
JButton button = new JButton ("Click here " , us ) ;
button.setRolloverIcon(uk);
add(button);
}
To get the path of a image to a text filed, this code will help you
txtPath.setText(lblImage.getIcon().toString());
//txtPath is the text filed use todiplay the path
//lblImage is the label which shows the image
You need to do C:\\Test\\test.png and not C:/Test/test.png
I am relatively new to Java, so bear with me.
I am completing a tutorial on LWUIT, and just want to load a simple theme, created using the editor. Here is the code in question:
try
{
Container container = c.getContainer();
container.setVisible(true);
Display.init(container);
Display.getInstance().setPureTouch(true);
//Resources r = Resources.open(getClass().getResourceAsStream("/res/Theme.res"));
Resources r = Resources.open("/res/Theme.res");
UIManager.getInstance().setThemeProps(r.getTheme("Simple"));
}
When I use the first (commented out) statement, I get
*** Signal: alarm { "name":"XletException", "domain":"ams", "appId":"com.thomasdge.xlet.hellojamaica.HelloJamaica", "msg":"XletAction['initXlet'] resulted in exception com.aicas.xlet.manager.AMSError: running xlet code caused java exception: initXlet() resulted in exception: java.lang.NullPointerException: <null>.read()I", "data":{ } }
When I use the other, I get
java.io.IOException: /res/Theme.res not found
I have my Theme.res file in /res/Theme. I have also tried it directly in the root, as well as /src. Same results for each.
Any ideas?
If you put the res file in that folder, you will need to go down one level. I recommend you to put the res in the src folder. So, /src/Theme.res. In the code you will only need to write Resources r = Resources.open("/Theme.res");
If resource file placed in res folder, you need to add res folder in project properties. Also you mentioned, the problem even in /src folder, I feel you didn't change the path. Just use Resources.open("/Theme.res") when you use /src folder. Also check the theme name. This should work.