#java swing icon

13 messages · Page 1 of 1 (latest)

hybrid coral
#

I am trying to set an icon on a JFrame but when I run this code it does not change the icon at all.

        JFrame frame = new JFrame("test gui");
        frame.setBounds(0, 0, 500, 270);
        frame.setIconImage(ImageIO.read(new File(PS_PROGRAM_DIR + "\\resources\\frame_icon.png")));
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLayout(null);
        frame.setVisible(true);

I am not accessing a file within a class path btw.

trail fiberBOT
#

This post has been reserved for your question.

Hey @hybrid coral! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

unborn wraith
#

Are you sure the path to that is not null?

#

On some JDKs, if the path is null, it replaces it with default Duke icon

#

Here, let's try something:

#
  public static BufferedImage readImageResource(String name, Class<?> clazz) {
    URL imageFileUrl = clazz.getClassLoader().getResource(name);
    if (imageFileUrl != null) {
      try {
        return ImageIO.read(imageFileUrl);
      } catch (IOException ioe) {
        System.err.println("Failed to load image resource");
      }
    }
    return null;
  }

use this method in that JFrame area

#

Since I use a Maven project, my stuff is usually in src/main/resources, so I did it like this:

this.setIconImage(FileUtils.readImageResource("icon/favicon.png", LauncherFrame.class));
#

You could always modify the method to take a file outside the class, but ensure it's still a URL path, or a converted Path object.

#

In your case, something could be done with Path imgPath = Paths.get(PS_PROGRAM_DIR.toString(), "resources", "frame_icon.png");

#

I still don't understand why you have an image file outside your project

#

If you compile the jar, the path to the image will be null for everyone else because you hard-coded a value that doesn't actually look it up within the .jar itself, and the PNG it looks for in your path isn't present in other peoples' system

#

it would only be present if it was within the same jar, or if you decided to be masochistic and make your project download an image and save it somewhere before calling a new instance in your JFrame, just to use it as an icon...