Loading an image in an applet

I am trying to load and display an existing image to my applet and break the image up into segments to allow the pieces to be moved into their correct position. However it is only getting as far as cutting the image up but it does not complete loading the image. Below is the run() method im using to load it:
public void run()
        int i;
        MediaTracker trackset;              // Tracker for images
        Image WholeImage;                 // The whole image
                    Image ResizedImage;
        ImageFilter filter;
     // Determine the size of the applet
     r = getSize();
        // Load up the image
        if (getParameter("SRC") == null)
          Error("Image filename not defined.");
     WholeImage = getImage(getDocumentBase(), getParameter("SRC"));
     // Scale original image if needed
        // Make the image load completely and put the image
        // into the track set.  Where it waits in paint() method.
        trackset = new MediaTracker(this);
        trackset.addImage(WholeImage, 1);
        // Mix up the puzzle
        System.out.println("Mixing puzzle.");
        PaintScreen = 2;
        repaint();
        try {
        Thread.sleep(100);
     } catch (InterruptedException e) {
        // Tell user of the wait for image loading
       //Trap trackset exceptions that track if the image
       //hasn't loaded properly and output to the user.
        PaintScreen = 0;
        repaint();
        try {
        Thread.sleep(100);
     } catch (InterruptedException e) {
        try {
           trackset.waitForID(1);
        } catch (InterruptedException e) {
           Error("Loading Interrupted!");
        // Check if image loaded up correctly
        //Where is image is held in the same directory
        //as the HTML file use getImage method to pass
        //getDocumentBase(), taking in the getParameter.
        if (WholeImage.getWidth(this) == -1)
             PaintScreen = 3;
             repaint();
             WholeImage = getImage(getDocumentBase(), getParameter("SRC"));
             trackset = new MediaTracker(this);
             trackset.addImage(WholeImage, 1);
             try {
                trackset.waitForID(1);
             } catch (InterruptedException e) {
                Error("Loading Interrupted!");
             if (WholeImage.getWidth(this) == -1)
                  PaintScreen = 4;
                  repaint();
                  stop();
                  return;
     // Resize picture if needed.
     int ResizeOption = integerFromString(getParameter("RESIZE"));
     if ((r.width != WholeImage.getWidth(this) ||
          r.height != WholeImage.getHeight(this)) &&
            ResizeOption != 0)
          if (ResizeOption == 2)
            ResizedImage =
              WholeImage.getScaledInstance(r.width, r.height - TOP_MARGIN,
                                 WholeImage.SCALE_FAST);
          else if (ResizeOption == 3)
            ResizedImage =
              WholeImage.getScaledInstance(r.width, r.height - TOP_MARGIN,
                                 WholeImage.SCALE_SMOOTH);
          else if (ResizeOption == 4)
            ResizedImage =
              WholeImage.getScaledInstance(r.width, r.height - TOP_MARGIN,
                                 WholeImage.SCALE_AREA_AVERAGING);
          else
            ResizedImage =
              WholeImage.getScaledInstance(r.width, r.height - TOP_MARGIN,
                                 WholeImage.SCALE_DEFAULT);
          trackset.addImage(ResizedImage, 2);
          PaintScreen = 5;
          repaint();
          try {
          Thread.sleep(100);
          } catch (InterruptedException e) {
          try {
          trackset.waitForID(2);
          } catch (InterruptedException e) {
          Error("Loading Interrupted!");
          WholeImage = ResizedImage;
        // Complete loading image.  Start background loading other things
        // Also put image into the Graphics class
        // Split up main image into smaller images
        PaintScreen = 1;
        repaint();
        try {
           Thread.sleep(100);
        } catch (InterruptedException e){}
        piecewidth = WholeImage.getWidth(this) / piecesx;
        pieceheight = WholeImage.getHeight(this) / piecesy;
        System.out.println("Image has loaded.  X=" +
                           WholeImage.getWidth(this) + " Y=" +
                           WholeImage.getHeight(this));
        imageset = new Image[totalpieces];
        for (i = 0; i < totalpieces; i++)
             filter = new CropImageFilter(GetPieceX(i) * piecewidth,
                                          GetPieceY(i) * pieceheight,
                                          piecewidth, pieceheight);
             imageset[i] = createImage(new
                                       FilteredImageSource(WholeImage.getSource(),
                                                           filter));
        // Set up the mouse listener
        System.out.println("Adding mouse listener.");
        addMouseListener(this);
        // Complete mixing the image parts
        System.out.println("Displaying puzzle.");
        PaintScreen = -1;
        repaint();
        while (end != null)
          try {
             Thread.sleep(100);
          } catch (InterruptedException e){}
     }Any help to where im going wrong would be much appreciated. Thanks!

ive seen this one many times and it dosent work for me! Shouldnt the second parameter of the getImage(...) method not include the 'http://..." part as that what getDocumentBase() is for, returning the URL of the page the applet is embedded in? I have tried using code like this and event getting a printout of the doc/code base into the console to make sure my images are in the right place (.gif images), and nothing's happening, null pointer every time!
{code}
Image image;
public void init() {
// Load image
image = getImage(getDocumentBase(), "http://hostname/image.gif");
public void paint(Graphics g) {
// Draw image
g.drawImage(image, 0, 0, this);
{code}
ps this code is from the site mentioned above
Edited by: Sir_Dori on Dec 8, 2008 8:37 AM

Similar Messages

  • Loading an image into an Applet from a JAR file

    Hello everyone, hopefully a simple question for someone to help me with!
    Im trying to load some images into an applet, currently it uses the JApplet.getImage(url) method just before registering with a media tracker, which works but for the sake of efficiency I would prefer the images all to be contained in the jar file as oppossed to being loaded individually from the server.
    Say I have a class in a package eg, 'com.mydomain.myapplet.class.bin' and an images contained in the file structure 'com.mydomain.myapplet.images.img.gif' how do I load it (and waiting for it to be loaded before preceeding?
    I've seen lots of info of the web for this but much of it is very old (pre 2000) and im sure things have changed a little since then.
    Thanks for any help!

    I don't touch applets, so I can't help you there, but here's some Friday Fun: tracking image loading.
    import java.awt.*;
    import java.awt.image.*;
    import java.beans.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.imageio.event.*;
    import javax.imageio.stream.*;
    import javax.swing.*;
    public class ImageLoader extends SwingWorker<BufferedImage, Void> {
        private URL url;
        private JLabel target;
        private IIOReadProgressAdapter listener = new IIOReadProgressAdapter() {
            @Override public void imageProgress(ImageReader source, float percentageDone) {
                setProgress((int)percentageDone);
            @Override public void imageComplete(ImageReader source) {
                setProgress(100);
        public ImageLoader(URL url, JLabel target) {
            this.url = url;
            this.target = target;
        @Override protected BufferedImage doInBackground() throws IOException {
            ImageInputStream input = ImageIO.createImageInputStream(url.openStream());
            try {
                ImageReader reader = ImageIO.getImageReaders(input).next();
                reader.addIIOReadProgressListener(listener);
                reader.setInput(input);
                return reader.read(0);
            } finally {
                input.close();
        @Override protected void done() {
            try {
                target.setIcon(new ImageIcon(get()));
            } catch(Exception e) {
                JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
        //demo
        public static void main(String[] args) throws IOException {
            final URL url = new URL("http://blogs.sun.com/jag/resource/JagHeadshot.jpg");
            EventQueue.invokeLater(new Runnable(){
                public void run() {
                    launch(url);
        static void launch(URL url) {
            JLabel imageLabel = new JLabel();
            final JProgressBar progress = new JProgressBar();
            progress.setBorderPainted(true);
            progress.setStringPainted(true);
            JScrollPane scroller = new JScrollPane(imageLabel);
            scroller.setPreferredSize(new Dimension(800,600));
            JPanel content = new JPanel(new BorderLayout());
            content.add(scroller, BorderLayout.CENTER);
            content.add(progress, BorderLayout.SOUTH);
            JFrame f = new JFrame("ImageLoader");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(content);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            ImageLoader loader = new ImageLoader(url, imageLabel);
            loader.addPropertyChangeListener( new PropertyChangeListener() {
                 public  void propertyChange(PropertyChangeEvent evt) {
                     if ("progress".equals(evt.getPropertyName())) {
                         progress.setValue((Integer)evt.getNewValue());
                         System.out.println(evt.getNewValue());
                     } else if ("state".equals(evt.getPropertyName())) {
                         if (SwingWorker.StateValue.DONE == evt.getNewValue()) {
                             progress.setIndeterminate(true);
            loader.execute();
    abstract class IIOReadProgressAdapter implements IIOReadProgressListener {
        @Override public void imageComplete(ImageReader source) {}
        @Override public void imageProgress(ImageReader source, float percentageDone) {}
        @Override public void imageStarted(ImageReader source, int imageIndex) {}
        @Override public void readAborted(ImageReader source) {}
        @Override public void sequenceComplete(ImageReader source) {}
        @Override public void sequenceStarted(ImageReader source, int minIndex) {}
        @Override public void thumbnailComplete(ImageReader source) {}
        @Override public void thumbnailProgress(ImageReader source, float percentageDone) {}
        @Override public void thumbnailStarted(ImageReader source, int imageIndex, int thumbnailIndex) {}
    }

  • Loading PNG image file from Applet?

    Hi All,
    My applet running on IE6 and it will often loads 100 PNG image files from a webserver.
    Size of PNG file is about 60Kb so 100*60=6000 Kb ~ 6M.
    In theory, the applet will took 6M of memory to store all 100 files. In practical, it tooks about
    6M* 25 = 150M of memory, that make my applet run in out of memory sometimes.
    I know the reason, may be the brower/applet convert the PNG file format to BMP file format before showing on the screen.
    So the main point here is the applet should not loads all 100 files into the memory,
    it should loads only 10 files at the same time, another 90 files should be cached in memory as PNG file format, not BMP image file format to save the memory usage.
    Is this solution possible in applet field?
    If it is possible how can I implement it?
    And please show me better solution if anys.
    Many Thanks.

    I know the reason, may be the brower/applet convert the PNG file format to
    BMP file format before showing on the screen.This sounds VERY unlikely! Why should the browser do that? And the applet does what you have coded I hope!
    Your problem is probably somewhere else. And it has nothing to do with applets I presume. Use a heap analyzer tool to find out what hogs the memory. A thorough code review can't hurt either. If you still thinks it is the images though, then just don't load them all at once then.

  • Loading multiple images in applet

    I am trying to create an applet that displays 8 images in a grid and up until now I have had no problems loading single images into the applet but I am having difficulty more than one. I thought I could just create multiple lines of the getImage method. It keeps telling me that an identifier is expected. I'm quite new to this so don't mock me.
    import java.applet.*;
    import java.awt.*;
    import javax.swing.*;
    public class clown extends Applet {
    Image[] cln=new Image[8];
    cln[0]=getImage(getDocumentBase(), "clown2.gif");
    cln[1]=getImage(getDocumentBase(), "clown3.gif");
    cln[2]=getImage(getDocumentBase(), "clown4.gif");
    cln[3]=getImage(getDocumentBase(), "clown5.gif");
    cln[4]=getImage(getDocumentBase(), "clown6.gif");
    cln[5]=getImage(getDocumentBase(), "clown7.gif");
    cln[6]=getImage(getDocumentBase(), "clown8.gif");
    cln[7]=getImage(getDocumentBase(), "clown9.gif");
    public void paint(Graphics g){
    g.drawImage(cln[0], 0, 0, 0, 0, this);
    g.drawImage(cln[0], 50, 10, 0, 0, this);
    g.drawImage(cln[0], 100, 10, 0, 0, this);
    g.drawImage(cln[0], 150, 10, 0, 0, this);
    g.drawImage(cln[0], 200, 10, 0, 0, this);
    g.drawImage(cln[0], 250, 10, 0, 0, this);
    g.drawImage(cln[0], 300, 10, 0, 0, this);
    g.drawImage(cln[0], 350, 10, 0, 0, this);
    }

    Ive just noticed a mistake but that still doesnt resolve the problem it should read:
    import java.applet.*;
    import java.awt.*;
    import javax.swing.*;
    public class clown extends Applet {
    Image[] cln=new Image[8];
    cln[0]=getImage(getDocumentBase(), "clown2.gif");
    cln[1]=getImage(getDocumentBase(), "clown3.gif");
    cln[2]=getImage(getDocumentBase(), "clown4.gif");
    cln[3]=getImage(getDocumentBase(), "clown5.gif");
    cln[4]=getImage(getDocumentBase(), "clown6.gif");
    cln[5]=getImage(getDocumentBase(), "clown7.gif");
    cln[6]=getImage(getDocumentBase(), "clown8.gif");
    cln[7]=getImage(getDocumentBase(), "clown9.gif");
    public void paint(Graphics g){
    g.drawImage(cln[0], 0, 0, 0, 0, this);
    g.drawImage(cln[1], 50, 10, 0, 0, this);
    g.drawImage(cln[2], 100, 10, 0, 0, this);
    g.drawImage(cln[3], 150, 10, 0, 0, this);
    g.drawImage(cln[4], 200, 10, 0, 0, this);
    g.drawImage(cln[5], 250, 10, 0, 0, this);
    g.drawImage(cln[6], 300, 10, 0, 0, this);
    g.drawImage(cln[7], 350, 10, 0, 0, this);

  • Doh! Why I need an applet to load an image on the web page???

    Hi everybody.
    I'm new student in Java programming and I try since to 1 week to understand, why Java applet is used to load image or something else on web page?
    Why not to use shockwave or flash to load an image or an animation?
    What is the difference?
    Best regards,
    Dimnet2000
    Canada

    The answer could be "why not ?"
    A better answer would be "it depends on what you want to do."
    If you simply want to display an image you should neither use Java nor Shockwave, plain html will be the best.
    If you want to do things like:
    - accessing a database
    - dynamically creating html
    - make an application accessible within the intranet of a company
    - make all at once
    - make other dynamic things
    Then Java is a good way to handle all these. Since it is a full programming language you can do more variable things than with shockwave which is fine for simple things that should look good.
    Btw.: If you want to train how to use Java on a html page displaying an image with Java is no bad idea. It gives a feeling on what you have to do when using Java.
    Hope this helps, Rommie.

  • Problem loading images in my applet

    Hi guys,
    When i test my Applet using an IDE the images are loaded fine, however when I run my applet using a browser it wont load the images.
    I think it is because I use this line:
    System.getProperty("java.class.path",".")My question is, how do you load images into an applet without signing it.
    Any help would be great.
    Alex

    Axilliary files like images, properties files etc. which are essentially part of the program are refered to as "resources". The best way to access these files is by the getResource() methods in the Class or ClassLoader objects. If you do it that way then the JVM reads them exactly the same way it reads .class and from the same place.
    Say your using an image, say my.gif from a class called MyClass. You put the image file in the same directory as the MyClass.class file. Then, in MyClass, you do:
    static ImageIcon myImage = new ImageIcon(MyClass.class.getResource("my.gif"), "MY Image");That will pick up the image from a file, from an http connection, from a jar, of from any combination of same.

  • Applet loading of images -- network or JAR approach faster?

    hi all,
    i'm stumped. my applet used to load images over the network. (it was actually designed by someone else.) yes, the applet used to load each image file independently over the network and incurred a network hit per image file.
    to avoid the overhead of a separate network connection for each image file, i bundled all the images into the same JAR file that contains the applet. yet, the loading time for the applet is somehow slower now. i'm totally mystified.
    i put the code for loading each image into a separate thread as well. here's the thread code:
    BEGIN CODE
    public class ImageLoaderThread extends Thread {
         private Hashtable images;
         private DesignApplet applet;
         public ImageLoaderThread(DesignApplet applet, Hashtable images, String imageFile) {
              super(imageFile);
              this.images = images;
              this.applet = applet;
         public void run() {
              try {
                   System.out.println("Starting to load image ...");
                   String imageFile = getName();
                   InputStream is = applet.getClass().getResourceAsStream(imageFile);
                   int arraySize = is.available() * 2; // CH: create extra space just in case
                   System.out.println("Image Loader Thread: " + imageFile + "bytes available: " + arraySize);
                   BufferedInputStream bis = new BufferedInputStream(is);
                   byte[] byBuf = new byte[arraySize]; // a buffer large enough for our image
                   int byteRead = bis.read(byBuf, 0, arraySize);
                   Image buttonImage = Toolkit.getDefaultToolkit().createImage(byBuf);
                   images.put(imageFile, buttonImage);
              catch(Exception e) {
                   System.out.println("Exception while loading: " + getName());
                   e.printStackTrace();
    END CODE
    imageFile is the name of an image file stored in the JAR file. it's not stored on the server anywhere, so i know the image is getting created from the JAR file. despite this, the speed of image creation seems tied to the network. in other words, when i attempt to load the applet over a slow link, it takes longer to load than over a fast link.
    any ideas what i'm doing wrong? i'm seriously stumped and could use help. my goals are to minimize loading time of the applet while minimizing network hits for the server.
    thanks!
    p.s. if you want to play w/ the applet, click on the following link and click the "Customize" button: http://www.cengraving.com/s/z/Photo-plaques/PP024.jsp

    Why are you using a thread to load each image why not just load the images in the gui thread?
    Each thread you create takes a finite time to be started and stopped. This will surely have added to the load and startup time.
    There is also blocking going on since using the Java Console I can see that each thread reports in sequence:
    "Starting to load image ..."
    And then after all threads have reported they are starting they then report in squence:
    Image Loader Thread: " + imageFile + "bytes available: " + arraySize information.
    This shows that there is at least some blocking going on with the threads.
    I don't think using separate threads to do the loading is helping at all. Just load them one after another in the same thread (the thread all your threads are being started from).
    The putting of the images into the images Hashtable will also be blocking since Hashtable is synchronized.

  • How to load the image on to the Java applet?

    Hey,
    I need help on loading a image to java, I am using Eclipse, I have no idea what class I should use. Please help me thanks

    I found this with search problem with loading images

  • Image processing with applets

    Hi
    I need to create a website with several image processing applets on it. however although the applets work locally they will not load at all through a server (i'm a student) my supervisor tells me i cant use an applet to display an image stored on a server. but as applets specifically have getImage methods which must be able to get images from the server i think he is wrong but do not know how to do it.
    Any advice will result in some really great Karma directed your way.
    thanks

    here's the code I use, make special note of the getDocumentBase(), as this request will be a URL based request, rather than a file read
    try {
    img = getImage(getDocumentBase(), "logo.gif");
    }catch(Throwable t) {
    System.out.println("Unable to load logo image",t);
    t.printStackTrace();
    hope this helps

  • How to writing an image from my applet to my apache webserver

    hi everyone,
    i have a big problem, writing an image from my applet to my apache
    webserver. i tried three way's of writing that file. every way was
    described in forums to solve this problem, but non of them worked and
    i don't know why. i'll give you the code of my writing-methods and
    describe, what happen when i test them, in order someone of you can
    give me an usefull tip, where the problem is.
    as inputparameter i give my method a new URL referring to
    http://localhost/test.jpg (this is the same directory, where my applet
    is loaded from, so i should have reading and writing permission,
    havn't i? while i'm developing, my applet runs on the same pc as my
    webserver, just in case you're wondering about localhost) and a
    selfmade BufferedImage (i already testet if it is not null and shows
    the correct things ... all ok).
    1. try:
    private void writeImageToServer(URL fileURL,BufferedImage img){
    try {
    URLConnection urlConnection = fileURL.openConnection();
    urlConnection.setDoOutput(true);
    OutputStream urlout = urlConnection.getOutputStream();
    BufferedOutputStream out = new BufferedOutputStream(urlout);
    ImageIO.write(img,"jpg",out);
    out.close(); // i also tried without this line -> same result
    // additionally a question: do i need
    out.close()?
    catch( IOException e ){
    e.printStackTrace();
    result:
    test.jpg doesn't appear in the webroot. but some very strange messages
    in the error.log of my apacheserver:
    [Tue Jun 08 11:40:22 2004] [error] [client 127.0.0.1] File does not
    exist: c:/programme/apache
    group/apache/htdocs/meta-inf/services/javax.imageio.spi.ImageOutputStreamSpi
    [Tue Jun 08 11:40:22 2004] [error] [client 127.0.0.1] File does not
    exist: c:/programme/apache
    group/apache/htdocs/meta-inf/services/javax.imageio.spi.ImageReaderSpi
    [Tue Jun 08 11:40:22 2004] [error] [client 127.0.0.1] File does not
    exist: c:/programme/apache
    group/apache/htdocs/meta-inf/services/javax.imageio.spi.ImageInputStreamSpi
    [Tue Jun 08 11:40:22 2004] [error] [client 127.0.0.1] File does not
    exist: c:/programme/apache
    group/apache/htdocs/meta-inf/services/javax.imageio.spi.ImageWriterSpi
    [Tue Jun 08 11:40:22 2004] [error] [client 127.0.0.1] File does not
    exist: c:/programme/apache
    group/apache/htdocs/meta-inf/services/javax.imageio.spi.ImageTranscoderSpi
    i cannot explain this lines to myself, because my apache should have
    nothing to do with java. all my javacode is executed on the client
    side in the browser. do this messages mean i have to add the ImageIO
    package from the sdk to my jar-applet. the jre, used by my iexplorer,
    doesn't contain this files in the meta-inf/services directory of
    rt.jar, but that's version 1.4.2_03, the same as my sdk, and the
    rt.jar contains the corresponding classfiles at javax.imageio.spi. so
    i'm realy confused by this messages.
    2. try:
    private void writeImageToServer(URL fileURL,BufferedImage img){
    try {
    URLConnection urlConnection = fileURL.openConnection();
    urlConnection.setDoOutput(true);
    OutputStream urlout = urlConnection.getOutputStream();
    BufferedOutputStream out = new BufferedOutputStream(urlout);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(img);
    out.close(); // same comments as above
    catch( IOException e ){
    e.printStackTrace();
    result:
    nothing. no error-messages in the error.log, no exceptions in the
    java-console and no test.jpg in the webroot. i searched my whole
    harddrives for it: nothing. isn't this the way, the JPEGImageEncoder
    works?
    3. try:
    private void writeImageToServer(URL fileURL,BufferedImage img){
    try {
    File file = new File(fileURL.toString);
    file.createNewFile();
    BufferedOutputStream out = new BufferedOutputStream(new
    FileOutputStream(file));
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(img);
    out.close(); // same comments as above
    catch( Exception e ){
    e.printStackTrace();
    result:
    the SecurityManager denies this action with "access denied" while
    calling createNewFile(). well, this way was dedicated to run from an
    application, not from an applet. i'd have to sign my applet to get the
    rights to do this, or i can edit java.policy on my client, what i
    don't want, because i cannot do this on every client, the applet will
    run, when i'm finished with it. this brings me to the question: does
    anybody know's how to sign my applet and give it full access to the
    harddrive and the webserver without paying 400$ to VeriSign for a
    commercial CA? i want to do this by myself, without paying anything
    and without giving a lot of information to another company.
    i would realy appreciate, if someone could give me a hint where i am
    wrong or how to do this correct.
    thank you very much
    [email protected]

    You hold several misconceptions. The first is that an applet can write to a server without help from the server. That will never work on a real server (though it might work in testing, if the server is on the same PC as the applet). Applets cannot get a File object that points to any place on the server.
    If you write a servlet designed for accepting image uploads, the applet can communicate back to that servlet and feed it the bytes of the image. There are other technologies that can replace the servlet, of course (PHP, ASP..) but I mention that because you say you are running Apache - and that is very Java oriented.
    For more help on servlets, try the [Web Tier APIs - Java Servlet|http://forums.sun.com/forum.jspa?forumID=33] forum.

  • How  can I  load an  image  in a scene?

    I want to load an image in a scene and I have tried it using the
    steve morris example( HAVI example ) , I am using a STB and when I send my xlet I don�t see this imagen at the tv.
    Source code is available from
    http://www.interactivetvweb.org/resources/code/havi/HaviXlet.zip
    Somebody knows another way to do it ???

    I assume you mean a JLabel as an AWT Label cannot display an Image.
    // POINT THE IMAGE BACK TO THE SERVER FROM WHICH THE APPLET WAS DOWNLOADED
    // BY USING GETCODEBASE(). OMIT THAT AND YOU WILL SEE THAT YOU GET A SECURITY
    // EXCEPTION AS THE APPLET WILL TRY TO LOCTE THE IMAGE ON THE LOCAL MACHINE AND
    // APPLETS BY DEFAULT CANNOT ACCESS RESOURCES ON THE CLIENT
    // assumes .gif file exists in same directory as HTML running the Applet
    Image image = getImage(getCodeBase(), "ImageName.gif");
    ImageIcon icon = new ImageIcon(image);
    JLabel - new JLabel(icon);
    // check out the getScaledInstance() method of Image class to resize your image

  • Displaying images in an applet

    Hi everyone.
    I have been developing an applet game in the applet viewer - which it works fine in. But when I open it in a browser, everything is displayed appart from the image - can't figure out why!
    Is it the way I am adding images to the display, this is how i am doing it at the moment....
    public static ImageIcon gameInfoPanelTitle = new ImageIcon("images/gameinformation.jpg");
    JLabel gameInfoPanelIntro = new JLabel(gameInfoPanelTitle);
    contentPane.add(gameInfoPanelIntro);thanks in advance guys!

    Check your Sun Java console. It may be generating NullPointerExceptions (or some other exception) when loading the images. This could be a result of the file path. When you access it using a browser, you're not downloading it across a network, from, say, a server, are you? That would definitely cause that problem.

  • Help!  Image in an applet

    Hi, I'm having some trouble displaying an image in my applet. I drew something in MS Paint, saved it as a gif, and want to draw it in my applet. I have tried using two methods to load the image:
    map = getImage(getCodeBase(),"cheese.gif");
    and
    Toolkit toolkit = getToolkit();
    map =toolkit.createImage("cheese.gif");
    System.out.println(map == null) prints false for both methods, meaning that (I assume) Java has found and knows what .gif I am requesting. I am drawing the image with
    g.drawImage(map, 25, 150, this);
    I have tried replacing "this" with "getContentPane()" as well, but that was fruitless.
    I think am importing all the right classes, like java.awt.*.
    My applet extends JApplet (I don't know this has anything to do with it). I would post the entire applet, but it is quite lengthy at the moment. Any help would be much appreciated, thanks in advance, and sorry about the long post. If anyone needs anymore information to help me, I will be glad to help.

    Try this html and code:
    <HTML>
        <HEAD>
            <TITLE></TITLE
        </HEAD>
        <BODY>
            <APPLET CODE="ImgApplet.class" width=500 height=500>
            <PARAM NAME=pic VALUE="ImgAppletPic.jpg">
            </APPLET>
        </BODY>
    </HTML>
    import java.awt.*;
    import java.applet.*;
    public class ImgApplet extends Applet {
        // var to store the pic;
        Image pic;
            // retrieving image;
            public void init() {
            pic = getImage(getCodeBase(), getParameter("pic"));
            public void paint(Graphics g) {
            g.drawImage(pic, 10, 10, this);
    }

  • Displaying an image in an applet

    hi there - can anyone tell me why the following code only displays the image through the applet viewer but when i load it in a browser it just displays a grey square the same size as the image i'm trying to load?! many thanks.
    import java.awt.*;
    import javax.swing.*;
    import java.net.*;
    public class DisplayImage extends JApplet
         public void init()
              ImageIcon icon = null;
              try
                   icon = new ImageIcon(new URL(getCodeBase(), "map.jpg"));
              catch(MalformedURLException e)
                   System.out.println("Failed to create URL:\n" + e);
                   return;
              int imageWidth = icon.getIconWidth();
              int imageHeight = icon.getIconHeight();
              resize(imageWidth, imageHeight);
              ImagePanel imagePanel = new ImagePanel(icon.getImage());
              getContentPane().add(imagePanel);
         class ImagePanel extends JPanel
              public ImagePanel(Image image)
                   this.image = image;
              public void paint(Graphics g)
                   g.drawImage(image, 0, 0, this);
              Image image;

    Rat fans!

  • Problem with reading images in an applet

    Okay when i use Jbuilders applet viewer, my images load just fine, but when i use internet explorer to view the applet it finds the class files and tries to load the images, but has an error, so i look at the response from the java console, and it says there is problem reading the images - says their read only - so what? they arent anyway, and besides all im doing is reading them.
    Anyone know whats wrong? why does it display in the applet viewer in jbuilder but not in the webpage?
    Please respond to [email protected] Thanks

    I dont think that is the problem though, as mediatracker is just to ensure that before the paint method is called, the images are loaded instead of being loaded only once the paint method is called.
    I was thinking that it may be the fact that the application is not signed so there may be security violations in the browser but that should only apply when the files do not reside on the computer from where your calling it from.
    what do u think?
    Thanks

Maybe you are looking for

  • Can't omit both the rowset and the row element?

    consider the simple document below. Notice that row-element and rowset-element are both empty, so neither type of element will be generated. Also notice that the xsql:query tag is embedded in other tags. I get "oracle.xml.sql.OracleXMLSQLException: T

  • No volumes in Disk Utility

    Dear Folks: I am working on a friend's 1 GIG 17" Powerbook with OS X 10.2.8. My firewire drive will not mount on the desktop. No icon appears. When I go to Disk Utility the pane which normally lists volumes is empty. What do I do? Thanks Raoul

  • PDF Documents suddenly display as black only

    Earlier this year I suddenly had numerous PDF documents start displaying completely black, making it impossible to read the text. Sometimes images appear as ghosted white outlines, but most commonly the whole document is simply a black blob. I can op

  • 2 questions from a new user........

    7/26 Hi!  Forgive me but I am a new Iphone user and have 2 questions.  1) How/where do you find what the remaining memory on your phone is after some apps have been added?  2) I have deleted the icon of a free app I downloaded but understand that doe

  • After upgrading to 20.0.1, my mouse scrolling speed is slow

    I've just updated to 20.0.1 from 19.0.2 and suddenly, the speed of my mouse scrolling has decreased dramatically. When I tried other browsers, it was usual/normal speed but for firefox, it was very slow (i.e around 5+ lines decreased). I have looked