0

My program will run, and a button will appear, but the image which is in the res folder that is in a referenced library will not appear (egg.png). There are no errors, but I'm confused as to why it won't run properly.

package gui;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

public class IconButton {
public static void main(String args[]) {
    JFrame frame = new JFrame("DefaultButton");

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ImageIcon image = new ImageIcon("C:\\Users\\Jack Young\\Desktop\\Egg game Sprites");
    JButton button = new JButton();
    button.setIcon(image);
    frame.add(button);
    frame.setSize(300, 200);
    frame.setResizable(false);
    frame.setVisible(true);
  }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 3
    You mention `"egg.png"` but use `"C:\\Users\\Jack Young\\Desktop\\Egg game Sprites"` ... so I am not suprised, provided the correct file name and this will work. – AxelH Jul 05 '18 at 07:51
  • You also mention "res" folder, but that path doesn't mention any "res" folders – MadProgrammer Jul 05 '18 at 07:53
  • in the code i posted i had the path from my computer posted, but it didn't work so i tried to change it just the egg.png that i had in my res folder. – Jack Young Jul 05 '18 at 08:13
  • But just `new ImageIcon("egg.png");` won't cut it either since it will look at the root of the project. See [How do I load a file from resource folder?](https://stackoverflow.com/questions/15749192/how-do-i-load-a-file-from-resource-folder) – AxelH Jul 05 '18 at 08:15
  • i was able to make it work by using "C:\\Users\\Jack Young\\Desktop\\Eclipse\\GUI\\res\\egg.png" is there a way to simplify it to something to the effect of "egg.png" – Jack Young Jul 05 '18 at 08:17
  • @Jack Young Yes, if you add the image to the root of your project path you can just call it by its filename. – T A Jul 05 '18 at 08:24
  • Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An [tag:embedded-resource] must be accessed by URL rather than file. See the [info. page for embedded resource](http://stackoverflow.com/tags/embedded-resource/info) for how to form the URL. – Andrew Thompson Jul 05 '18 at 10:43

1 Answers1

0

try this:- for eg:- if image is in icons folder in resource:-

private final ImageIcon imageIcon = new ImageIcon(getClass().getClassLoader().getResource("icons/image.png"));

Greeshma
  • 95
  • 2
  • 10