We help IT Professionals succeed at work.

images not displaying when running java applet in eclipse

robertben
robertben used Ask the Experts™
on
Hello Experts,
I am having a problem getting an image to display in an applet provided to me from a java textbook. I opened the applet in Eclipse and made sure the image file was in the same directory as the class file. When I run the applet in the Eclipse Applet Viewer the other components show up but no image.
Help please.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JBear extends JApplet implements ActionListener
{
   private ImageIcon image = new ImageIcon("bear.gif");
   private JButton closerButton = new JButton("Oh my!");
   private int width, height;
   Container con = getContentPane();
   public void init()
   {
      con.setLayout(new FlowLayout());
      closerButton.addActionListener(this);
      con.add(closerButton);
      width = image.getIconWidth();
      height = image.getIconHeight();
   }
   public void actionPerformed(ActionEvent event)
   {
      width = width * 2;
      height = height * 2;
      repaint();
   }
   public void paint(Graphics g)
   {
      super.paint(g);
      g.drawImage(image.getImage(), 0, 0, width, height, this);
   }
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016
Commented:
Try

 private ImageIcon image ;
...
// (in init)
image = new ImageIcon(getClass().getResource("bear.gif"));

Open in new window

Author

Commented:
That worked. This is the 2nd time this book (Java Programming, sixth edition, Farrell) was wrong.
Thank you
Top Expert 2016

Commented:
:)