0

I'm trying to load an image into my Java applet and I've tried it several ways but the image still doesn't appear in the applet.

Here's my code:

public class BackgroundApplet extends Applet {
   Image backGround;
   Image fish;

   public void init() {
       // set the size of the applet to the size of the background image.
       // Resizing the applet may cause distortion of the image.
       setSize(300,300);
       // Set the image name to the background you want. Assumes the image is in 
       // the same directory as the class file is
       backGround = getImage(getCodeBase(),"underwater.jpg");
       BackGroundPanel bgp = new BackGroundPanel();
       bgp.setLayout(new FlowLayout());
       bgp.setBackGroundImage(backGround);
       // set the layout of the applet to Border Layout
       setLayout(new BorderLayout());
       // now adding the panel, adds to the center(by default in Border Layout) of the applet
       add(bgp);

       fish = getImage(getCodeBase(), "fish.jpg");
   }

   public void paint(Graphics g)
   {
       // Attempt 1
       g.drawImage(fish,20,20,this);
       // Attempt 2
       ImageIcon img = new ImageIcon("fish.jpg");
       img.paintIcon(this, g, 20,20);
       // Attempt 3
       Image image = img.getImage();
       g.drawImage(image, 50, 50, this);
   }}

As you can see, I also have loaded a background image into my applet and that shows up just fine. Could it be that the fish is loading behind the background image?

Any help is appreciated, thanks!

** Unrelated note: when I implement the Runnable interface (because I want to have animations on top of the background image), the background image suddenly does not appear when I run the applet. Any tips for this as well?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Seany242
  • 373
  • 7
  • 20
  • 1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) Why code an applet? If it is due due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 3) Why AWT rather than Swing? See this answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. – Andrew Thompson May 12 '13 at 05:42
  • @AndrewThompson thanks for the advice. I wanted an applet because I want to put it on my website, and I realized after some research that Swing is better than AWT. – Seany242 May 12 '13 at 15:24
  • *"I want to put it on my website,"* That is more easily done with a `JFrame`. Launch it from a link using [Java Web Start](http://stackoverflow.com/tags/java-web-start/info). – Andrew Thompson May 12 '13 at 15:39

0 Answers0