0

I am making a java game and I am trying to set the JFrames icon to a file named f3.png and it is not working. hear is my code:

package t;

import java.awt.Image;
import java.awt.Toolkit;
import java.io.IOException;

import javax.swing.JFrame;

public class t {

    public static void main(String[] args) throws IOException {
        Image i = Toolkit.getDefaultToolkit().getImage("f3.png");
        JFrame frame = new JFrame();
        frame.setTitle("test");
        frame.setSize(600,600);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setIconImage(i);
    }
}

I ran it and it still had the default icon

  • At a guess, `f3.png` is not within the working directory/context, so your program can't load the icon. Better to use [`ImageIO.read`](https://docs.oracle.com/javase/tutorial/2d/images/loadimage.html) as this will actually through an exception if the image can't can be read – MadProgrammer Oct 30 '22 at 22:57
  • Try this here: https://stackoverflow.com/a/1614803/5841551 – kladderradatsch Oct 30 '22 at 22:58
  • f3.png and the main file are in the same directory –  Oct 30 '22 at 22:59
  • Which means that you're using the wrong path to the image. Get it as a resource, and then use ImageIO. – Hovercraft Full Of Eels Oct 30 '22 at 23:00
  • I have tried that –  Oct 30 '22 at 23:00
  • So, how do you fix this problem? You could put in `System.out.println("Working Directory = " + System.getProperty("user.dir"))` and then make sure that `f3.png` is in the same location. This, however is not a suitable long term solution, as the working directory will change, a lot. You're better off using embedded resources, how you do this will depended a lot on your IDE and build system, but basically it will ensure that the resource is available at runtime via a stable path – MadProgrammer Oct 30 '22 at 23:00
  • Please look at [this answer](https://stackoverflow.com/a/20319007/) as well as [this answer](https://stackoverflow.com/a/58354541/522444) – Hovercraft Full Of Eels Oct 30 '22 at 23:08
  • i figured it out, i had f3.png in the incorrect directory –  Oct 30 '22 at 23:12
  • I made it into a .jar and now it is not working –  Oct 31 '22 at 12:24

0 Answers0