How to change java icon in a JFrame

后端 未结 5 1048
渐次进展
渐次进展 2020-12-31 11:54

Ok so I\'ve been researching this one quiet a bit. I am fairly new to java but thought that this one would be easy. Ive tried just about every way that has been answered on

相关标签:
5条回答
  • 2020-12-31 12:27
    1. Paste your image icon (fav.png) in the same package first,
    2. Write following code in constructor of JFrame:

    setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("fav.png")));

    Note:- fav.png is the name of icon

    0 讨论(0)
  • 2020-12-31 12:30

    I have an answer for you. First, make sure that the images are in a folder, not a package. Next, insert this line of code:

    Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("path/to/image.png"));
    ImageIcon icon = new ImageIcon( );
    setIconImage(icon.getImage());
    

    This code gets the image from the class path, and returns it as a image icon, and then it sets it. This should add the image icon to the application. If it doesn't, then tell me.

    EDIT: After you told me that that didn't work then I decided to take a second crack at it... First, put your images into a completely separate folder. I usually call this /res. Next, put your image in there. Now, for loading I took a completely different route. I decided to use ImageIO instead of default loading. To load the image, you use this code:

    try {
        frame.setIconImage(ImageIO.read(new File("res/icon.png")));
    }
    catch (IOException exc) {
        exc.printStackTrace();
    }
    

    ImageIO works a lot better for loading images. If this still doesn't work then please tell me.

    If you want to export this as a JAR then put a folder the same name as you used in the program in the same directory as the JAR.

    0 讨论(0)
  • 2020-12-31 12:36
    this.setIconImage(new ImageIcon(getClass().getResource("/iconsfolder/iconsname.jpg")).getImage()); 
              // sets the Global icon for the system
    

    try this code put after this code:

    public void displayGUI()
    {
    
    0 讨论(0)
  • 2020-12-31 12:49

    For example in a NetBeans project, create a resources folder in the src folder.

    Put your images (jpg, ...) in there.

    Whether you use ImageIO or Toolkit (including getResource), you must include a leading / in your path to the image file:

    Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/agfa_icon.jpg"));
    setIconImage(image);
    

    If this code is inside your JFrame class, the image is added to the frame as an icon in your title bar.

    0 讨论(0)
  • 2020-12-31 12:49

    This works pretty fine for me. Just add this after you've created your JFrame.

    try {
       Image image = new ImageIcon("/icons/image.jpg").getImage();
       frame.setIconImage(image);
    }catch(Exception e){
       System.out.println("Application icon not found");
    }
    
    0 讨论(0)
提交回复
热议问题