Jose
Jose

Reputation: 1

images do not appear on my java applet

Hey I'm trying to create a video game and I'm testing to see if I can make a sprite or image appear on the applet I've asked for help before from my peers and professor, but they don't seem to help. I don't know if I have the image in the wrong location or if my code is bugged, but I would appreciate if someone took a look at it Thanks! Oh! by the way I'm programming in Java and I'm using Eclipse JUNO.

enter code here

package meh;
import java.awt.*;
import javax.swing.JApplet;
import javax.swing.ImageIcon;


public class Draw  extends JApplet{
    public static void main(String[] args)
    {
        Draw test = new Draw();


    }
    private Image exImage;
    private boolean imagesLoaded;

    public void run()
    {

        imagesLoaded = false;

        try
        {
            loadImages();
            try
            {
                Thread.sleep(10000);

            }
            catch(InterruptedException ex){}
        }
        finally{}


    }
    public void loadImages()
    {
        exImage = loadImage("C:/Users/Temp/workspace/From Scratch/bin/Ma_rn_0");
        imagesLoaded = true;
        repaint();
    }
    private Image loadImage(String fileName)
    {
        return new ImageIcon(fileName).getImage();
    }
    public void paint(Graphics g)
    {
        if(g instanceof Graphics2D)
        {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        }
        if(imagesLoaded)
        {
            drawImage(g, exImage,0,0, null);
        }
        else
        {
            g.drawString("Loading...", 5, 12);
        }
    }

    public void drawImage(Graphics g, Image image, int x, int y, String caption)
    {
        g.drawImage(image, x, y, null);
        g.drawString(caption, x+5, y + 12 +image.getHeight(null));
    }

}

Upvotes: 0

Views: 1123

Answers (2)

Reimeus
Reimeus

Reputation: 159754

Unless they are signed, applets can only load images from the same location from where they originated. Here you are attempting to load an image from the local disk. All initialisation for applet resources should be done from the init method. Images can be loaded as resources from the same JAR file from which they are deployed. You could do

Image exImage = ImageIO.read(getClass().getResourceAsStream("images/MyImage.jpg"))

Upvotes: 1

Nikolay Kuznetsov
Nikolay Kuznetsov

Reputation: 9579

1 public static void main(String[] args)

Applets are not supposed to have main(), it uses init, start, stop and destroy.

http://docs.oracle.com/javase/tutorial/deployment/applet/getStarted.html

2 Try to learn about EDT concept

3 Don't override paint method

4 Use ImageIO to load images

Upvotes: 0

Related Questions