Solved

magic

Posted on 1998-07-10
5
288 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 ?
0
Comment
Question by:hateli
  • 3
  • 2
5 Comments
 
LVL 6

Accepted Solution

by:
gadio earned 200 total points
ID: 1225779
What you should do is create an applet that holds a Canvas class. The canvas will be the drawing area. You should write your own canvas so that it will listen to keyboard events. When you press space, you will initiate a new thread in the listener method, that will draw the circle on the canvas, and move it location every given time. In order to avoid garphic flickering you may want to use double buffering. These are only headlins. I suggest that you take it a step at as a time and when you implement comment here and I'll give you more specific clarifications.
0
 

Author Comment

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

Anticipating UR earliest reply.


0
 
LVL 6

Expert Comment

by:gadio
ID: 1225781
Do you want a sample code of how to write your own Canvas or did you do it?
0
 

Author Comment

by:hateli
ID: 1225782
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


0
 
LVL 6

Expert Comment

by:gadio
ID: 1225783
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.

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
GUI builder for Eclipse? 8 27
HSSFWorkbook cannot be resolved error 10 50
Java Timer (static) 9 36
session migration servlets 2 26
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This video teaches viewers about errors in exception handling.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now