We help IT Professionals succeed at work.

magic

hateli
hateli asked
on
Medium Priority
306 Views
Last Modified: 2010-03-30
JDK 1.1
win 95 platform

i want to move a image containg ball from up to down .
it should come down as soon as i press space bar .
and similarly i want to randomly generate balls from
up to down in a 200 pixels width area. and i want to store
current x and current y co-ordinates . what should i do ?
Comment
Watch Question

Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Ya i have tried UR option. It was terrific idea. It would be good as U pass the code .

Anticipating UR earliest reply.


Commented:
Do you want a sample code of how to write your own Canvas or did you do it?

Author

Commented:
Well See i will write in detail what i did .
 1) I have one background image of building. I am suppose to move one image on
    it in a particular angel after i press a space bar.
 2) i am stuck here. I added a panel and in that i added 2 image componant in it
    but 2nd image is not shown .

   What U said is little bit confusing in a way that how would i create my canvas
   which will have one backgroud image and on that ball is to moved ?

  So i asked U for a sample code for it . It would be nice if U supply it.
  Thanks a lot.

  hateli


Commented:
here is a sample that is close to what you need. Compile it, put 2 images (image1.gif, image2.gif) in the same dir, build html file and see how it works. Then if you have Qs Im here.

1. file images_overlay.java



import java.applet.Applet;
import java.awt.*;
import java.net.*;

public class images_overlay extends Applet {
    String[] url_strings = { "image1.gif", "image2.gif"};
    int x[] = {0,0};
    int y[] = {0,0};
    Image[] images;
    ImageCanvas image_canvas;
    mover m1, m2;

    /**
     * Initializes the applet.  You never need to call this directly; it is
     * called automatically by the system once the applet is created.
     */
    public void init() {
        add( image_canvas = new ImageCanvas( getCodeBase(), url_strings, x, y ));
    }

    /**
     * Called to start the applet.  You never need to call this directly; it
     * is called when the applet's document is visited.
     */
    public void start() {
        m1 = new mover( 0.75, 1.1, 0, 0, 190, 190, 0, image_canvas, 400 );
        m2 = new mover( 0.9, 1.05, 0, 0, 190, 190, 1, image_canvas, 300 );
        m1.start();
        m2.start();
    }

    /**
     * Called to stop the applet.  This is called when the applet's document is
     * no longer on the screen.  It is guaranteed to be called before destroy()
     * is called.  You never need to call this method directly
     */
    public void stop() {
        m1.stop();
        m2.stop();
        m1 = null;
        m2 = null;
    }

}


class mover extends Thread {
    double xstep, ystep;
    int x_left_top, y_left_top;
    int x_bottem_right, y_bottem_right;
    double dirx, diry;
    int index;
    MoveDest move_dest;
    int sleep_time;
    double cx, cy;
    boolean endPlease;

    public mover( double xs, double ys, int xlt, int ylt, int xbr, int ybr, int idx, MoveDest md, int ticks_per_sec ) {
        xstep = xs; ystep = ys;
        x_left_top = xlt;
        y_left_top = ylt;
        x_bottem_right = xbr;
        y_bottem_right = ybr;
        index = idx;
        move_dest = md;
        sleep_time = 1000 / ticks_per_sec;
        cx = 0;
        cy = 0;
        endPlease = false;
        dirx=1.0;
        diry=1.0;
    }

    public void endRequest() {
        endPlease = true;
    }

    public void run() {
        while( !endPlease ) {
            move_dest.setNewCoordinates( index, (int)cx, (int)cy );
            try {
                this.sleep(sleep_time);
            } catch( Exception e ) {}
            cx += xstep*dirx;
            cy += ystep*diry;
            if( cx > x_bottem_right || cx < x_left_top ) dirx *= -1.0;
            if( cy > y_bottem_right || cy < y_left_top ) diry *= -1.0;
        }
    }
}




2. file MoveDest.java


public interface MoveDest {
   public void setNewCoordinates( int index, int xc, int yc );
}





3. file ImageCanvas.java


import java.awt.*;
import java.net.*;
import java.awt.image.*;           // For ImageFilter stuff


class ImageCanvas extends Canvas implements MoveDest {
  //-------------------------------------------------------------------------
  // Instance variables.

  private Image[] images;
  private int x[];
  private int y[];


  protected String imageString = "<Existing Image>";

  /** Turn this on to get verbose debugging messages. */
  public boolean debug = /*true;*/false;


  /** Width and height of the Canvas. This is the width/height of the image
   *  plus twice the margin.
   */
  protected int width, height;

  protected boolean explicitSize = false;
  private int explicitWidth=0, explicitHeight=0;

  // The MediaTracker that can tell if image has been loaded
  // before trying to paint it or resize based on its size.
  private MediaTracker tracker;

