Oliver
Oliver

Reputation: 270

Having difficulty add a custom icon to a JFrame

I have been trying to change the icon in the frame. I have virtually tried everything:

Here is my code and see if you can figure it out Thanks Oli

    import javax.swing.*;
    public class androidDriver 
    {

        public static void main(String[] args) throws IOException 
        {
            JFrame f = new JFrame("Android Data Viewer");
            f.setResizable(false);
            f.setSize(300,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            f.setIconImage(new ImageIcon("androidIcon2.gif").getImage());
        }
    }

Upvotes: 0

Views: 2771

Answers (4)

user2675678
user2675678

Reputation:

Make a separate folder next to the source folder then put your image in there, and then use ImageIO to get the image like so:

f.setIconImage(ImageIO.read(new File("res/androidIcon2.gif")));

Also, if that doesn't work, try saving the image as a .png instead of a .gif.

Upvotes: 0

objects
objects

Reputation: 8677

If you put the image in the same directory as the class file then the following should work for you:

        f.setIconImage(new ImageIcon(androidDriver.class.getResource("androidIcon2.gif")).getImage());

Also would suggest setting the icon image before you make the frame visible

        f.setIconImage(new ImageIcon(androidDriver.class.getResource("androidIcon2.gif")).getImage());
        f.setVisible(true);

Upvotes: 1

user296828
user296828

Reputation:

Have you tried using Toolkit.getDefaultToolkit().getImage("androidIcon2.gif")

And two other things:

  1. Does the image exist? The code you posted will fail silently.

  2. Is it formatted properly? (though I assume Java could handle it if it wasn't)

Upvotes: 0

L. Cornelius Dol
L. Cornelius Dol

Reputation: 64026

I suspect you may have to actually wait for the image to load using a MediaTracker. It's likely that the image is still loading at the point the frame setIconImage references it, so it does nothing.

Upvotes: 0

Related Questions