Question

I am trying to add an image to my applet. I have googled this but I have not found a decent example that I understand. Does anyone know where I can find a good example of adding an image to and applet?

I got this online but when I run the applet it doesn't display my image.

   public class Lab5 extends JApplet {
        //Lab5(){}


        Image img;

        public void init() {
                img = getImage(getDocumentBase(), "img\flag0.gif");                 
        }


        public void paintComponent(Graphics g) {
            g.drawImage(img, 50, 50, this);
        }
}

Below is my HTML file

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
    <applet code="Lab5.class" width= 250 height = 50></applet>
    </body>
</html>
Was it helpful?

Solution

Here's a simple example that shows an image from a URL from the internet. You'd probably use a resource in the internet url's place, such as an image held in a directory of the application's jar:

Class SimpleAppletImage.java

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class SimpleAppletImage extends JApplet {
   @Override
   public void init() {
      try {
         SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
               try {
                  // you might want to use a file in place of a URL here
                  URL url = new URL("http://duke.kenai.com/gun/Gun.jpg");
                  BufferedImage img = ImageIO.read(url);
                  MyPanel myPanel = new MyPanel(img );
                  getContentPane().add(myPanel);
               } catch (MalformedURLException e) {
                  e.printStackTrace();
               } catch (IOException e) {
                  e.printStackTrace();
               }
            }
         });
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

class MyPanel.java

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

@SuppressWarnings("serial")
class MyPanel extends JPanel {
   private BufferedImage img;

   public MyPanel(BufferedImage img) {
      this.img = img;
      setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (img != null) {
         g.drawImage(img, 0, 0, this); // corrected
      }
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top