How can I display an image in the Applet?

后端 未结 3 1415
执念已碎
执念已碎 2020-12-09 14:20

I have an image and I want to display it in the applet, The problem is the image wont display. Is there something wrong with my code?

Thanks...

Here\'s my co

3条回答
  •  心在旅途
    2020-12-09 15:03

    aang = getImage(getDocumentBase(), getParameter("images.jpg"));
    

    I suspect you are doing something wrong, and that should be just plain:

    aang = getImage(getDocumentBase(), "images.jpg");
    

    What is the content of HTML/applet element? What is the name of the image? Is the image in the same directory as the HTML?

    Update 1

    The 2nd (changed) line of code will try to load the images.jpg file in the same directory as the HTML.

    Of course, you might need to add a MediaTracker to track the loading of the image, since the Applet.getImage() method returns immediately (now), but loads asynchronously (later).

    Update 2

    Try this exact experiment:

    Save this source as ${path.to.current.code.and.image}/FirstAirBender.java .

    /*
    
    
    */
    import javax.swing.*;
    import java.awt.*;
    import java.net.URL;
    import javax.imageio.ImageIO;
    
    public class FirstAirBender extends JApplet {
    
        Image aang;
    
        public void init() {
            try {
                URL pic = new URL(getDocumentBase(), "images.jpg");
                aang = ImageIO.read(pic);
            } catch(Exception e) {
                // tell us if anything goes wrong!
                e.printStackTrace();
            }
        }
    
        public void paint(Graphics g) {
            super.paint(g);
            if (aang!=null) {
                g.drawImage(aang, 100, 100, this);
            }
        }
    }
    

    Then go to the prompt and compile the code then call applet viewer using the source name as argument.

    C:\Path>javac FirstAirBender.java
    C:\Path>appletviewer FirstAirBender.java
    C:\Path>
    

    You should see your image in the applet, painted at 100x100 from the top-left.

提交回复
热议问题