MediaTracker

I want to preload some images with the MediaTracker, total size of the images is 28 MB. I added all images to a MediaTracker object then called
waitForAll(). The Problem is that I always get the java.lang.OutOfMemory
error.
How can it be that the VM runs out of memory bacause of loading 28 MB pictures??
How can I avoid this error or how can I preload the pics a different way??
When I don't preload the screen flickers while displaying/loading the
image.
Thankx in advance.

java -Xmx128m MyProgram
gives a max amount of 128 mb of memory for your program.

Similar Messages

  • Mediatracker is not working in browser

    I want to load 2 JEPGs and show them in an applet. Therefore I'm using mediatracker to wait till all Images are loaded like in the following code. When I use the appletviewer everything is working fine, but when I upload the applet and view it with a browser it doesn't get through the waitForAll()... And so they don't appear on the screen at all...
    Why is that ? Does anyone know where the error is ?
    Thx
    Feleex
    Image backgr1,backgr2;
    backgr1 = getToolkit().getImage("SHHlinear.jpg");
    backgr2 = getToolkit().getImage("SHHcycle.jpg");
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(backgr1, 0);
    mt.addImage(backgr2, 0);
    try {
    mt.waitForAll();
    } catch (InterruptedException e) {}

    You can't use toolkit in applets. Use just getImage() instead of getToolkit().getImage()

  • How can I prevent the MediaTracker waitForID method from blocking?

    Hi everyone:
    I am writing an application that deals with various image file formats with the help of the JIMI package (available at http://java.sun.com/products/jimi/). Everything works fine except for the Targa format. When I generate an Image object as follows (url is a valid URL object):
    Image image = Jimi.getImage(url);
    ImageIcon icon = new ImageIcon(image);the program execution blocks at the second line above. I searched the ImageIcon source code for some clues, which led me to the following ImageIcon method (tracker is a MediaTracker object, a static property of ImageIcon):
    (01) protected void loadImage(Image image) {
    (02)   synchronized(tracker) {
    (03)     tracker.addImage(image, 0);
    (04)     try {
    (05)       tracker.waitForID(0, 0);
    (06)     } catch (InterruptedException e) {
    (07)       System.out.println("INTERRUPTED while loading Image");
    (08)     }
    (09)     loadStatus = tracker.statusID(0, false);
    (10)     tracker.removeImage(image, 0);
    (11)
    (12)     width = image.getWidth(imageObserver);
    (13)     height = image.getHeight(imageObserver);
    (14)   }
    (15) }The program blocks at line (05) above. I peeked into the MediaTracker class source code, which brought me to determine that the image loading process never finishes. The symptoms are as follows:
    (1) When I perform a c.checkImage(image, null) where c is some Component, I always get a result of 7, which translates to the following combination of ImageObserver constants:
    WIDTH | HEIGHT | PROPERTIESAs matter of fact, the dimensions are indeed determined correctly. However, when the loading process terminates, the checkImage result includes ALLBITS or FRAMEBITS in case of success, ABORT or ERROR in case of failure. None of these bits is ever turned on whenever I try to load a Targa image.
    (2) When I get to the MediaTracker source code, I see that when none of the four bytes above is set, the internal MediaTracker status has the MediaTracker.LOADING bit turned on (nothing abnormal here). And the waitForID method terminates precisely only when this bit is turned off!
    Logically, if the loading process fails for some reason, I should expect to get an error response so that I can go further in code execution. However, since the loading process never terminates, everything stays blocked at the waitForID method invocation.
    Is there an efficient way to detect such a hidden loading error without letting my program go into the waitForID endless loop? In other words, going back to the first two lines of code of this message, how could I detect that an Image loading process will not terminate before calling the ImageIcon constructor?
    Thanks in advance for any useful help...
    Jean-Fran�ois Morin

    Hi:
    I tried precisely your suggestion before posting my message to the forum yesterday. I just forgot to mention it... Maybe I was afraid of increasing my message length more and more...
    I already know that this solution prevents the MediaTracker from blocking. However...
    (1) If they reach a troublesome image (like a Targa), the users of my application might not be pleased by its freezing for 10 seconds. Actually, this image loading module is part of an architecture for database applications from which my development team and I produce applications for various customers. Images are used, in particular, in Oracle BLOB support.
    (2) If I use a smaller timeout delay, I have no guarantee that any image, whatever its length, will load properly (Targa excluded, of course). According to tests I performed yesterday, I am virtually sure that the 10-second delay will be busted very easily by pictures larger than 1 Mb. I cannot overlook this potential problem: an Oracle BLOB can contain up to 2 terabytes of data!
    On the other side, I don't want to focus too much the attention on the JIMI Targa import filter because I know that a revised version of the JIMI and JAI packages will be part of JDK 1.4. This is why I am trying to figure out what is happening in the MediaTracker and Toolkit classes, which are much more fundamental than the Jimi ones...
    Thanks anyway...
    Best regards,
    Jean-Fran�ois Morin

  • Loading GIFs, MediaTracker sometimes doesn't wait

    Hi,
    I'm trying to solve this problem for a long time without any success. In my applet I load gif images into Image class. GIFs are generated by servlet and than loaded by applet. I use MediaTracker and most of the time images are loaded without any problem. But sometimes MediaTracker just doesn't wait for image to load. It's like there is something wrong with those gifs, but IE can load them and I can open them with PSP and everything is ok.
    I even created a method that loads image file into an array and than create Image from byte array. Doesn't help.
    Here is my code:
    Image       img  = null;
    try
        URL     url  = new URL(name);
        byte[]  file = getFile(url.openStream());
        img  = Toolkit.getDefaultToolkit().createImage(file);
        //img = Toolkit.getDefaultToolkit().getImage(new URL(name));
        MediaTracker tracker = new MediaTracker(this);
        tracker.addImage(img,0);
        tracker.waitForID(0,1000);
        if(tracker.isErrorID(0)) { System.out.println("error");}
    catch (InterruptedException e) {System.out.println("loadImage-error"); }
    catch (MalformedURLException e){System.out.println("loadImage-error"); }
    catch (Exception e)            {System.out.println("loadImage-error"); }and getImage method:
    public byte[] getFile(InputStream in) throws IOException
         int    bytesRead;
         byte[] buffer = new byte[4096];
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
         while( (bytesRead = in.read(buffer,0,4096)) > 0 )
                   bos.write(buffer,0,bytesRead);
         bos.flush();
         bos.close();
         return bos.toByteArray();

    Mistery solved!
    There was indeed problem in creating gif image files. Sometimes. Bug was in the LZW compression algorithm that I downloaded from the internet. Grrrr.
    But be aware, bad images can be opened with IE or PSP, but fail to load by Java.
    Matjaz
    P.S. Needless to say, Duke Dolars are not offered anymore.

  • Mediatracker (waitforid) - null pointer exception

    Ok in the run event..
             try {
              if(CURLOAD<=47) {
              try {
              im[CURLOAD] = getImage(new URL(URLtoUse, LNKS[CURLOAD]));
              } catch(MalformedURLException e) {
                   System.out.println("Error loading images.");
                   s="Error loading images.";
              System.out.println("Curload: "+String.valueOf(CURLOAD));
              tracker.addImage(im[CURLOAD], CURLOAD);
              tracker.waitForID(CURLOAD);
              CURLOAD++;
              //tracker.waitForID(1);
             } catch (InterruptedException e) {
              return;
             }CURLOAD will be 0-47, but on 0 it it gives a null pointer exception on the line "tracker.waitForID(CURLOAD);" anyone know why? I thought I would assign a new mediatracker id for every image loaded.. but it doesn't feel like working :(

    tracker is my mediatracker, and waitForID is a built-in java function.. it waits until the image is done loading (or is supposed to)
    Edit: Solved by myself... forgot to set LNKS array
    Edited by: Dazappa on Apr 7, 2008 9:24 PM

  • Why to I have to specify a Component for MediaTracker?

    Hi,
    I've an application which loads some images. I use a MediaTracker to load the images.
    The problem is, that I've to specify a component when creating the MediaTracker.
    I tried to create a MediaTracker with
    new MediaTracker(null);
    but then I get a NullPointerException when I call .waitForID(0);
    So I create a MediaTracker like:
    new MediaTracker(new Panel());
    even tough I don't need the panel.
    Do I have to use this workaround to load the images? Or is there a smarter way of doing this??
    thx,
    dani

    ok here is my code, I use a JPanel to be able to use the MediaTracker
    Image img = Toolkit.getDefaultToolkit().createImage(imgURL);
    // load the image with media tracker class
    MediaTracker tracker = new MediaTracker(new Panel());
    tracker.addImage(img, 0);       
    tracker.waitForID(0);       
    // width and height of the course image
    w = img.getWidth(null);
    h = img.getHeight(null);
    System.out.println("w="+w+", h="+h);If I use this code, the image is loaded properly. If I try to take out the MediaTracker stuff then I get w=-1, h=-1.
    The imgURL is something like maps/something.gif. The directory where the "maps/xyz.gif"'s are located is in the classpath.
    thx
    dani

  • MediaTracker and IE 5.0

    I I have a problem:
    I use a MediaTracker to load an Image and display it in my applet. This works well on most Computers and most clients. But one IE : version 5.00.23 doesnt load the Image, means it is not displayed.
    I called isErrorAny from MediaTracker and it returned that there are errors.
    How can I see which errors occured or is there a known problem with this IE version?
    thanks
    Noel

    To see what's going on in the virtual machine you can check "enable java console" in the internet options>advanced. Then you can bring up the console in the view menu (I think). See if the virtual machine throws a NoSuchMethodError. If it does, it's all microsofts fault, as usual. (IE5 uses java 1.1.4, can you believe it?!)

  • NullPointerException at inheriting class with that has no MediaTracker ???

    Hello everybody!
    I have a very very strange problem and I am not able to understand and solve it..
    This is it: I wrote two classes that inherit "scene" from the same superclass and are supposed to display an Icon and a button (They are MHP-Applications, but i guess it is more a java than a mhp problem, that's why I am posting to this forum..). The Icon class has a mediaTracker in it and works fine but the button class (with no mediaTracker) throws a NullPointerException when trying to access "scene" from the superclass. Why?? Has it something to do with the MediaTracker? I also found out that my icon class won't work too, when programming it without a Thread..Does anybody has an idea what is a possible reason for that?
    The Icon class works well and is as follows:
    public class Icon extends Scene implements Runnable{
    public Icon() {
    myWorkerThread = new Thread(this);
    myWorkerThread.start();
    public void display() {
    MediaTracker tracker = new MediaTracker(this);
    pic = Toolkit.getDefaultToolkit().getImage("AlphaGrafik.png");
    tracker.addImage(pic, 0);
    try{
    tracker.waitForAll();
    catch(InterruptedException e) {
    hContainer1 = new HContainer(0,0,720,576);
    icon = new HStaticIcon(pic, 0, 0, 720, 576);
    hContainer1.add(icon);
    //INHERITED FROM SUPERCLASS
    scene.add(hContainer1);
    scene.setVisible(true);
    public void run() {
    display();
    This is my Button Class which throws the NullPointer:
    public class MHPTest_1 extends Szene implements Runnable{
    private Thread myWorkerThread;
    private HContainer hContainer1;
    private HTextButton button;
    private Image pic;
    public MHPTest_1() {
    myWorkerThread = new Thread(this);
    myWorkerThread.start();
    public void display(){
    hContainer1 = new HContainer(0,0,720,576);
    button = new HTextButton();
    button.setBounds(70, 80, 100, 50);
    hContainer1.add(button);
    //HERE I GET THE NULLPOINTEREXCEPTION!!!
    scene.add(hContainer1);
    scene.setVisible(true);
    public void run() {
    display();
    Any help is very useful for me!
    Thanks in advance,
    with best regards,
    Alex.

    Ups, yes it's a typo..
    scene comes from the superclass Scene and is instantiated in a method there by
    createScene(){
    scene=factory.getBestScene(hst);
    I solved it but now i have another problem with that "solution" which actually isn't one:
    when i add
    createScene();
    to my Button Class and my Icon class,
    they will work.
    but if i want to add both my button class and my Icon class to my Superclass,
    i create two instances of "scene", what is not allowed (it is a Digital TV App where only one instance of scene works..).
    What's surprising here:
    Sometimes it works with the IRT RI, sometimes it won't ???
    What could be possible reasons for that?
    I really need to add more like one Components (e.g. an Icon AND a button) to my scene instance, without creating two of them..
    Do you have an idea of how to solve that?
    As you see, i wasn't able to handle this yet ;-(

  • NullPointerException with MediaTracker

    So the class (which has another small class in it for the sake of easier linking) is giving me a null pointer exception in the console window when i try to run it. The class is intended to create a scrolling background that wraps around. It works fine by itself, having real difficulties getting it into the larger project.
    Thanks a TON for any help in advance:
    import java.io.*;
    import java.net.URL;
    import java.applet.*;
    import java.awt.image.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Draw extends Canvas
         char s;
         private BufferedImage biBackground = null;
         private Toolkit tk;
         private JFrame f;
        public Draw()
              tk = Toolkit.getDefaultToolkit();
              loadBackground("Still1.gif");
              f = new JFrame("AniDemo 1.0");
              myPanel p = new myPanel(biBackground);
              f.add(p);
             f.pack();
             f.setVisible(true);
            private void loadBackground(String fn)
             Image im = tk.getImage(fn);
             MediaTracker mt = new MediaTracker(f);
             mt.addImage(im, 0);
              try
                   mt.waitForID(0);
                   biBackground = new BufferedImage(800, 550, BufferedImage.TYPE_INT_RGB);
                   Graphics2D g2 = biBackground.createGraphics();
                   g2.drawImage(im, 0, 0, null);
                   g2.dispose();
              catch(InterruptedException e)
                   System.out.println(e.toString());
         class myPanel extends JPanel implements ActionListener
              private BufferedImage background;
              private BufferedImage bi = null;
              private int upperLeft = 0;
              int width;
              int height;
              public myPanel(BufferedImage bg)
                   super();
                   background = bg;
                   width = background.getWidth()/2;
                   height = background.getHeight();
                   bi = background.getSubimage(upperLeft,0,width,height);
                   setPreferredSize(new Dimension(width, height));
                   Timer t = new Timer(100, this);
                   t.start();
              public void actionPerformed(ActionEvent e)
                   upperLeft += 1;
                   if(upperLeft >= width)
                        upperLeft = 0;
                   bi = background.getSubimage(upperLeft,0,width,height);
                   repaint();
              public void paintComponent(Graphics g)
                   g.drawImage(bi, 0, 0, this);
    }

    loadBackground("Still1.gif";);
    f = new JFrame("AniDemo 1.0";); Notice that the frame is created after the call to loadBackground. So when this statement is called
    MediaTracker mt = new MediaTracker(f); f is null, resulting in a null pointer exception. But since all you're doing is drawing the image onto a BufferedImage, you might as well skip the Toolkit and MediaTracker entirely and use javax.swing.ImageIO.read(...).
    Some other anomalies:
    public class Draw extends Canvas
    class myPanel extends JPanel implements ActionListener Your potentially combining AWT and SWING. And "myPanel" is mislabeld. Should be "MyPanel"
    mt.addImage(im, 0);
    g2 = biBackground.createGraphics();
    g2.drawImage(im, 0, 0, null);
    g2.dispose();
    ... You don't flush the toolkit image, via im.flush(), after you're done with it and ready to discard it.
    public void paintComponent(Graphics g)
        g.drawImage(bi, 0, 0, this);
    } Unless your BufferedImage is guaranteed to fill the entire size of the panel, you're violating the opacity property of the panel. You need include a super.paintComponent(g) call or insert setOpaque(false) in the constructor.
    f = new JFrame("AniDemo 1.0";);
    myPanel p = new myPanel(biBackground);
    f.add(p);
    f.pack();
    f.setVisible(true); You are not actually using your Draw class as a Canvas component. So why extend Canvas?
    try {
        mt.waitForID(0);
        biBackground = new BufferedImage(800, 550, BufferedImage.TYPE_INT_RGB);
    }catch(InterruptedException e){
        System.out.println(e.toString());
    } If an InterruptedException is actually thrown, your "biBackground" variable will be null resulting in null pointer exceptions later in your code.

  • MediaTracker ... Image Flicks & Image Ghosts

    - Applet went well all times with computer A but not computer B
    - Computer B however is OK with any other applets
    When Computer B called the applet, the applet downloaded and went well. But when I scrolled up & down the screen ... the images lost its shape and with "long tail ghosts". When I refreshed the screen, the images displayed well again. Everytime I scrolled up & down the screen, I have to do this exercise.
    QUESTIONS:
    - Is it I did not code it right with MediaTracker?
    - More, even with Computer A, the first time the applet and images downloaded, the screen will flick every time an image arrives ... is it Double Buffering will solve the problem ... how to implement Double Buffering with my codes?
    Much appreciated for any idea ...
    SOURCE:
    import java.applet.*;
    import java.awt.Image;
    import java.awt.Graphics;
    import java.awt.MediaTracker;
    public class BackgroundImage extends Applet {
    MediaTracker tracker;
    Image background;
    Image family;
    Image mailbox;
    Image cat[] = new Image[7];
    public void init() {
    tracker = new MediaTracker(this);
    background = getImage(getDocumentBase(),"images/background.jpg");
    family = getImage(getDocumentBase(),"images/family.gif");
    mailbox = getImage(getDocumentBase(),"images/mailbox.gif");
    tracker.addImage(background,0);
    tracker.addImage(family,1);
    tracker.addImage(mailbox,2);
    for(int i=0,y=3; i<cat.length; i++,y++) {
    cat[i] = getImage(getDocumentBase(),"images/cat"+i+".gif");
    tracker.addImage(cat,y);
    public void paint(Graphics g) {
    g.drawImage(background,0,0,this);
    g.drawImage(family,8,493,this);
    g.drawImage(mailbox,8,403,this);
    for(int i=0,x=20,y=152,z=-4; i<cat.length; i++) {
    g.drawImage(cat[i],x,y,this);
    x+=(30+z);
    y+=60;
    z=(int)(z*1.5);

    Last source copy & paste was corrupted ... here it comes again (last post Sun's upload window turned my cat[i] to cat only ... and the codes following the cat turned to italic!)
    SOURCE:
    import java.applet.*;
    import java.awt.Image;
    import java.awt.Graphics;
    import java.awt.MediaTracker;
    public class BackgroundImage extends Applet {
    MediaTracker tracker;
    Image background;
    Image family;
    Image mailbox;
    Image cat[] = new Image[7];
    public void init() {
    tracker = new MediaTracker(this);
    background = getImage(getDocumentBase(),"images/background.jpg");
    family = getImage(getDocumentBase(),"images/family.gif");
    mailbox = getImage(getDocumentBase(),"images/mailbox.gif");
    tracker.addImage(background,0);
    tracker.addImage(family,1);
    tracker.addImage(mailbox,2);
    for(int i=0,y=3; i<cat.length; i++,y++) {
    cat[i] = getImage(getDocumentBase(),"images/cat"+i+".gif");
    tracker.addImage(cat,y);
    public void paint(Graphics g) {
    g.drawImage(background,0,0,this);
    g.drawImage(family,8,493,this);
    g.drawImage(mailbox,8,403,this);
    for(int i=0,x=20,y=152,z=-4; i<cat.length; i++) {
    g.drawImage(cat[i],x,y,this);
    x+=(30+z);
    y+=60;
    z=(int)(z*1.5);

  • ImageIcon vs MediaTracker

    I need some advice from the experts out there
    which is a better way to get images from a file on the hard drive into an image object?
    Image m = new ImageIcon("Blah.gif");
    or
    using a mediatracker and default toolkit and all that
    i've had problems with low end machines (pentium 133, 32 megs of ram) failing to load images when using the the media tracker method. (works fine on decent machines)
    would switching to the imageIcon method work better?
    thanks

    I think you can use the toolkit to load images, but I think it all comes down to the same thing. MediaTracker is probably pretty close to your best bet.

  • Image.getWidth(null) and image..getHeight(null)  returns -1

    Hi ,
    Plz tell me whats wrong with code
    import java.awt.Image;
    import java.awt.Toolkit;
    public class ImgSize {
        public static void main(String args[]) {
            Image image = Toolkit.getDefaultToolkit().getImage("Picture.jpg");
            double width = image.getWidth(null);
            double height = image.getHeight(null);
            System.out.println("width :" + width + "-- height :" + height);
            getImageDimesion("Picture.jpg");
        public static void getImageDimesion(String abc) {
            Image image = Toolkit.getDefaultToolkit().getImage(abc);
            double width = image.getWidth(null);
            double height = image.getHeight(null);
            System.out.println("width :" + width + "-- height :" + height);
    }output:
    width :-1.0-- height :-1.0
    width :2592.0-- height :1944.0
    There is no difference in main function getWidth/ getHeight and function getImageDimension getWidth/ getHeight
    If u remove getWidth and getHeigth in the main function i.e comment the 1st four lines in main function then the output is
    Output
    width :-1.0-- height :-1.0
    Plz help in understanding this.
    Thanks
    Venkat

    Toolkit images are not loaded until they are first drawn or you request a property from it (such as getWidth). To force the image to load and wait for it to finish loading, you can use the MediaTracker class. The ImageIcon class has one built in.
    Image image = Toolkit.getDefaultToolkit().getImage("Picture.jpg");
    new ImageIcon(image); //loads the image

  • Animated GIF frame loss

    I have an applet that has a JPanel with a JLabel in it. That JLabel was created with an ImageIcon constructor with an animated gif image. The gif has eleven frames (each with replace set) and is set to loop. When I bring up the applet the image animates through the first 7 frames then stops. I can File/Open the gif in Netscape and it looks fine - animates all images and loops. Looking at it with:
    setDebugGraphicsOptions(DebugGraphics.BUFFERED_OPTION); or FLASH_OPTION
    it looks good until that 7th frame then I start to see flash of grey the size of the JLabel.
    I understand that the ImageObserver defaults to the JLabel. But I have tried directly setting it with no joy. I have also tried calling .flush() on the image with no joy. So I tried a different animated gif and it stopped on the 3rd frame (but also appears fine in a browser).
    I am on day 2 of trying to figure this out (pulling my hair out).
    I cut this down quite a bit, so there may be syntax errors.
    public class RRR extends JApplet implements RRRConsts
    public void init()
    loadImages();
    myJPanel = new MyJPanel();
    contentPane.add(myJPael);
    private void loadImages()
    try
    problemImage = loadImage(new URL(getDocumentBase(),
    "problem.gif"));
    catch (Exception e)
    { logger.log(Level.SEVERE, "Unable to load images", e); }
    private Image loadImage(URL url) throws InterruptedException
    Image image = getImage(url);
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(image, 0);
    tracker.waitForID(0);
    return image;
    MyJPanel myJPanel = null;
    static Image problemImage = null;
    class MyJPanel extends JPanel implements RRRConsts
    MyJPanel()
    setLayout(null);
    setBounds(0,0,468,540);
    setOpaque(false);
    buildUI();
    private void buildUI()
    myLabel = new MyLabel();
    add(myLabel);
    private MyLabel myLabel = null;
    class MyLabel extends JLabel implements RRRConsts, ActionListener
    MyLabel()
    super(new ImageIcon(RRR.problemImage));
    }

    I just had the same problem. It seems that when using an animated gif as ImageIcon it will not be loaded compeltly if it is too large. The maximum seems to be somewhere between 60 - 70 KB.
    I managed to use a higher compression on my gifs to make them smaller, but I haven't found any general solution yet.

  • How can I create a single background image for a BorderLayout?

    I can create a background with an image file for the individual panel (North, West, Center, East and South) in a BorderLayout, but I've been spinning my wheel for a long while now trying to figure out how to create just one background with a single image file for all of these panels?
    In my application, a panel may contain various buttons, a listbox, a group of checkboxes, a combo box, or a canvas. Even if I used the same image file, when the panels are finally put together, one can clearly see that the end product is the result of a lot of patch works.
    Hope someone has an answer for this. BTW, I'm using AWT because it works with existing browsers without the need for a separate Java plug-in.
    Regards,
    V.V.

    Look at this :
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.awt.image.BufferedImage;
    public class PanI extends Frame
         Image map;
         Panel pan;
         myPan p8,p4,p6,p2,p5;
         BufferedImage I;
    public PanI() 
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         map = getToolkit().getImage("map2.gif");
         MediaTracker tracker = new MediaTracker(this);
         tracker.addImage(map,0);
         try   {tracker.waitForID(0);}
         catch (InterruptedException e){}
         I = new BufferedImage(1,1,BufferedImage.TYPE_INT_ARGB);
         setBounds(10,10,map.getWidth(null)+8,map.getHeight(null)+27);
         setLayout(new BorderLayout());
         pan = new Panel();
         add(pan,BorderLayout.CENTER);
         pan.setLayout(new BorderLayout());
         pan.setSize(map.getWidth(null),map.getHeight(null));
         p5 = new myPan(5);
         p5.setBackground(Color.red);
         pan.add(p5,BorderLayout.CENTER);
         p8 = new myPan(8);
         p8.setBackground(Color.orange);
         pan.add(p8,BorderLayout.NORTH);
         p4 = new myPan(4);
         p4.setBackground(Color.blue);
         pan.add(p4,BorderLayout.WEST);
         p6 = new myPan(6);
         p6.setBackground(Color.green);
         pan.add(p6,BorderLayout.EAST);
         p2 = new myPan(2);
         p2.setBackground(Color.pink);
         pan.add(p2,BorderLayout.SOUTH);
         setVisible(true);
    public class myPan extends Panel
         int where;
    public myPan(int i)
         super();
         where = i;
    public void paint(Graphics g)
         if (I.getWidth(null) != pan.getWidth() || I.getHeight(null) != pan.getHeight())
              I = new BufferedImage(pan.getWidth(),pan.getHeight(),BufferedImage.TYPE_INT_ARGB);
              Graphics      G = I.getGraphics();
              G.drawImage(map,0,0,pan.getWidth(),pan.getHeight(),null);     
              G.dispose();
         int x1=0;
         int x2=getWidth();
         int y1=0;
         int y2=getHeight();
         if (where == 8)
         if (where == 2)
              y1 =  p8.getHeight()+p5.getHeight();
              y2 =  getHeight()+y1;
         if (where == 4)
              y1 =  p8.getHeight();
              y2 =  y1+getHeight();
         if (where == 5)
              x1 =  p4.getWidth();
              x2 =  x1+getWidth();
              y1 =  p8.getHeight();
              y2 =  y1+getHeight();
         if (where == 6)
              x1 =  p4.getWidth()+p5.getWidth();;
              x2 =  x1+getWidth();
              y1 =  p8.getHeight();
              y2 =  y1+getHeight();
         g.drawImage(I,0,0,getWidth(),getHeight(),x1,y1,x2,y2,null);
    public void update(Graphics g)
         paint(g);
    public static void main (String[] args) 
         new PanI();
    Noah

  • How can I repeat a for loop, once it's terms has been fulfilled???

    Well.. I've posted 2 different exceptions about this game today, but I managed to fix them all by myself, but now I'm facing another problem, which is NOT an error, but just a regular question.. HOW CAN I REPEAT A FOR LOOP ONCE IT HAS FULFILLED IT'S TERMS OF RUNNING?!
    I've been trying many different things, AND, the 'continue' statement too, and I honestly think that what it takes IS a continue statement, BUT I don't know how to use it so that it does what I want it too.. -.-'
    Anyway.. Enought chit-chat. I have a nice functional game running that maximum allows 3 apples in the air in the same time.. But now my question is: How can I make it create 3 more appels once the 3 first onces has either been catched or fallen out the screen..?
    Here's my COMPLETE sourcecode, so if you know just a little bit of Java you should be able to figure it out, and hopefully you'll be able to tell me what to do now, to make it repeat my for loop:
    Main.java:
    import java.applet.*;
    import java.awt.*;
    @SuppressWarnings("serial")
    public class Main extends Applet implements Runnable
         private Image buffering_image;
         private Graphics buffering_graphics;
         private int max_apples = 3;
         private int score = 0;
         private GameObject player;
         private GameObject[] apple = new GameObject[max_apples];
         private boolean move_left = false;
         private boolean move_right = false;
        public void init()
            load_content();
            setBackground(Color.BLACK);
         public void run()
              while(true)
                   if(move_left)
                        player.player_x -= player.movement_speed;
                   else if(move_right)
                        player.player_x += player.movement_speed;
                   for(int i = 0; i < max_apples; i++)
                       apple.apple_y += apple[i].falling_speed;
                   repaint();
                   prevent();
                   collision();
              try
              Thread.sleep(20);
              catch(InterruptedException ie)
              System.out.println(ie);
         private void prevent()
              if(player.player_x <= 0)
              player.player_x = 0;     
              else if(player.player_x >= 925)
              player.player_x = 925;     
         private void load_content()
         MediaTracker media = new MediaTracker(this);
         player = new GameObject(getImage(getCodeBase(), "Sprites/player.gif"));
         media.addImage(player.sprite, 0);
         for(int i = 0; i < max_apples; i++)
         apple[i] = new GameObject(getImage(getCodeBase(), "Sprites/apple.jpg"));
         try
         media.waitForAll();     
         catch(Exception e)
              System.out.println(e);
         public boolean collision()
              for(int i = 0; i < max_apples; i++)
              Rectangle apple_rect = new Rectangle(apple[i].apple_x, apple[i].apple_y,
    apple[i].sprite.getWidth(this),
    apple[i].sprite.getHeight(this));
              Rectangle player_rect = new Rectangle(player.player_x, player.player_y,
    player.sprite.getWidth(this),
    player.sprite.getHeight(this));
              if(apple_rect.intersects(player_rect))
                   if(apple[i].alive)
                   score++;
                   apple[i].alive = false;
                   if(!apple[i].alive)
                   apple[i].alive = false;     
         return true;
    public void update(Graphics g)
    if(buffering_image == null)
    buffering_image = createImage(getSize().width, getSize().height);
    buffering_graphics = buffering_image.getGraphics();
    buffering_graphics.setColor(getBackground());
    buffering_graphics.fillRect(0, 0, getSize().width, getSize().height);
    buffering_graphics.setColor(getForeground());
    paint(buffering_graphics);
    g.drawImage(buffering_image, 0, 0, this);
    public boolean keyDown(Event e, int i)
         i = e.key;
    if(i == 1006)
    move_left = true;
    else if(i == 1007)
         move_right = true;
              return true;     
    public boolean keyUp(Event e, int i)
         i = e.key;
    if(i == 1006)
    move_left = false;
    else if(i == 1007)
         move_right = false;
    return true;
    public void paint(Graphics g)
    g.drawImage(player.sprite, player.player_x, player.player_y, this);
    for(int i = 0; i < max_apples; i++)
         if(apple[i].alive)
              g.drawImage(apple[i].sprite, apple[i].apple_x, apple[i].apple_y, this);
    g.setColor(Color.RED);
    g.drawString("Score: " + score, 425, 100);
    public void start()
    Thread thread = new Thread(this);
    thread.start();
    @SuppressWarnings("deprecation")
         public void stop()
         Thread thread = new Thread(this);
    thread.stop();
    GameObject.java:import java.awt.*;
    import java.util.*;
    public class GameObject
    public Image sprite;
    public Random random = new Random();
    public int player_x;
    public int player_y;
    public int movement_speed = 15;
    public int falling_speed;
    public int apple_x;
    public int apple_y;
    public boolean alive;
    public GameObject(Image loaded_image)
         player_x = 425;
         player_y = 725;
         sprite = loaded_image;
         falling_speed = random.nextInt(10) + 1;
         apple_x = random.nextInt(920) + 1;
         apple_y = random.nextInt(100) + 1;
         alive = true;
    And now all I need is you to answer my question! =)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    package forums;
    import java.util.Random;
    import javax.swing.Timer;
    import javax.imageio.ImageIO;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class VimsiesRetardedAppleGamePanel extends JPanel implements KeyListener
      private static final long serialVersionUID = 1L;
      private static final int WIDTH = 800;
      private static final int HEIGHT = 600;
      private static final int MAX_APPLES = 3;
      private static final Random RANDOM = new Random();
      private int score = 0;
      private Player player;
      private Apple[] apples = new Apple[MAX_APPLES];
      private boolean moveLeft = false;
      private boolean moveRight = false;
      abstract class Sprite
        public final Image image;
        public int x;
        public int y;
        public boolean isAlive = true;
        public Sprite(String imageFilename, int x, int y) {
          try {
            this.image = ImageIO.read(new File(imageFilename));
          } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Bailing out: Can't load images!");
          this.x = x;
          this.y = y;
          this.isAlive = true;
        public Rectangle getRectangle() {
          return new Rectangle(x, y, image.getWidth(null), image.getHeight(null));
      class Player extends Sprite
        public static final int SPEED = 15;
        public Player() {
          super("C:/Java/home/src/images/player.jpg", WIDTH/2, 0);
          y = HEIGHT-image.getHeight(null)-30;
      class Apple extends Sprite
        public int fallingSpeed;
        public Apple() {
          super("C:/Java/home/src/images/apple.jpg", 0, 0);
          reset();
        public void reset() {
          this.x = RANDOM.nextInt(WIDTH-image.getWidth(null));
          this.y = RANDOM.nextInt(300);
          this.fallingSpeed = RANDOM.nextInt(8) + 3;
          this.isAlive = true;
      private final Timer timer = new Timer(200,
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            repaint();
      public VimsiesRetardedAppleGamePanel() {
        this.player = new Player();
        for(int i=0; i<MAX_APPLES; i++) {
          apples[i] = new Apple();
        setBackground(Color.BLACK);
        setFocusable(true); // required to generate key listener events.
        addKeyListener(this);
        timer.setInitialDelay(1000);
        timer.start();
      public void keyPressed(KeyEvent e)  {
        if (e.getKeyCode() == e.VK_LEFT) {
          moveLeft = true;
          moveRight = false;
        } else if (e.getKeyCode() == e.VK_RIGHT) {
          moveRight = true;
          moveLeft = false;
      public void keyReleased(KeyEvent e) {
        moveRight = false;
        moveLeft = false;
      public void keyTyped(KeyEvent e) {
        // do nothing
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        //System.err.println("DEBUG: moveLeft="+moveLeft+", moveRight="+moveRight);
        if ( moveLeft ) {
          player.x -= player.SPEED;
          if (player.x < 0) {
            player.x = 0;
        } else if ( moveRight ) {
          player.x += player.SPEED;
          if (player.x > getWidth()) {
            player.x = getWidth();
        //System.err.println("DEBUG: player.x="+player.x);
        Rectangle playerRect = player.getRectangle();
        for ( Apple apple : apples ) {
          apple.y += apple.fallingSpeed;
          Rectangle appleRect = apple.getRectangle();
          if ( appleRect.intersects(playerRect) ) {
            if ( apple.isAlive ) {
              score++;
              apple.isAlive = false;
        g.drawImage(player.image, player.x, player.y, this);
        for( Apple apple : apples ) {
          if ( apple.isAlive ) {
            g.drawImage(apple.image, apple.x, apple.y, this);
        g.setColor(Color.RED);
        g.drawString("Score: " + score, WIDTH/2-30, 10);
      private static void createAndShowGUI() {
        JFrame frame = new JFrame("Vimsies Retarded Apple Game");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new VimsiesRetardedAppleGamePanel());
        frame.pack();
        frame.setSize(WIDTH, HEIGHT);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args) {
        SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              createAndShowGUI();
    }Hey Vimsie, try resetting a dead apple and see what happens.

Maybe you are looking for

  • How to Change the Font Size in Module Pool Selection Screen?

    Hi, There is a module pool, and I need to change the font size mentioned in the selection screen. Could you plaese tell me, how will I be able to do that?

  • Instructor's Solutions Manual

    The Instructor Solutions manual is available in PDF format for the following textbooks. These manuals include full solutions to all problems and exercises with which chapters ended, but please DO NOT POST HERE, instead send an email with details; tit

  • Delete vendor based on Company code

    Hi all, I am working in EBP 3.5 with SAP R/3 4.7 version in classic scenario. I am looking for deletion of vendors based on specific company code in EBP system. Pointers or solutions will be highly appreciated and awarded. Regards Dinesh singh

  • Entity Object validation for "Date" type

    I am trying to use the Entity Object validation for a Date field type, it is a required field. I am using the format: MM/dd/yy HH:mm:ss It is a simple validation where the date value must be less than or equal to the current date/time. I tried using

  • Simple FLV Listener Error

    Hi, I have a Flash 8 movie that has two frames. In the first is a picture of a TV and a click here button. When you click the button it goes to frame 2 what has a FLVPlayer move (I just imported the FLV file, no coding and called it "Commercial") and