Solved

IMAGE

Posted on 1998-07-07
13
245 Views
Last Modified: 2010-03-30
1) I want to move a image of ball from top to Down. What shoul i do ! it shoud be
    only active when i press apace bar ball will fall down .

2) I want to generate Random balls from down to up and i want to maintain
    current position of all the balls . if ball vanishes from the screen then
    that ball is not counted.

0
Comment
Question by:hateli
  • 7
  • 6
13 Comments
 

Expert Comment

by:usk
ID: 1225333
I am not sure that I know what you mean.

1. You want to create an applet where there is an image of a ball in the top of the applet, and when the user presses space the ball must move to the bottom of the applet.

2. You want to create another applet where some balls are drawn with random position, and it is not be drawn if the position is outside the applet.

If not pleas describe what your problem is, in detail!

Is it something like the applet I have on my homepage?
   www.cybersite.dk
Where I have some moving balls.





0
 

Author Comment

by:hateli
ID: 1225334
i think ur point no 1 is what i mean. Assume a man is there on top of the applet.
i press space bar man will jump that's it . At same time Balls R generated in random from
bottom right corner of the applet.

Anticipating a reply ASAP.
i will C UR applet.
If possible i wolud like to have a code for my above problem.

0
 

Expert Comment

by:usk
ID: 1225335
I have created the applet with a ball moving from top to bottom when a key is pressed.

Now pleas specify what you mean when you say random balls?

What is to be random about the balls, the position on the applet or do you want them to move in random patterns or is it the size of the balls that is to be random or the color or a combination these? How many rendom balls do you want? Are the random balls to be generated all the time, or is it only when the user presses space you want them to be generated (while the first ball is moving from top to bottom)?

If you want this ASAP then you might be a bit more informative so that I don't have to guess what it is you need.






0
 

Author Comment

by:hateli
ID: 1225336
to usk ,
Well it would be good that if U pass the the code of
ball coming down after i press a key.

Well the other thing goes like this.
balls should be generated of same color but randomly and should
move from down to top in random positions.i also want to store
cordinates of all the balls generated. if ball went out of the applet it shoud be eliminated from array . my applet size is 500
by 300 ! hope this solves UR query.

Please reply ASAP
hateli
0
 

Author Comment

by:hateli
ID: 1225337
i just now saw UR applet on UR site same way but balls will
generate from down to top as if they R going in the air. if it goes out of the cordinates it should vanish but at the same time other balls R getting generated randomly.

0
 

Accepted Solution

by:
usk earned 60 total points
ID: 1225338
http://www.cybersite.dk/examples/

here you can see the applet and download the code !!

hope this is what you need

rgds USK
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Expert Comment

by:usk
ID: 1225339


Why do you give 60 points for this question, when you give 100 points for your "Random Image Move" question ?

0
 

Expert Comment

by:usk
ID: 1225340
You can solve the problem in two ways.

Use KeyListener and (FocusListener or MouseListener).

If you use FocusListener (my suggestion)then :

public void init()
{
.
  this.addFocusListener();
.
}


public void run()
{
  ..
  this.requestFocus(); //Insert this if you want your moving
                             //images start right after load
  ..
}

public void focusGained(FocusEvent e)
{
  //Applet gained focus, start moving images.
}

public void focusLost(FocusEvent e)
{ /*Nothing unless you want to stop somthing*/ }

IF you use MouseListener the use these methods instaed:

 this.addMouseListener(); //in init();

 //add nothing to run();

 //Start moving images in
 public void  mouseClicked(MouseEvent e) {}
 or
 public void  mousePressed(MouseEvent e) {}
 
 //these must be declared
 public void  mouseEntered(MouseEvent e) {}
 public void  mouseExited(MouseEvent e)  {}
 public void  mouseReleased(MouseEvent e){}

regrads USK

PS.
  Do you want me to add this to the example on my homepage ?
  In that case, do you want Mouse or FocusListener ?
  Add some points to this question.


0
 

Author Comment

by:hateli
ID: 1225341
yaar i will try and give U double points promise .
i want keyboard and mouse control both !
i will send a code AS AS U reply me ! promise !

0
 

Expert Comment

by:usk
ID: 1225342
HI.. I can see that you have closed the question, but do you still want me to add mouse/keybord events to the applet ??

Reason that I havent done it yet is that I have just returned from two weeks holiday.
0
 

