开发者

Having difficulty add a custom icon to a JFrame

I have been trying to change the icon in the frame. I have virtually tried everyt开发者_运维百科hing:

  • The icon is 16x16 which is the right size ....doesn't work

  • I've trying PNG,GIF and JPG formats none of them work.

  • Tried different way of setting the icon....doesn't work.

  • I've tried relative (local paths) e.g. "icon.gif" and absolute paths e.g. "c:\work\java\icon.gif" ...doesn't work

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());
        }
    }


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);


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.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