Images in an applet

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class CardDeck5 extends Applet implements ActionListener
{//start class CardDeck3
private CardLayout cardLayout;
private Panel main,crd1,crd2,crd3,crd4,crd5,p,card;
private Button first,second,third,fourth,fifth,sixth;
private Image image1,image2,image3,image4,image5,image6,image7,image8;
static int typeImage=0;
public void init()
{     //start void init
Image image1=getImage(getDocumentBase(),"chi2.gif");
     /*image2=getImage(getDocumentBase(),"Frog.gif"); //establish variables for images
     image3=getImage(getDocumentBase(),"Cryn_syf.gif");
     image4=getImage(getDocumentBase(),"Cnitemid.gif");
     image5=getImage(getDocumentBase(),"aoxom.gif");
     image6=getImage(getDocumentBase(),"stealy.gif");
     image7=getImage(getDocumentBase(),"lake_tahoe_ban.gif");
     image8=getImage(getDocumentBase(), "mykistys.jpg");*/
     prepareImage(image1, this);
     /*prepareImage(image2, this);
     prepareImage(image3, this);
     prepareImage(image4, this);
     prepareImage(image5, this);
     prepareImage(image6, this);
     prepareImage(image7, this);
prepareImage(image8, this);*/
setLayout(new BorderLayout());     //set layout
card = new Panel();                                   //est main panel
     card.setSize(500,500);
cardLayout = new CardLayout();     //est card layout
card.setLayout(cardLayout);          //put cardlayout on panel
add("Center", card);
/*first card*/
Picture Pic1=new Picture();                    //create Pic1 of type Picture
Pic1.setSize(400,400);               //set size of panel
crd1=new Panel();                    // Pic1 to panel crd1
crd1.add(Pic1);                     //add Pic 1 to panel crd1
card.add(crd1,"1");               //add crd1 to main panel
/*second card*/
Picture Pic2=new Picture();
     Pic2.setSize(400,400);
crd2=new Panel();
crd2.add(Pic2);
card.add(crd2,"2");
/*third card*/
     Picture Pic3=new Picture();
     Pic3.setSize(400,400);
crd3=new Panel();
crd3.add(Pic3);
card.add(crd3,"3");
/*fourth panel*/
Picture Pic4=new Picture();
     Pic4.setSize(400,400);
     crd4=new Panel();
     crd4.add(Pic4);
card.add(crd4,"4");
/*fifth panel*/
Picture Pic5=new Picture();
Pic5.setSize(400,400);
crd5=new Panel();
crd5.add(Pic5);
card.add(crd5,"5");
Panel p = new Panel();
p.setLayout(new GridLayout(1,3));
first=new Button("Image1");
first.addActionListener(this);
p.add(first);
second=new Button("Image2");
second.addActionListener(this);
p.add(second);
third=new Button("Image3");
third.addActionListener(this);
p.add(third);
fourth=new Button("Image4");
fourth.addActionListener(this);
p.add(fourth);
add( card, BorderLayout.CENTER);               //put card panel in center
add(p,BorderLayout.SOUTH);                         //add button panel to south border
} //end constructor
public void actionPerformed(ActionEvent e)
Object source=e.getSource();
if (source == first)
cardLayout.show(card,"2");
          typeImage=1;
          card.repaint();
          //System.out.println("typeimage in ap "+ typeImage);
if (source== second)
cardLayout.show(card,"3");
     typeImage=2;
     card.repaint();
     // System.out.println("typeimage in ap "+ typeImage);
if (source == third)
          cardLayout.show(card,"4");
          typeImage=3;
          card.repaint();
          //System.out.println("typeimage in ap "+ typeImage);
if (source == fourth)
          cardLayout.show(card,"5");
          typeImage=5;
          card.repaint();
          //System.out.println("typeimage in ap "+ typeImage);
}//end action performed
class Picture extends Canvas
{  //picture start
protected void showImage(Graphics g, int x, int y, Image image,
          String loadingMessage, String errorMessage)
          // Get the status of the image
          int flags = checkImage(image, this);
          // If the image aborted or had an error, print the error message
          if ((flags & (ImageObserver.ABORT+ImageObserver.ERROR)) != 0)
          g.drawString(errorMessage, x, y+30);
          return;
          // If the image has been loaded fully, display it
          } else if ((flags & ImageObserver.ALLBITS) != 0) {
          g.drawImage(image, x, y, this);
          // If the image is still loading, display the loading message
          } else {
          g.drawString(loadingMessage, x, y+30);
          return;
     public void paint (Graphics g )
     {      //begin paint
g.drawRect(0,0,400,400);
showImage(g,0,0,image8,"image loading","image can't load");
showImage(g,40,0,image7,"image loading","image can't load");
switch(typeImage)
          case 1:
               //System.out.println("typeimage in paint after switch" +typeImage);
               showImage(g,100,100,image1,"image loading","image can't load");
               break;
     case 2:
               //System.out.println("typeimage in paint after switch" +typeImage);
               g.drawString("We miss you!",100,100);
               showImage(g,90,90,image2,"image loading","image can't load");
break;
          case 3:
                    //System.out.println("typeimage in paint after switch" +typeImage);             //begin else if
g.drawString("Its crying time",150,100);
                    showImage(g,100,150,image3,"image loading","image can't load");
break;
          case 4:
//System.out.println("typeimage in paint after switch" +typeImage);
                                   showImage(g,130,75,image6,"image loading","image can't load");
break;
     case 5:
                    //System.out.println("typeimage in paint after switch" +typeImage);
g.drawString(" Album cover from Aoxomoxa",150,230);
                         showImage(g,130,75,image5,"image loading", "image can't load");
break;
}//end switch
     } //end paint
}          //end class picture
} //end class CardDeck1
when I compile the previous applet(that use to work under previous version) I get the following errors
D:\data\CardDeck5.java:16: incompatible types
found : java.awt.Image
required: Image
image1=getImage(getDocumentBase(),"chi2.gif");
^
D:\data\CardDeck5.java:25: cannot resolve symbol
symbol : method prepareImage (Image,CardDeck5)
location: class CardDeck5
     prepareImage(image1, this);
