Exception in thread "main" java.lang.NullPointerException when make a JLabel [duplicate] - java

This question already has answers here:
Java - class.getResource returns null
(21 answers)
Closed 5 years ago.
I'am a beginner and I've met some problems when I attempted to use a JPG to make a label.
and it shows that
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.(Unknown Source)
at pane.MyImageIcon.(MyImageIcon.java:11)
at pane.MyImageIcon.main(MyImageIcon.java:21)
package pane;
import java.net.*;
import java.awt.*;
import javax.swing.*;
public class MyImageIcon extends JFrame {
public MyImageIcon() {
JFrame jf=new JFrame();
Container container = jf.getContentPane();
JLabel jl = new JLabel("it is a frame", JLabel.CENTER);
URL url = MyImageIcon.class.getResource("ofii.jpg");
Icon icon = new ImageIcon(url);
jl.setIcon(icon);
jl.setHorizontalAlignment(SwingConstants.CENTER);
jl.setOpaque(true);
container.add(jl);
jf.setSize(800,800);
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String args[]) {
new MyImageIcon();
}
}

Print out variable "url". You will find it being null. Check if the image actually exists in the jar, on the given path. These posts might help:
Getting images from a .jar file
Jar get image as resource
https://gamedev.stackexchange.com/questions/30416/dynamically-load-images-inside-jar

Unknown source usually means it can't find the image, Make sure the image exists and is placed in the same location as your Java class file, if not, you can use classpath relative paths in getResource() putting / at the start

Related

Using an icon image for a GUI

I have created the following code for a school project, a "password protector", just for fun, really. However, the problem I have is that the icon image does not appear, but instead the default java "coffee cup".
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class UserInterfaceGUI extends JFrame
{
private static final long serialVersionUID = 1;
private JLabel userNameInfo; // ... more unimportant vars.
public UserInterfaceGUI()
{
this.setLayout(new FlowLayout());
userNameInfo = new JLabel("Enter Username:"); // ... more unimportant var. declartions
this.add(userNameInfo); // ... more unimportant ".add"s
event e = new event();
submit.addActionListener(e);
}
public static void main(String[] args)
{
//This icon has a problem \/
ImageIcon img = new ImageIcon("[File Location hidden for privacy]/icon.ico");
UserInterfaceGUI gui = new UserInterfaceGUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(400, 140);
gui.setIconImage(img.getImage());
gui.setTitle("Password Protector");
gui.setVisible(true);
}
}
Can someone tell me why this just shows the java coffee cup at the bottom of the screen and on the bar at the top of the window?
There are two likely problems here:
Java is unlikely to support .ico files. The only types that can be relied on are GIF, PNG & JPEG. For all types supported on any specific JRE, use ImageIO.getReaderFileSuffixes() (but seriously, for app. icons stick to the 3 types with guaranteed support).
The code is trying to load an application resource as a file, when it will likely be (or become) an embedded-resource that should be accessed by URL. See the embedded resource info. page for tips on how to form the URL.

Exception in thread "main" java.lang.NullPointerException at javax.swing.ImageIcon.<init>(Unknown Source)

I am working on a little program for school however I am getting this error whenever I run it:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at Creatieve.Opracht.Main.main(Main.java:14)
The langugae I am coding in is Java, and before someone comments on it, no this is not a computer sience project so I can't ask a teacher.
This is de code I have written:
package Creatieve.Opracht;
import java.awt.*;
import javax.swing.*;
public class Main {
static JFrame frame;
static Puzzel puzzel;
public static void main(String[] args){
frame = new JFrame("CKV Creatieve Oprdacht 2.0");
frame.setSize(900, 900); //Lengte en breedte van de foto
puzzel = new Puzzel(new ImageIcon(Main.class.getResource("/image.png")).getImage());
frame.add(puzzel);
frame.setVisible(true);
}
}
And also this:
package Creatieve.Opracht;
import java.awt.*;
import javax.swing.*;
public class Puzzel extends JPanel{
Onderdeel[] onderdelen;
Image img;
public Puzzel(Image img){
this.img = img;
onderdelen = new Onderdeel[9];
int onderdeelGrootte = img.getWidth(null)/3;
for(int i = 0; i != onderdelen.length; i++){
onderdelen[i] = new Onderdeel(this, i, onderdeelGrootte);
}
}
public void paint(Graphics g){
super.paint(g);
for (int i = 0; i != onderdelen.length; i++){
onderdelen[i].paint(g);
}
}
}
It would be awesome if one of you could tell me how I can fix the problem.
Thank you in advance!
Exception came on this line in your code when you are accessing image,
new ImageIcon(Main.class.getResource("/image.png")).getImage().
you have to check that /image.png image available at this location or not, if possible use qualified path name of your folder to resolve issue.
The resource file /image.png does not exists. So Main.class.getResource("/image.png") is returning null. Hence while creating the ImageIcon object with null is resulting in NullPointerException
to solve this issue.....
just copy your images to /your_Drive_in_which_workspace_folder_is_present/workspace/projectname/bin/projectname/
now this statement should be like this:
Icon IconObject=new ImageIcon(getClass().getResource("Image_name.png"));

