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

Similar Messages

  • Image Processing using applet

    hi,
    I am doing my project in java.My project is " Online Image Processing ".
    I did some processing like gray Scale, Invert , Contrast and rotate 90 degree.
    can any one help me for
    1. I vant to rotate Image to 1 degree...
    2. How to get Blure and Sharpen image?
    3. Can i append frames inside applet?
    plz Help me ..

    I did not read the content of the links (To lazy) just found them for you.
    You say that the examples use frames:
    this should not be a problem as the required code is the same.
    Tip:
    How whould you display a image in a frame?
    How whould you display a image in a applet?
    Concentrate on the above 2 and simply change the code accordingly.
    This should be easy also try asking google.

  • 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.

  • 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) {}
    }

  • Using Java Advanced Imaging (JAI) in Applet

    I'm trying to port a JAI user interface to an applet using Apache Tomcat. When I try to display an image in the applet I get an exception and I have no idea what the cause is. I've opened up security completely (temporarily) to ensure that I'm not getting an error due to an applet security issue. Consequently, I'm able to browse/open files from the client.
    Here is the stack for the error I'm getting. Can anyone tell me what is causing this error? Thanks.
    Java(TM) Plug-in: Version 1.4.1_01
    Using JRE version 1.4.1_01 Java HotSpot(TM) Client VM
    User home directory = C:\Documents and Settings\Administrator
    Proxy Configuration: No proxy
    c:   clear console window
    f:   finalize objects on finalization queue
    g:   garbage collect
    h:   display this help message
    l:   dump classloader list
    m:   print memory usage
    o:   trigger logging
    p:   reload proxy configuration
    q:   hide console
    r:   reload policy configuration
    s:   dump system properties
    t:   dump thread list
    v:   dump thread stack
    x:   clear classloader cache
    0-5: set trace level to <n>
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at javax.media.jai.FactoryCache.invoke(FactoryCache.java:130)
         at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1669)
         at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:481)
         at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:340)
         at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:805)
         at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:853)
         at javax.media.jai.RenderedOp.getWidth(RenderedOp.java:2135)
         at com.abi.protmodule.GelDisplayData.getGelImage(GelDisplayData.java:558)
         at com.abi.protmodule.ScrollingGelPanel.<init>(ScrollingGelPanel.java:58)
         at com.abi.ris.web.applet.GelEditPanel.showGelImage(GelEditPanel.java:76)
         at com.abi.ris.web.applet.GelEditApplet.openGelJButton_actionPerformed(GelEditApplet.java:159)
         at com.abi.ris.web.applet.GelEditApplet.chooseFileJButton_actionPerformed(GelEditApplet.java:136)
         at com.abi.ris.web.applet.GelEditApplet$1.actionPerformed(GelEditApplet.java:73)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1764)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1817)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:419)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
         at java.awt.Component.processMouseEvent(Component.java:5093)
         at java.awt.Component.processEvent(Component.java:4890)
         at java.awt.Container.processEvent(Container.java:1566)
         at java.awt.Component.dispatchEventImpl(Component.java:3598)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3439)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
         at java.awt.Container.dispatchEventImpl(Container.java:1609)
         at java.awt.Component.dispatchEvent(Component.java:3439)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    Caused by: java.lang.NoSuchFieldError: borders
         at com.sun.medialib.mlib.Image.initIDs(Native Method)
         at com.sun.medialib.mlib.Image.<clinit>(Image.java:2903)
         at com.sun.media.jai.mlib.MediaLibAccessor$1.run(MediaLibAccessor.java:223)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sun.media.jai.mlib.MediaLibAccessor.setUseMlib(MediaLibAccessor.java:220)
         at com.sun.media.jai.mlib.MediaLibAccessor.useMlib(MediaLibAccessor.java:185)
         at com.sun.media.jai.mlib.MediaLibAccessor.isMediaLibCompatible(MediaLibAccessor.java:391)
         at com.sun.media.jai.mlib.MediaLibAccessor.isMediaLibCompatible(MediaLibAccessor.java:314)
         at com.sun.media.jai.mlib.MlibScaleRIF.create(MlibScaleRIF.java:82)
         ... 39 more
    Could not find mediaLib accelerator wrapper classes. Continuing in pure Java mode.

    look at
    http://forum.java.sun.com/thread.jsp?thread=290960&forum=20&message=1261471
    and
    http://forum.java.sun.com/thread.jsp?forum=20&thread=173410
    It's something related with DLL libraries...

  • 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

  • Really need to show an image in this applet...

    Hi,
    I need to display an image in my applet as a sort of "Start Screen" like you get on games.
    But I'm damned if I can get it to work, my tutor provided the unifinished shell of a program, and it seems that I need to display this image before any... panels.. or whatever it is... are initiated. So I could either create a new one, just to show this image, then make it go away when the image does, or, have it popup as part of a message box, or something.
    I stumbled on a splash screen feature, found in Java 1.6, but although I'm using 1.6, my university still uses 1.5, so it's a no go.
    Ideally, it would be a popup window I think, more like a fancy about box than a title screen. But I don't know how to do that either, so any help would be greatly appreciated ^^
    Thanks

    Look into addNotify() and MediaTracker.

  • 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.

  • I can't see my image in an applet

    I am drawing an image in an applet, I see the image in jbuilder but i can't see it with IE 5.0 , I am using graphis 2D, please help me

    this is the code in the applet class:
    package untitled9;
    import java.awt.event.*;
    import java.awt.*;
    import java.net.*;
    import java.applet.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2003</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    public class Applet1 extends Applet
    boolean isStandalone = false;
    Image imagen,fondo;
    double alpha = -0.2;
    int r = 0;
    URL u,fondo_url;
    PopupMenu popupMenu1 = new PopupMenu();
    MenuItem menuItem1 = new MenuItem();
    //Get a parameter value
    public String getParameter(String key, String def)
    return isStandalone ? System.getProperty(key, def) :
    (getParameter(key) != null ? getParameter(key) : def);
    //Construct the applet
    public Applet1()
    //Initialize the applet
    public void init()
    try
    jbInit();
    catch(Exception e)
    e.printStackTrace();
    //Component initialization
    private void jbInit() throws Exception
    menuItem1.setLabel("rotar");
    this.addMouseListener(new java.awt.event.MouseAdapter()
    public void mousePressed(MouseEvent e)
    this_mousePressed(e);
    popupMenu1.add(menuItem1);
    //Get Applet information
    public String getAppletInfo()
    return "Applet Information";
    //Get parameter info
    public String[][] getParameterInfo()
    return null;
    public void paint(Graphics g)
    Graphics g_3 = g.create();
    Graphics2D g2 = (Graphics2D)g_3;
    Graphics2D g3 = (Graphics2D)g;
    if (r==1)
    g2.rotate(alpha,100,100);
    try
    fondo_url = new URL("file:/C:/Documents and Settings/macastro/Escritorio/untitled9/src/untitled9/fondo.gif");
    catch (MalformedURLException e)
    g3.drawString ("Mal formado el URL",10,10);
    fondo = getImage(fondo_url);
    g3.drawImage(fondo,100,100,this);
    try
    u = new URL("file:/C:/Documents and Settings/macastro/Escritorio/untitled9/src/untitled9/imagen.gif");
    catch (MalformedURLException e)
    g2.drawString ("Mal formado el URL",10,10);
    imagen = getImage(u);
    g2.drawImage(imagen,100,100,this);
    void this_mousePressed(MouseEvent e)
    r = 1;
    alpha+=-0.1;
    repaint();
    and this is the code in the html file:
    <html>
    <head>
    <title>
    HTML Test Page
    </title>
    </head>
    <body>
    untitled9.Applet1 will appear below in a Java enabled browser.<br>
    <applet
    codebase = "."
    code = "untitled9.Applet1.class"
    name = "TestApplet"
    width = "400"
    height = "300"
    hspace = "0"
    vspace = "0"
    align = "middle"
    >
    </applet>
    </body>
    </html>

  • Moving two seperate images in an applet

    Hi i am trying to move two seperate images on an applet. these images are two random cards from a pack of playing card, ie king,jack, queen etc..
    i can get both images moving at the same time but i want i want to do is to animate the movement of one image and when it raches a certain point onscreen, the other image moves to a different position onscreen and i should end up with both card images onscreen at different positions.
    here is the code for the part in which the applet draws the image to the graphics object:
    public void run()
            long tm = System.currentTimeMillis();
             while(Thread.currentThread() == t)
                 repaint();
                 try
                     tm += delay;
                     Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
                     //increment frame so that image moves 4 pixels at a time
                     f1 = f1 + 4;
                     f2 = f2 + 5;
                     f3 = f3 + 2;
                     f4 = f4 + 2;
                 catch(InterruptedException e)
                     break;
        public void stop()
            t = null;
        public void update(Graphics g)
            //code that generates 5 random card and animate them onscreen.
            Dimension d = size();
            int w = cards[r1].getWidth(this);
            int h = cards[r1].getHeight(this);
            if(f1 <= 100)
                // Erase the previous image
                g.setColor(getBackground());
                g.fillRect(0, 0, d.width, d.height);
                g.setColor(Color.black);
                g.drawImage(cards[r1], f2, f1, this);  //co ordinates
                if((r1 != r2) && (f1 == 100 ) && (f3 <= 300))
                    g.drawImage(cards[r2], f4, f3, this);  //co ordinates
            //g.drawImage(cards[r2], f4, f3, this);  //co ordinates
        }Has u can see from the above code. all 52 card images are stored in an array. I use a random function to generate a random image from the array, in this case two random images.
    i have used if statements that tell me when to stop the animation of an image and when to start the next image for animation using the f1,f2,f3 etc.. these are used for the co ordinates of the actual images.
    i increment them each time the applet is run from within a Thread.

    Sounds like you just need a little swing(or awt if you're using "old java")
    http://java.sun.com/docs/books/tutorial/uiswing/mini/index.html
    BorderLayout might be useful. Be aware that it can be tricky to switch out swing components and you may need to validate the container.
    Also, be aware that a "Frame"(JFrame) in java are what you would call a window and that a "Panel"(JPanel) in java is basically just an area that contains components, kinda like a <div> or <span> in html.

  • 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!

  • I need help with the Quote applet.

    Hey all,
    I need help with the Quote applet. I downloaded it and encoded it in the following html code:
    <html>
    <head>
    <title>Part 2</title>
    </head>
    <body>
    <applet      codebase="/demo/quote/classes" code="/demo/quote/JavaQuote.class"
    width="300" height="125" >
    <param      name="bgcolor"      value="ffffff">
    <param      name="bheight"      value="10">
    <param      name="bwidth"      value="10">
    <param      name="delay"      value="1000">
    <param      name="fontname"      value="TimesRoman">
    <param      name="fontsize"      value="14">
    <param      name="link"      value="http://java.sun.com/events/jibe/index.html">
    <param      name="number"      value="3">
    <param      name="quote0"      value="Living next to you is in some ways like sleeping with an elephant. No matter how friendly and even-tempered is the beast, one is affected by every twitch and grunt.|- Pierre Elliot Trudeau|000000|ffffff|7">
    <param      name="quote1"      value="Simplicity is key. Our customers need no special technology to enjoy our services. Because of Java, just about the entire world can come to PlayStar.|- PlayStar Corporation|000000|ffffff|7">
    <param      name="quote2"      value="The ubiquity of the Internet is virtually wasted without a platform which allows applications to utilize the reach of Internet to write ubiquitous applications! That's where Java comes into the picture for us.|- NetAccent|000000|ffffff|7">
    <param      name="space"      value="20">
    </applet>
    </body>
    </html>When I previewed it in Netscape Navigator, a box with a red X appeared, and this appeared in the console when I opened it:
    load: class /demo/quote/JavaQuote.class not found.
    java.lang.ClassNotFoundException: .demo.quote.JavaQuote.class
         at sun.applet.AppletClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadCode(Unknown Source)
         at sun.applet.AppletPanel.createApplet(Unknown Source)
         at sun.plugin.AppletViewer.createApplet(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.io.FileNotFoundException: \demo\quote\JavaQuote\class.class (The system cannot find the path specified)
         at java.io.FileInputStream.open(Native Method)
         at java.io.FileInputStream.<init>(Unknown Source)
         at java.io.FileInputStream.<init>(Unknown Source)
         at sun.net.www.protocol.file.FileURLConnection.connect(Unknown Source)
         at sun.net.www.protocol.file.FileURLConnection.getInputStream(Unknown Source)
         at sun.applet.AppletClassLoader.getBytes(Unknown Source)
         at sun.applet.AppletClassLoader.access$100(Unknown Source)
         at sun.applet.AppletClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         ... 10 more
    Exception in thread "Thread-4" java.lang.NullPointerException
         at sun.plugin.util.GrayBoxPainter.showLoadingError(Unknown Source)
         at sun.plugin.AppletViewer.showAppletException(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    java.lang.NullPointerException
         at sun.plugin.util.GrayBoxPainter.showLoadingError(Unknown Source)
         at sun.plugin.AppletViewer.showAppletStatus(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)What went wrong? and how can I make it run correct?
    Thanks,
    Nathan Pinno

    JavaQuote.class is not where your HTML says it is. That is at the relative URL "/demo/quote/".

  • Add Image to an Applet

    How do I add an image to an applet (along with other components:button, choice etc)? Sample code would be appreciated. I do not see any component to add image.
    Thanks.

    If you are using one of the getImage methods, they don't wait around for the image to load; they return immediately. So we use a MediaTracker to block program execution until the image is completely loaded. This is older java technology and will work in older versions of java. If you are using j2se 1.4+ then you can use the ImageIO class for loading an image.
    /*  <applet code="AppletImage" width="400" height="400"></applet>
    *  use: >appletviewer AppletImage.java
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    public class AppletImage extends Applet
        public void init()
            Button button = new Button("Button");
            Choice choice = new Choice();
            choice.add("item 1");
            choice.add("item 2");
            Panel north = new Panel();
            north.add(button);
            north.add(choice);
            TextField tf = new TextField("text field", 12);
            Panel fieldPanel = new Panel();
            fieldPanel.add(tf);
            ScrollPane scrollPane = new ScrollPane();
            scrollPane.add(new AppletImagePanel());
            Panel panel = new Panel(new BorderLayout());
            panel.add(scrollPane);
            panel.add(fieldPanel, "South");
            setLayout(new BorderLayout());
            add(north, "North");
            add(panel);
        public static void main(String[] args)
            Applet applet = new AppletImage();
            Frame f = new Frame();
            f.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
            f.add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            applet.start();
            f.setVisible(true);
    class AppletImagePanel extends Panel
        Image image;
        public AppletImagePanel()
            loadImage();
        public void paint(Graphics g)
            super.paint(g);
            int w = getWidth();
            int h = getHeight();
            int imageWidth = image.getWidth(this);
            int imageHeight = image.getHeight(this);
            int x = (w - imageWidth)/2;
            int y = (h - imageHeight)/2;
            g.drawImage(image, x, y, this);
        public Dimension getPreferredSize()
            return new Dimension(image.getWidth(this), image.getHeight(this));
        private void loadImage()
            String fileName = "images/owls.jpg";
            MediaTracker tracker = new MediaTracker(this);
            URL url = getClass().getResource(fileName);
            image = Toolkit.getDefaultToolkit().getImage(url);
            tracker.addImage(image, 0);
            try
                tracker.waitForID(0);
            catch(InterruptedException ie)
                System.err.println("interrupt: " + ie.getMessage());
    }

  • Broken help images

    I have had a recurring problem with RoboHelp for Word 6.
    Whenever I have to work on a help project that I havent' looked at
    in a while, I make my edits and then try to compile (to Web help).
    I will get a silent compile failure - the status window says
    'Starting compilation...' and the window title says 'WebHelp has
    been generated'. No help files are generated. I have learned from
    experience (and possibly from this forum) that what this means is
    that a help image 'object' has become corrupt and ends up as a Word
    image rather than a RH help image. I have to go through each module
    (all 28 of them) and switch from Dynamic WYSIWYG to TrueCode. I
    started to save the files in TrueCode mode, so that means I have to
    convert to WYSIWYG and then convert again to TrueCode. Then I have
    to search (visually) for any images that didn't get converted,
    delete the image, and re-insert it the RH way. I have noticed that
    It is usually one particular image btnChoices.bmp - just an image
    of a small button with 3 periods (to simulate an ellipsis - we use
    it to show a list of choices that can be entered into a field). So,
    a 15 edit ends up taking a day or so trying to get it to compile.
    Well it finally happened - I have a file that doesn't get
    fixed when I do that. I have it down to:
    1. delete the image
    2. re-insert the image
    3. convert to WYSIWYG
    4. convert to TrueType
    5. The conversion fails on the image I just added
    I tried re-capturing the image and giving it a different name
    - no luck.
    Has any one else had this problem? Did Adobe correct it in
    version 7?
    Phil

    Updating to RoboHelp 7 didn't help.
    I ended up making a new project and importing all the .doc
    files into it. I found one place that had a compiler tag that
    didn't make sense. I removed the tag. Anyway I got it to work -
    still don't know for sure what was wrong. A better message would
    sure help - or a log file to see how far it got.
    Phil

  • Animating array of images in an applet

    I�m trying to create an "animation" by drawing images in an applet....
    ....any error appears when I run the applet, but any image is drawn.
    public class mail extends Applet implements Runnable {
          Image[] images = new Image[17];
         int frame = 0;
         volatile Thread thread;
         public void init() {
              setSize(600,400);
              for(int i=1; i<=16; i++)
                   images[i] = getImage(getDocumentBase(), "/images/cena"+i+".JPG");
         public void start() {
             (thread = new Thread(this)).start();
         public void stop() {
             thread = null;
         public void paint(Graphics g) {
             g.drawImage(images[frame], 0, 0, this);
         public void run() {
             int delay = 1000;   
             try {
                 while (thread == Thread.currentThread()) {
                      for(int j=1; j<=16; j++)
                           frame = j;
                           repaint();
                           Thread.sleep(delay);
             } catch (Exception e) {
    }

    ....any error appears when I run the applet, but Any error appears? Either you mean a sperific error, or no error?
    any image is drawn.Do you mean no image is draw? Or that images are drawn at random?
    // Guess one: caps, should the .JPG be lowercase?
    images[i] = getImage(getDocumentBase(),
    Base(), "/images/cena"+i+".JPG");
    public void run() {
    int delay = 1000;
    try {
    while (thread == Thread.currentThread())
    rentThread()) {
         for(int j=1; j<=16; j++)
              frame = j;
              repaint();
              Thread.sleep(delay);
    } catch (Exception e) {
    Your try catch has much larger scope than it should. It should just cover sleep, and only catch InterruptedException.

Maybe you are looking for

  • Unix Environment Variables

    I use EBS 11.5 and I am trying to use XML Publisher with RTF files for PO printing. I have a main script loaded into Oracle as the template and it uses <?import:file///home/dave/scripts/test.rtf?> to pull in a subtemplate. I want to change this to re

  • Difference b/w At-selection-screen and onfield

    Hi,      What is the difference between at-selection-screen and at-selction-onfield?

  • Can anyone send me link of IDOC gentn using change pointers!

    Hey guys I need to learn IDOC generation using change pointers.Please send me some help notes and link  and sample program on that !

  • When I undock my laptop, i can't use it. Welcome screen hangs

    any help appreciated. The computer works fine when its' on the docking station but when I undock it after I shutdown, I turn the computer on, and it gets hung up on the welcome screen. Just will sit there. I will reboot about 5 times or so and it may

  • Mac repair shop SE london

    Hi Can anyone recommend a good MAC repair place/person. I have a horrible feeling that things have gone a bit wrong on my Powerbook G4, I know there is an error on the Vram after running AHT. But now I can't get it to boot up.... any ideas and sugges