Domanda

Sto cercando di aggiungere un'immagine alla mia applet. Ho cercato su Google questo, ma non ho trovato un esempio decente che ho capito. Qualcuno sa dove posso trovare un buon esempio di aggiunta di un'immagine e applet?

L'ho ottenuto online ma quando eseguo l'applet non visualizza la mia immagine.

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

Di seguito è il mio file 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>
È stato utile?

Soluzione

Ecco un semplice esempio che mostra un'immagine da un URL di Internet. Probabilmente useresti una risorsa al posto dell'URL di Internet, come un'immagine tenuta in una directory del barattolo dell'applicazione:

Classe SimpleppletImage.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
      }
   }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top