How to set Icon to JFrame

I tried this way, but it didnt changed?
ImageIcon icon = new ImageIcon("C:\\Documents and Settings\\Desktop\\favicon(1).ico");
frame.setIconImage(icon.getImage());
Better use a .png file; .ico is Windows specific. And better to not use a file, but a class resource (can be packed in the jar of the application).
URL iconURL = getClass().getResource("/some/package/favicon.png");
// iconURL is null when not found
ImageIcon icon = new ImageIcon(iconURL);
frame.setIconImage(icon.getImage());
Though you might even think of using setIconImages for the icon in several sizes.
Try putting your images in a separate folder outside of your src folder. Then, use ImageIO to load your images. It should look like this:
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
Finally I found the main issue in setting the jframe icon. Here is my code. It is similar to other codes but here are few things to mind the game.
this.setIconImage(new ImageIcon(getClass().getResource("Icon.png")).getImage());
1) Put this code in jframe WindowOpened event
2) Put Image in main folder where all of your form and java files are created e.g.
src\ myproject\ myFrame.form
src\ myproject\ myFrame.java
src\ myproject\ OtherFrame.form
src\ myproject\ OtherFrame.java
src\ myproject\ Icon.png
3) And most important that name of file is case sensitive that is icon.png won't work but Icon.png.
this way your icon will be there even after finally building your project.
This works for me.
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(".\\res\\icon.png"));
For the export jar file, you need to configure the build path to include the res folder and use the following codes.
URL url = Main.class.getResource("/icon.png");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(url));
Yon can try following way,
myFrame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
Here is the code I use to set the Icon of a JFrame
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
try{
setIconImage(ImageIO.read(new File("res/images/icons/appIcon_Black.png")));
}
catch (IOException e){
e.printStackTrace();
}
Just copy these few lines of code in your code and replace "imgURL" with Image(you want to set as jframe icon) location.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create the frame.
JFrame frame = new JFrame("A window");
//Set the frame icon to an image loaded from a file.
frame.setIconImage(new ImageIcon(imgURL).getImage());
I'm using the following utility class to set the icon for JFrame and JDialog instances:
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Scanner;
public class WindowUtilities
{
public static void setIconImage(Window window)
{
window.setIconImage(Toolkit.getDefaultToolkit().getImage(WindowUtilities.class.getResource("/Icon.jpg")));
}
public static String resourceToString(String filePath) throws IOException, URISyntaxException
{
InputStream inputStream = WindowUtilities.class.getClassLoader().getResourceAsStream(filePath);
return toString(inputStream);
}
// http://stackoverflow.com/a/5445161/3764804
private static String toString(InputStream inputStream)
{
try (Scanner scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\A"))
{
return scanner.hasNext() ? scanner.next() : "";
}
}
}
So using this becomes as simple as calling
WindowUtilities.setIconImage(this);
somewhere inside your class extending a JFrame.
The Icon.jpg has to be located in myproject\src\main\resources when using Maven for instance.
I use Maven and have the structure of the project, which was created by entering the command:
mvn archetype:generate
The required file icon.png must be put in the src/main/resources folder of your maven project.
Then you can use the next lines inside your project:
ImageIcon img = new ImageIcon(getClass().getClassLoader().getResource("./icon.png"));
setIconImage(img.getImage());
My project code is as below:
private void setIcon() {
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/slip/images/cage_settings.png")));
}
frame.setIconImage(new ImageIcon(URL).getImage());
/*
frame is JFrame
setIcon method, set a new icon at your frame
new ImageIcon make a new instance of class (so you can get a new icon from the url that you give)
at last getImage returns the icon you need
it is a "fast" way to make an icon, for me it is helpful because it is one line of code
*/
public FaceDetection() {
initComponents();
//Adding Frame Icon
try {
this.setIconImage(ImageIO.read(new File("WASP.png")));
} catch (IOException ex) {
Logger.getLogger(FaceDetection.class.getName()).log(Level.SEVERE, null, ex);
}
}'
this works for me.

Not sure why image is no being displayed

So im importing an image to use as a background and for some reason its giving me:
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(Unknown Source)
at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
at sun.awt.image.ImageFetcher.run(Unknown Source)
Could someone help me?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class PixelLegendsMain extends JFrame implements ActionListener{
public void actionPerformed(ActionEvent e){
}
public static void main(String[ ] args)throws Exception{
PixelLegendsMain plMain = new PixelLegendsMain();
arenaBuild arena = new arenaBuild();
plMain.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
plMain.add(arena);
plMain.setSize(600,460);;
plMain.setVisible(true);
plMain.setResizable(false);
plMain.setLocation(200, 200);
}
}
This is the main class and this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Graphics;
import java.net.URL;
import java.io.*;
import javax.swing.Timer;
public class arenaBuild extends JPanel{
String picPath = "pictures/";
String[] fileName = {picPath+"stageBridge.png", picPath+"turret.png"};
ClassLoader cl = arenaBuild.class.getClassLoader();
URL imgURL[] = new URL[2];
Toolkit tk = Toolkit.getDefaultToolkit();
Image imgBG;
public arenaBuild()throws Exception{
for (int x=0;x<2;x++){
imgURL[x]= cl.getResource(picPath+fileName[x]);
}
imgBG = tk.createImage(imgURL[0]);
}
public void paintComponent(Graphics g){
g.drawImage(imgBG,0,0,600,460,0,0,600,460, this);
}
}
Thjis is where im calling the image in. Im new to this so i'd appreciate if someone can explain why this is happening and help me fix it :D
The most likely explanation is that your tk.createImage(imgURL[0]) call is passing a null URL.
How could this happen? Well the ClassLoader.getResource(String) method is specified as returning null if it can't find a resource ... so it would seem that the problem is that you are using the wrong path for the first resource.
The path you are using appears to be this: "pictures/pictures/stageBridge.png":
It seems unlikely that you really put your images in a directory called "pictures/pictures".
Since you are calling the method on a ClassLoader object (rather than a Class object), the notionally relative path you are using will be treated as an absolute path; i.e. you will get "/pictures/..." rather than "/PixelLegendsMain/pictures/..."
Seems that i unfortuantely did not look at my own code long enough, it seems that i was calling the picPath twice so instead of the path being
"pictures/stageBridge.png"
it was
"pictures/pictures/stageBridge.png"
Sorry for the waste of time, and thank you all for answering
Try printing the current working directory, in order to check if your images path are correct.
This is a simple way of doing that:
System.out.println(new File(".").getAbsolutePath());
Maybe the problem is that the images pictures/tageBridge.png and pictures/turret.png are not the correct path to the file.
Hope it helps!

Java Combo Boxes + Image Icons

I'm trying to build a really basic program that will alternate between two pictures depending on which item from a dropdown box is selected. This is the code I'm trying to run, but I keep getting an error saying:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:181)
at Gui.<init>(Gui.java:10)
at Apples.main(Apples.java:7)
The images are in the src file.
Does anyone know what I am doing wrong??
Thanks,
Ravin
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gui extends JFrame{
private JComboBox box;
private JLabel picture;
private static String [] filename = {"Ravinsface.png", "Wojs face.png"};
private Icon[] pics = {new ImageIcon(getClass().getResource(filename[0])), new ImageIcon(getClass().getResource(filename[1]))};
public Gui(){
super("The Title");
setLayout(new FlowLayout());
box = new JComboBox(filename);
box.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent event){
if(event.getStateChange()==ItemEvent.SELECTED);
picture.setIcon(pics[box.getSelectedIndex()]);
}
}
);
add(box);
picture = new JLabel(pics[1]);
add(picture);
}
}
Use getClass().getClassLoader().getResource(String)
/e1 I put an explanation of the different getResource(String) methods on the other answer.
It looks like one (or more) of the arguments you are passing into your ImageIcon constructor are null. This is because the resource is not being found here:
private Icon[] pics = {new ImageIcon(getClass().getResource(filename[0])), new ImageIcon(getClass().getResource(filename[1]))};
Why aren't you just using
new ImageIcon(String filename)
? I'm not 100% sure how getResource works, never having used it.
do this:
you must put your .png
beside your .class files
(in project_name/bin)
then your files path can recognize
then it will works
remember you are using class loader so if you put images beside .class files it will be correct

Categories

Resources