Author Comment

by:hateli
ID: 1225343
USK my mouse prob + key board prob is solved !
now i have changed some of ur code in such a way !
i have mad Balloon fly from down to up only in
300 pixel - 500 pixel on y cordinates . that is
right corners !

My applet size is 500 width and 300 height !

now as soon as i press space bar stone is flying
on the basis of my hyperbola equation.

now i want to trap collusion beetween stone and randomly
generated ballons..

Can u help me my code goes like this ...

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class dropball extends Applet implements FocusListener, KeyListener, Runnable
{
  private Thread     my_thread   = null;  //Thread running the applet
  private Image      wkpicture   = null;  //Work picture
  private Image      Ballon   = null;  //picture to be loaded  of balloon
  private Image      Ballon1   = null;  //picture to be loaded  of Yellow balloon
  private Image      Ballon2   = null;  //picture to be loaded  of orange balloon
  private Image      bgpicture1   = null;  //picture to be loaded of stone

  private final Color bgcolor    = new Color(0x05057f);  //Background color
  // This is for cliprect
  Rectangle paint_area = new Rectangle();
  Rectangle new_area = new Rectangle();
  Dimension window_size ;


  boolean Loaded    = false;        //Check flag to see if picture is loaded
  boolean Loaded1    = false;        //Check flag to see if picture of stone is loaded

  int     ImageYpos =260;            //Moving pictures current Y pos
  int     ImageXpos =200;            //Moving pictures current X pos
  double  RanVal    = 0 ;            // Try to get Random val when space bar is pressed
 /* Vector BV = new Vector();
  Vector SV = new Vector();*/


  int w = 22;
  int h = 41;
  int px = 400;
  int py = 500;

  int opx,opy;

  boolean KeyPressed = false;       //True when key is pressed and will stay true
                                    //until picture is at the bottom of the applet
  // droping ball
  final int speed = 2;                //Number of pixels image moves
  final int pause = 15;               //Number of mill sek. between moves

  // bubbles
  final int NumOfBubbles = 15;         //Number of bubbles moving from bottom of applet
  int BubblesX[];         //Current X pos of bubbles
  int BubblesY[];         //Current Y pos of bubbles
  int StoneX[];         //Current X pos of Stone
  int StoneY[];         //Current Y pos of Stone

  int BubbleSpeed[];      //Number of pixels image moves


  public void init()
  {
    setBackground(bgcolor);
   
    this.addKeyListener(this);
    this.addFocusListener(this);

    wkpicture  = createImage(getSize().width,getSize().height);     //Create workpicture
    Ballon  = getImage(getDocumentBase(), getParameter("img1")); //Create ballon picture
    bgpicture1  = getImage(getDocumentBase(), getParameter("img2")); //Create stone picture
    Ballon1  = getImage(getDocumentBase(), getParameter("img3")); //Create stone picture
    Ballon2  = getImage(getDocumentBase(), getParameter("img4")); //Create stone picture


    Loaded=prepareImage(Ballon,this);                             //Load bubble picture
    Loaded1=prepareImage(bgpicture1,this);                                   //Load Stone picture

    BubblesX = new int[NumOfBubbles];        
    BubblesY = new int[NumOfBubbles];        
    BubbleSpeed = new int[NumOfBubbles];      

    for (int i = 0; i < NumOfBubbles; i++)  initBubble(i);
              //{{INIT_CONTROLS
            setLayout(null);
                setSize(500,300);
            //}}
}

  private void initBubble(int i)
  {
    Double RandX = new Double((Math.random()*getSize().width)+1); //Give  bubble random X pos
   // BubblesX[i] = RandX.intValue();                               //Give  bubble random X pos
    BubblesX[i] = (int) (Math.random() * 200) + 350;
//    showStatus("Rajesh ="+BubblesX[i]);
    BubblesY[i] = getSize().height;                   // Put bubble in bommtom of applet
    Double RandS = new Double((Math.random()*4)+1);   // Give bubble random speed
    BubbleSpeed[i] = RandS.intValue();                // Give bubble random speed
  }

  public void paint(Graphics g)
  {
    try {
      if(Loaded)
      {
       g.drawImage(wkpicture,0,0,bgcolor,this);
      }
    } catch (Exception e){stop();}
  }

  public void drawBubbles(Graphics g)
  {
    int temp ;

    g.clearRect(0,0,getSize().width,getSize().height);  //Clear work picture
    for (int i = 0; i < NumOfBubbles; i++)              //Handle each bubble
    {
//       showStatus("Drawing ...." + i);
      // Try to use here cliprect
      temp = Math.random() > 0.5 ? 1 : -2 ;
      BubblesY[i] = BubblesY[i] - BubbleSpeed[i]  ;
      BubblesX[i] =  BubblesX[i] + temp ;
      if (BubblesY[i] < 0 - Ballon.getHeight(this)) initBubble(i); //If bubble is offscreen then create new
      if (Math.random()* 200 > 100 )
      {
      g.drawImage(Ballon,BubblesX[i],BubblesY[i],this); //Draw on work picture
//      showStatus("True......");
      }
      else
      {
      g.drawImage(Ballon1,BubblesX[i],BubblesY[i],this); //Draw on work picture
//      showStatus("FALSE......");
      }

    }
  }

  //Draw loaded picture on work picture
  public void background(Graphics g)
  {
    drawBubbles(g);
    // Draws a initial image of stone on lase linf of the applet
 //  g.drawImage(bgpicture1,(getSize().width/2)-(bgpicture1.getWidth(this)/2),ImageYpos,this);
   g.drawImage(bgpicture1,ImageXpos,ImageYpos,this);


    g.setColor(Color.white);
    g.drawLine(0,getSize().height-1,getSize().width,getSize().height-1);
  }

  //Don't start animation until picture is completely loaded
  public boolean imageUpdate(Image img,int infoflag,int x,int y,int w,int h)
  {
    if(infoflag == ALLBITS)
    {
      Loaded = true;
      start();
      return false;
    } else return true;

  }

  //Avoid flashing when repaint
  public void update(Graphics g)
  {
    paint(g);
  }

//###########  KEY EVENTS ############

  /* Key Listener methods */
  public void keyPressed(KeyEvent e) {
  }

  public void keyReleased(KeyEvent e) {
  }

  public void keyTyped(KeyEvent e) {
     KeyPressed = true;
     ImageYpos = 260;
     ImageXpos = 200 ;
     RanVal =  Math.random()*10 ;
     showStatus("RanVal"+(int)RanVal);
  }

//###########  Focus EVENTS ############

  /* Focus Listener methods */
  public void focusLost(FocusEvent e) {
  }

  public void focusGained(FocusEvent e) {
  }
 

  //########### RUN ##########
  public void run()
  {
   // showStatus("ImageXpos"+ImageXpos);

    int MaxY = (getSize().height)-bgpicture1.getHeight(this);
    MaxY = (getSize().height)-Ballon.getHeight(this);
    while (true) {


      if (KeyPressed && (ImageYpos > 0))
      {

       ImageYpos = ImageYpos - 5 ;// ImageYpos = speed - ImageYpos;
       ImageXpos = ImageXpos + 5 ;
       }
      else { KeyPressed = false; }



      // Checking for clash
      if(KeyPressed == true)
        {
       /*   for (int i = 0 ; i < NumOfBubbles; i++)
          {
             if(ImageXpos==BubblesY[i])
             showStatus(" Kaypo che ! ");
          }*/
        }

      try {
//         showStatus("Rajesh ="+ImageYpos+"Going at = "+ImageXpos); // Show current Y pos in status
         background(wkpicture.getGraphics()); // Draw image on background
         repaint();
         my_thread.sleep(pause);              // wait
      }
      catch (Exception e) {showStatus(e.toString()); stop();}
    }    
  }

  public void start()
  {
    this.requestFocus(); //To avoid having to click applet first
    window_size = getSize();
    if((Loaded) && (my_thread == null))
    {
      my_thread = new Thread(this);
      my_thread.start();
    }
  }

  public void stop()
  {
     if(my_thread != null)
     {
       my_thread.interrupt();
       my_thread = null;

     }
  }

Please help me ASAP


0
 

Author Comment

by:hateli
ID: 1225344
USK my mouse prob + key board prob is solved !
now i have changed some of ur code in such a way !
i have mad Balloon fly from down to up only in
300 pixel - 500 pixel on y cordinates . that is
right corners !

My applet size is 500 width and 300 height !

now as soon as i press space bar stone is flying
on the basis of my hyperbola equation.

now i want to trap collusion beetween stone and randomly
generated ballons..

Can u help me my code goes like this ...

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class dropball extends Applet implements FocusListener, KeyListener, Runnable
{
  private Thread     my_thread   = null;  //Thread running the applet
  private Image      wkpicture   = null;  //Work picture
  private Image      Ballon   = null;  //picture to be loaded  of balloon
  private Image      Ballon1   = null;  //picture to be loaded  of Yellow balloon
  private Image      Ballon2   = null;  //picture to be loaded  of orange balloon
  private Image      bgpicture1   = null;  //picture to be loaded of stone

  private final Color bgcolor    = new Color(0x05057f);  //Background color
  // This is for cliprect
  Rectangle paint_area = new Rectangle();
  Rectangle new_area = new Rectangle();
  Dimension window_size ;


  boolean Loaded    = false;        //Check flag to see if picture is loaded
  boolean Loaded1    = false;        //Check flag to see if picture of stone is loaded

  int     ImageYpos =260;            //Moving pictures current Y pos
  int     ImageXpos =200;            //Moving pictures current X pos
  double  RanVal    = 0 ;            // Try to get Random val when space bar is pressed
 /* Vector BV = new Vector();
  Vector SV = new Vector();*/


  int w = 22;
  int h = 41;
  int px = 400;
  int py = 500;

  int opx,opy;

  boolean KeyPressed = false;       //True when key is pressed and will stay true
                                    //until picture is at the bottom of the applet
  // droping ball
  final int speed = 2;                //Number of pixels image moves
  final int pause = 15;               //Number of mill sek. between moves

  // bubbles
  final int NumOfBubbles = 15;         //Number of bubbles moving from bottom of applet
  int BubblesX[];         //Current X pos of bubbles
  int BubblesY[];         //Current Y pos of bubbles
  int StoneX[];         //Current X pos of Stone
  int StoneY[];         //Current Y pos of Stone

  int BubbleSpeed[];      //Number of pixels image moves


  public void init()
  {
    setBackground(bgcolor);
   
    this.addKeyListener(this);
    this.addFocusListener(this);

    wkpicture  = createImage(getSize().width,getSize().height);     //Create workpicture
    Ballon  = getImage(getDocumentBase(), getParameter("img1")); //Create ballon picture
    bgpicture1  = getImage(getDocumentBase(), getParameter("img2")); //Create stone picture
    Ballon1  = getImage(getDocumentBase(), getParameter("img3")); //Create stone picture
    Ballon2  = getImage(getDocumentBase(), getParameter("img4")); //Create stone picture


    Loaded=prepareImage(Ballon,this);                             //Load bubble picture
    Loaded1=prepareImage(bgpicture1,this);                                   //Load Stone picture

    BubblesX = new int[NumOfBubbles];        
    BubblesY = new int[NumOfBubbles];        
    BubbleSpeed = new int[NumOfBubbles];      

    for (int i = 0; i < NumOfBubbles; i++)  initBubble(i);
              //{{INIT_CONTROLS
            setLayout(null);
                setSize(500,300);
            //}}
}

  private void initBubble(int i)
  {
    Double RandX = new Double((Math.random()*getSize().width)+1); //Give  bubble random X pos
   // BubblesX[i] = RandX.intValue();                               //Give  bubble random X pos
    BubblesX[i] = (int) (Math.random() * 200) + 350;
//    showStatus("Rajesh ="+BubblesX[i]);
    BubblesY[i] = getSize().height;                   // Put bubble in bommtom of applet
    Double RandS = new Double((Math.random()*4)+1);   // Give bubble random speed
    BubbleSpeed[i] = RandS.intValue();                // Give bubble random speed
  }

  public void paint(Graphics g)
  {
    try {
      if(Loaded)
      {
       g.drawImage(wkpicture,0,0,bgcolor,this);
      }
    } catch (Exception e){stop();}
  }

  public void drawBubbles(Graphics g)
  {
    int temp ;

    g.clearRect(0,0,getSize().width,getSize().height);  //Clear work picture
    for (int i = 0; i < NumOfBubbles; i++)              //Handle each bubble
    {
//       showStatus("Drawing ...." + i);
      // Try to use here cliprect
      temp = Math.random() > 0.5 ? 1 : -2 ;
      BubblesY[i] = BubblesY[i] - BubbleSpeed[i]  ;
      BubblesX[i] =  BubblesX[i] + temp ;
      if (BubblesY[i] < 0 - Ballon.getHeight(this)) initBubble(i); //If bubble is offscreen then create new
      if (Math.random()* 200 > 100 )
      {
      g.drawImage(Ballon,BubblesX[i],BubblesY[i],this); //Draw on work picture
//      showStatus("True......");
      }
      else
      {
      g.drawImage(Ballon1,BubblesX[i],BubblesY[i],this); //Draw on work picture
//      showStatus("FALSE......");
      }

    }
  }

  //Draw loaded picture on work picture
  public void background(Graphics g)
  {
    drawBubbles(g);
    // Draws a initial image of stone on lase linf of the applet
 //  g.drawImage(bgpicture1,(getSize().width/2)-(bgpicture1.getWidth(this)/2),ImageYpos,this);
   g.drawImage(bgpicture1,ImageXpos,ImageYpos,this);


    g.setColor(Color.white);
    g.drawLine(0,getSize().height-1,getSize().width,getSize().height-1);
  }

  //Don't start animation until picture is completely loaded
  public boolean imageUpdate(Image img,int infoflag,int x,int y,int w,int h)
  {
    if(infoflag == ALLBITS)
    {
      Loaded = true;
      start();
      return false;
    } else return true;

  }

  //Avoid flashing when repaint
  public void update(Graphics g)
  {
    paint(g);
  }

//###########  KEY EVENTS ############

  /* Key Listener methods */
  public void keyPressed(KeyEvent e) {
  }

  public void keyReleased(KeyEvent e) {
  }

  public void keyTyped(KeyEvent e) {
     KeyPressed = true;
     ImageYpos = 260;
     ImageXpos = 200 ;
     RanVal =  Math.random()*10 ;
     showStatus("RanVal"+(int)RanVal);
  }

//###########  Focus EVENTS ############

  /* Focus Listener methods */
  public void focusLost(FocusEvent e) {
  }

  public void focusGained(FocusEvent e) {
  }
 

  //########### RUN ##########
  public void run()
  {
   // showStatus("ImageXpos"+ImageXpos);

    int MaxY = (getSize().height)-bgpicture1.getHeight(this);
    MaxY = (getSize().height)-Ballon.getHeight(this);
    while (true) {


      if (KeyPressed && (ImageYpos > 0))
      {

       ImageYpos = ImageYpos - 5 ;// ImageYpos = speed - ImageYpos;
       ImageXpos = ImageXpos + 5 ;
       }
      else { KeyPressed = false; }



      // Checking for clash
      if(KeyPressed == true)
        {
       /*   for (int i = 0 ; i < NumOfBubbles; i++)
          {
             if(ImageXpos==BubblesY[i])
             showStatus(" Kaypo che ! ");
          }*/
        }

      try {
//         showStatus("Rajesh ="+ImageYpos+"Going at = "+ImageXpos); // Show current Y pos in status
         background(wkpicture.getGraphics()); // Draw image on background
         repaint();
         my_thread.sleep(pause);              // wait
      }
      catch (Exception e) {showStatus(e.toString()); stop();}
    }    
  }

  public void start()
  {
    this.requestFocus(); //To avoid having to click applet first
    window_size = getSize();
    if((Loaded) && (my_thread == null))
    {
      my_thread = new Thread(this);
      my_thread.start();
    }
  }

  public void stop()
  {
     if(my_thread != null)
     {
       my_thread.interrupt();
       my_thread = null;

     }
  }

Please help me ASAP


0
 

Expert Comment

by:usk
ID: 1225345
TRY THIS

int ImageWidth   = bgpicture1.getWidth(this);
int ImageHeight  = bgpicture1.getHeight(this);
int BubbleWidth  = Ballon.getWidth(this);
int BubbleHeight = Ballon.getHeight(this);

for (int i = 0; i < NumOfBubbles; i++)
{
  IF((BubblesX[i] <= ImageXpos   + ImageWidth)  &&
     (ImageXpos   <= BubblesX[i] + BubbleWidth) &&
     (BubblesY[i] <= ImageYpos   + ImageHeight) &&
     (ImageYpos   <= BubblesY[i] + BubbleHeight) )
  {
    // clash
  }
  else
  {
    // NO clash
  }
}
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This video teaches viewers about errors in exception handling.

708 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

17 Experts available now in Live!

Get 1:1 Help Now