Set icon in JFrame

2019-09-19 00: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.