简体   繁体   中英

JFrame Icon Image Not Working

I have been searching around the internet trying to find out how to add an Icon Image to my JFrame, but I keep getting errors. I understand this has been asked on stack overflow but the solutions are not working for me. Here is my code:

    ImageIcon imageIcon = new ImageIcon("src/slime.png");
    ImageIcon image = new ImageIcon("src/slime.gif");

    JLabel label = new JLabel(image, JLabel.CENTER);
    label.setAlignmentX(0);
    label.setAlignmentY(0);
    label.setIcon(image);

    JFrame window = new JFrame("Slime");
    window.setVisible(true);
    window.setSize(250, 200);
    window.setResizable(false);
    window.setIconImage(newImageIcon(getClass().getResource("src/slime.png")).getImage());
    window.add(label);

here is the error I get: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at javax.swing.ImageIcon.<init>(ImageIcon.java:205) at MainJFrame.<init>(MainJFrame.java:39) at MainJFrame$1.run(MainJFrame.java:18) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727) at java.awt.EventQueue.access$200(EventQueue.java:103) at java.awt.EventQueue$3.run(EventQueue.java:688) at java.awt.EventQueue$3.run(EventQueue.java:686) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:697) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) at java.awt.EventDispatchThread.run(EventDispatchThread.java:91) Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at javax.swing.ImageIcon.<init>(ImageIcon.java:205) at MainJFrame.<init>(MainJFrame.java:39) at MainJFrame$1.run(MainJFrame.java:18) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727) at java.awt.EventQueue.access$200(EventQueue.java:103) at java.awt.EventQueue$3.run(EventQueue.java:688) at java.awt.EventQueue$3.run(EventQueue.java:686) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:697) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

Help would be very much appreciated. Note: I have tried window.setIconImage(imageIcon.getImage()); but that doesn't work and makes my other image that I have printed on the screen disapear.

Use getClass to get the image:

window.setIconImage(new ImageIcon(
                getClass().getResource("src/slime.png")).getImage());

But if you want to add image to your label an then add the label to your frame use this instead:

Image img = (new ImageIcon(getClass().getResource("src/slime.png"))).getImage();
JLabel lblIcon = new JLabel(new ImageIcon(newimg));
window.add(lblIcon);

and if you want to resize the image size to be the size of window do this (put the code before adding it to window):

Image newimg = img.getScaledInstance(window.getWidth() , window.getHeight(), java.awt.Image.SCALE_SMOOTH);// resizing image to the window size

EDIT:

of course you cannot use getClass() in public static void main() method you should put your code somewhere non-static like a class constructor for example.

public class MainForm extends javax.swing.JFrame {

/**
 * Creates new form MainForm
 */
public MainForm() {
    //put your code here...
    window.setIconImage(new ImageIcon(
            getClass().getResource("src/slime.png")).getImage());
}
public static void main(String args[]) {
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
                new MainForm().setVisible(true);
            }
        });
    }

It is always good to try-catch block to check if you getting the image correctly. albeit in this situation when you are getting the code from inside your packages is not that necessary but if you are going to get any resource from outside of your project make sure of your opening process.

Try this. Pretty the same as sajjad's answer just has a check to make sure the image url isn't null before using it.

java.net.URL imageUrl = YourClass.class.getResource("/IconImage.png");
if(imageUrl != null){
   setIconImage(new ImageIcon(imageUrl));
}

Try this, it has to work

frame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/src/slime.gif")));

You wrote,

newImageIcon()

This might be a method because it compiled for you. I think you might have to write it as new ImageIcon() This might be the problem. The javax.swing.ImageIcon is not being created.

Simply, why dont you use

setIconImage(imageIcon.getImage());

Here is the full code,

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class IconImageDemo1 extends JFrame
{

    public IconImageDemo1()
    {
        createAndShowGUI();
    }

    private void createAndShowGUI()
    {
        setTitle("IconImage Demo");
        setLayout(new FlowLayout());
        setSize(400,400);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("icons/camera.png")));

        setLocationRelativeTo(null);
    }

    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
                new IconImageDemo1();
            }
        });
    }
}

First, just for safety reasons, don't try and make your JFrame in your main method. That is why you are getting some of the static errors from some of the solutions. Static is just a big problem in my opinion because as soon as you make one static, you make them all static. Try and initelize the JFrame in the constructor instead of the main method. Just make a new MainJFrame object in the main method:

public static void main(String[] args){
    MainJFrame frame = new MainJFrame();
}

And put all of your code in the constructor, if you don't know what this is, which you should know then this is what one looks like:

public MainJFrame(){
    //This is a constructor
    //All frame init code in here
}

Then put the same code in there but put a space between the new and ImageIcon in your setIconImage() argument. So the whole constructor should look like this:

public MainJFrame(){
    ImageIcon imageIcon = new ImageIcon("src/slime.png");
    ImageIcon image = new ImageIcon("src/slime.gif");

    JLabel label = new JLabel(image, JLabel.CENTER);
    label.setAlignmentX(0);
    label.setAlignmentY(0);
    label.setIcon(image);

    JFrame window = new JFrame("Slime");
    window.setVisible(true);
    window.setSize(250, 200);
    window.setResizable(false);
    window.setIconImage(new ImageIcon(getClass().getResource("src/slime.png")).getImage());
    window.add(label); }

If that still doesn't work then try to use ImageIO to load the image. This won't work on applets though since it will give you a security error.

window.setIconImage(ImageIO.read(new File("folder/to/file.png")));

You also need to surround this line in a throw/catch block and if you are working in eclipse then make sure the file is in a folder outside of your main package. Other than that you should be good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM