0

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)

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.

Cj1m
  • 805
  • 3
  • 11
  • 26
  • What are the errors that occur? – FThompson Jul 17 '13 at 10:47
  • Can you paste here your error? – kukis Jul 17 '13 at 10:51
  • Well when I try window.setIconImage(ImageIO.read("src/slime.png")); I get the error The method read(File) in the type ImageIO is not applicable for the arguments (String) – Cj1m Jul 17 '13 at 10:51
  • also if you haven't already, read the note at the bottom. :) – Cj1m Jul 17 '13 at 10:52
  • 2
    Well, the setIconImage(ImageIO.read("...")); you refer to is not in your posting; in fact, you call setIconImage without any parameters at all. There are many (, many) examples of how to do this on the web, I don't know that providing you more random examples is going to help. If you want to know what you are doing wrong, reduce your code to the minimum necessary to show the problem and tell us what happens when you run it, and what you have tried IN THAT CODE, not just a random statement which we then have to guess about. – arcy Jul 17 '13 at 10:59
  • Ok I'll edit it rcook – Cj1m Jul 17 '13 at 11:11
  • @user1952565 : I hope this [answer](http://stackoverflow.com/a/9866659/1057230), will be able to guide you in a good way :-) – nIcE cOw Jul 17 '13 at 11:37

4 Answers4

1

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.

0

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.

sajjadG
  • 2,546
  • 2
  • 30
  • 35
0

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));
}
ChadNC
  • 2,528
  • 4
  • 25
  • 39
0

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();
            }
        });
    }
}
JavaTechnical
  • 8,846
  • 8
  • 61
  • 97