  // Used by MediaTracker to be sure image is loaded before paint & resize,
  // since you can't find out the size until it is done loading.
  //private static int lastTrackerID=0;
  //private int currentTrackerID;
  private boolean doneLoading = false;

  private Container parentContainer;


  //-------------------------------------------------------------------------

  //-------------------------------------------------------------------------
  // Constructors

  /** Create an ImageCanvas using the image at URL specified.
   * @param imageURL The URL of the image.
   */
  public ImageCanvas(URL baseURL, String[] names, int[] xs, int[] ys) {
        Init(baseURL,names,xs,ys);
  }

  public void Init(URL base, String[] url_strings, int[] xs, int[] ys) {
    images = new Image[url_strings.length];
    x = xs;
    y = ys;
    tracker = new MediaTracker(this);
    for( int cnt1 = 0; cnt1 < url_strings.length; cnt1++ ) {
        try {
            URL imageURL = new URL(base, url_strings[cnt1] );
            images[cnt1] = getImage(imageURL);
            tracker.addImage(images[cnt1], cnt1);
            imageString = imageURL.toExternalForm();
        } catch( MalformedURLException e ) {}
    }
    repaint();
  }


  public void setNewCoordinates( int index, int xc, int yc ) {
    synchronized(this) {
        x[index]=xc;
        y[index]=yc;
    }
    repaint();
  }


  public void waitForImage(boolean doLayout) {
    if (!doneLoading) {
      int waitfor=0;
      //try { tracker.waitForID(currentTrackerID); }
      try {
        for( int cnt1 = 0; cnt1 < images.length; cnt1++ ) {
            waitfor=cnt1;
            tracker.waitForID(cnt1);
        }
      }
      catch (InterruptedException i) {
        System.out.println(i);
      }
      catch (Exception e) {
                System.out.println("Error loading " + waitfor + ": "
                           + e.getMessage());
                e.printStackTrace();
      }
      if (tracker.isErrorID(0))
        new Throwable("Error loading image " + imageString).printStackTrace();
      if (explicitWidth != 0)
        width = explicitWidth;
      else
        width = images[0].getWidth(this);
      if (explicitHeight != 0)
        height = explicitHeight;
      else
        height = images[0].getHeight(this);
      resize(width, height);
      debug("[waitForImage] - " + imageString + " is " +
            width + "x" + height + ".");

      // If no parent, you are OK, since it will have been resized before
      // being added. But if parent exists, you have already been added,
      // and the change in size requires re-layout.
      if (((parentContainer = getParent()) != null) && doLayout) {
        setBackground(parentContainer.getBackground());
            parentContainer.layout();
      }

      doneLoading = true;
          debug("[waitForImage] -Done");
    }
  }


  public void centerAt(int x, int y) {
    debug("Placing center of " + imageString + " at (" + x + "," + y + ")");
    move(x - width/2, y - height/2);
  }
  public synchronized boolean inside(int x, int y) {
    return (x >= 0) && (x <= width) && (y >= 0) && (y <= height);
  }

  public void paint(Graphics g) {

    if (!doneLoading)
        waitForImage(true);
    else {
        synchronized(this) {
            for( int cnt1 = 0; cnt1 < images.length; cnt1++ ) {
                g.drawImage( images[cnt1],x[cnt1],y[cnt1],this);
            }
        }
    }

  }

  public Dimension preferredSize() {
    if (!doneLoading)
      waitForImage(false);
    return(new Dimension(200,200));
  }

   public Dimension minimumSize() {
     if (!doneLoading)
       waitForImage(false);
     return(new Dimension(200,200));
   }

  public void resize(int width, int height) {
    if (!doneLoading) {
      explicitSize=true;
      if (width > 0)
        explicitWidth=width;
      if (height > 0)
        explicitHeight=height;
    }
    super.resize(width, height);
  }

  public void reshape(int x, int y, int width, int height) {
    if (!doneLoading) {
      explicitSize=true;
      if (width > 0)
        explicitWidth=width;
      if (height > 0)
        explicitHeight=height;
    }
    super.reshape(x, y, width, height);
  }


  protected void debug(String message) {
    if (debug)
      System.out.println(message);
  }

  //-------------------------------------------------------------------------

  private static URL makeURL(String s) {
    URL u = null;
    try { u = new URL(s); }
    catch (MalformedURLException m) {
      System.err.println("Bad URL " + s + ": " + m);
      m.printStackTrace();
    }
    return(u);
  }

  //-------------------------------------------------------------------------
  // Needs to be static since it is called by the constructor.

  private static Image getImage(URL url) {
    return(Toolkit.getDefaultToolkit().getImage(url));
  }

}




----------------
There may be some extra code here (I hope not) since its quickly made from other code...   :-)
Good luck,
G.

Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.