Question

J'essaye d'ajouter une image à mon applet.J'ai googlé ceci mais je n'ai pas trouvé d'exemple décent que je comprends.Quelqu'un sait-il où je peux trouver un bon exemple d'ajout d'une image à une applet?

Je l'ai mis en ligne, mais lorsque j'exécute l'applet, elle n'affiche pas mon 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);
        }
}

Voici mon fichier HTML

<!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>
Était-ce utile?

La solution

Voici un exemple simple qui montre une image d'une URL d'Internet.Vous utiliseriez probablement une ressource à la place de l'URL Internet, comme une image conservée dans un répertoire du fichier jar de l'application:

Classe 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();
      }
   }
}

classe 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
      }
   }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top