1

There is a similar question (Java Applet Cannot Locate Resources), but base gives me an error, and asks me for the creation of a variable.


I have an applet that I embedded into HTML with:

<object type="application/x-java-applet" height="600" width="800">
<param name="code" value="net.me.applet.WindowMain" />
</object>

The applet launches, and attempting to change the contentpane's color works too, so that means that the link with the HTML might not have errors.

Then, I linked my assets like so:

ImageIcon left = new ImageIcon(getCodeBase(), "Arrow_Left.png");

The PNG is in the same directory as my applet. The images don't show, so I assume that the assets were not found. I also tried doing "/Arrow_Left.png", without avail.

The directory structure is this:

/ root directory
index.html
(dir)net
     | me
         | applet
               | WindowMain.class

When I developed the applet in Eclipse, I made a package with the compilation unit, and a folder called "assets" in the src folder, and I accessed those for testing purposes with ImageIcon("src/assets/Arrow_Left.png")

Community
  • 1
  • 1
Space
  • 39
  • 1
  • 5
  • You should never access resources using src, as it won't exist at runtime – MadProgrammer Feb 21 '16 at 20:36
  • *"The PNG is in the same directory as my applet"* is that the same directory as your index.html file or your class file (in the package) – MadProgrammer Feb 21 '16 at 20:38
  • @MadProgrammer I have my index.html in the root directory, and then there is a series of directories as packages, so from root directory: net > me > applet > WindowMain.class. I put the PNG in the same dir as my WindowMain.class – Space Feb 21 '16 at 20:39
  • You should also beware that applets are effectively deprecated as the plugin is no longer supported (and is effectively blocked by most browsers) – MadProgrammer Feb 21 '16 at 20:39
  • Use getClass().getResource("Arrow_Left.png") instead – MadProgrammer Feb 21 '16 at 20:42
  • @MadProgrammer I will keep that in mind, but I would like to finish what I started as it is for now. I got firefox to launch the applet, but I had to do changes with javacpl to enable `file:///`. As stated, changing contentpane color worked in the browser, so the applet is probably loaded properly. – Space Feb 21 '16 at 20:43
  • @MadProgrammer I also put `ImageIcon(getClass().getResource("Arrow_Left.png"))`, but that did not work. – Space Feb 21 '16 at 20:46
  • Start using ImageIO.read instead of ImageIcon, it will grow an IOException when it fails to read the image – MadProgrammer Feb 21 '16 at 20:47

1 Answers1

1

I put the PNG in the same dir as my WindowMain.class

Then the string needs to be the relative path from the code base. Something like:

ImageIcon left = new ImageIcon(getCodeBase(), "net/me/applet/Arrow_Left.png");

But definitely heed the advice to use ImageIO.read(..) which provides better feed-back.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433