Set icon in JFrame

社会主义新天地 提交于 2019-12-25 13:43:07

问题


I want to change the icon of the project instead of java icon. When the program icon is being displayed in status bar, it should be displaying the customized icon instead of default java icon.

I am using the following code. Please suggest me what's wrong in this code.

class newframe extends JFrame 
{

    Container cp;
    newframe()
    {
        cp=this.getContentPane();
        cp.setLayout(null);
    }

    public static void main(String args[])
    {
        newframe frm= new newframe(); 

        frm.setbounds(0,0,1000,800);
        frm.setVisible(true);
        ImageIcon im1= new ImageIcon("path upto image");
        frm.setIconImage(im1.getImage());
    }
}

回答1:


..new ImageIcon("path upto image"); 

A frame icon will typically be an embedded-resource, so must be accessed by URL rather than (a String representing a path to) a File.




回答2:


There are a couple of things that would be keeping it from compiling. First:

frm.setbounds(0,0,1000,800);

Your "setbounds" should have a capital B. Typically, functions will be cased such that the first letter of the first word is lowercased, and subsequent words are upper-cased. See this link for the doc on setBounds: setBounds

There's a second issue in your ImageIcon path. Its hard to say if that came right from your code or if you removed the path for the sake of the example, but Andrew Thompson has addressed that adequately.




回答3:


I think the problem is the decleration of the imageicon. What you should do is instead of getting the direct path, do something like this:

ImageIcon im1= new ImageIcon("Toolkit.getDefaultToolkit(). getImage(getClass().getResource("path upto image"))");
I do this with all of my applications, and it works every time.



来源:https://stackoverflow.com/questions/12892166/set-icon-in-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!