^
D:\data\CardDeck5.java:154: cannot resolve symbol
symbol : method checkImage (Image,CardDeck5.Picture)
location: class CardDeck5.Picture
          int flags = checkImage(image, this);
^
D:\data\CardDeck5.java:157: cannot resolve symbol
symbol : variable ImageObserver
location: class CardDeck5.Picture
          if ((flags & (ImageObserver.ABORT+ImageObserver.ERROR)) != 0)
^
D:\data\CardDeck5.java:157: cannot resolve symbol
symbol : variable ImageObserver
location: class CardDeck5.Picture
          if ((flags & (ImageObserver.ABORT+ImageObserver.ERROR)) != 0)
^

try to fix the errors your self beware with the datatypes, about the pictures, they are stored in the "server side" and applets run on the "client side" and applets have restricted acces to server resources...

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

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

  • 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

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

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

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

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

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

  • Removing Images From an Applet

    Is it possible to remove an image from an applet? For example, if you click on an image, it is deleted permanently.
    Thanks,
    gigabit

    Yes, sorry. I phrased it poorly.
    I have multiple images on my applet, however. I only
    want to make certain images no longer visible to the
    image. Is it possible to specify which images you
    want to hide?Just don't draw them.
    Not being able to select which pictures are to be painted and which aren't hint at a design flaw of your program's. Have a list of pictures and booleans whether they are to be shown. Run through the list and draw each picture as needed. Or skip the booleans and simply remove the reference to the image from the list.

  • 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

Maybe you are looking for

  • Automatic Downloads and Song Order

    Hi, I have automatic downloads enabled on my iPhone 4 so songs I buy on my computer are automatically synced with the phone over the air right after I buy them.  Great feature. Here's the problem: when I buy a song on my computer, it puts it at the t

  • SAPGUI through portal

    Hi Guys, I am very new to portal, I want to get separate sapgui window through portal, we can get it by clicking on plant management but that is embedded,  I need the same separately. I have gone through some search and created iview with the help of

  • Validation of profit center for MIGO transaction

    Hi! For MIGO transaction I want to restrict users of one profit center to post for another profit center. I have tried it with GGB0 , OB28 as well as OKC7 but i was unable to do it. please help me out with details. thanks Amit

  • Leading & Non Leading Issue

    Dear Experts, Can you pleases help me understand the concept of Sub Ledgers. We have 2 Co codes . One is of country US the co code is (US01) & another is of India (IN01) US01 Co Code is using leading Ledger. & IN01 is using non leading leader (L4) In

  • Animation in Forms 6i (like Flash)

    Please anybody can help me. How to embed animation in forms 6i. like (forms 6i). pls give me complete coding or detail bcaz i am new guy in Oracle. If answer is ActiveX or OLE . please explain how to use them. Muhammad Faisal