Hi Guys! Will you share your thoughts on a Thread issue?

Hi! I am working on figuring out how to get my application to use threads to enable the simultaneous movement of (n) balls across the JFrame area. The task is to enable the user to click on the application and with each click a new ball should be created as a Thread and then it should bounce back and forth across the screen.
I have been working on this now for a couple of days. It would be really great if one of you guys could help me! :-)
Here are my specific issues:
I am using the mousePressed() method to generate the data needed to instantiate a Ball object. However, I cannot get it to work as a Thread.
I tried calling the start() method on it but all that happens is the application stays blank.
I cannot get this thing to work -and I really need to make it work today -- Please --- is there a sweetheart out there who will take a minute to help? ;-)
Jennifer
My code is below:
Balls.java
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Balls extends JFrame implements MouseListener
      private int x, y, r, g, b;//Variables to hold x,y and color values
      private Vector basketOBalls;//Hold all of the Ball objects (and Threads created)
      private Ball ballFactory;//Ball objects created here
        Method Name: Balls()
        Return Value: none
        Input Parameters: None
        Method Description: Constructor
      public Balls()
        //call to super for Title of app
        super( " Bouncing Balls " );
        //Listen for mouse events
        addMouseListener( this ); 
        //instantiate the basketOBalls object
        basketOBalls = new Vector(20);
            //Set Initial JFrame Window Size
        setSize( 400, 400 );
     //Show it!
     show();
     }//EOConstructor
        Method Name: mousePressed(MouseEvent e)
        Return Value: none
        Input Parameters: MouseEvent
        Method Description: This takes the info from the users
        mouse click and creates a new Ball Object and then adds it
        to the basketOBalls Vector. Presently, it (incorrectly?) also
        calls the repaint() method in order to draw the ball to the
        screen.
       public void mousePressed( MouseEvent e )
           x = e.getX();//set x value
           y = e.getY();//set y value
           r = 1 + (int) ( 254 * Math.random() );//set red value
           g = 1 + (int) ( 254 * Math.random() );//set green value
           b = 1 + (int) ( 254 * Math.random() );//set blue value
           Color colorin = new Color( r, g, b );
           ballFactory = new Ball( x, y, colorin );
           //new Thread(ballFactory).start(); //This is the Problem area!!!!!!!!!!!!!!!!!!!!!
           basketOBalls.addElement( ballFactory );
           repaint();
        }//EOmP
        Method Name: paint( Graphics g )
        Return Value: none
        Input Parameters: Graphics Object g
        Method Description: Walk through the Vector to
        explicitly cast each object back as a Ball and
        then calls the Ball draw() and ball move() methods
        in order to make the balls move on the screen.
    public void paint( Graphics g )
        Ball b;
        for( int i = 0; i < basketOBalls.size(); i++)
           b = (Ball) (basketOBalls.elementAt(i));
           b.draw(g);
           b.move();
        }//EOFor
      }//EOpaint
        Method Name: main()
        Return Value: none
        Input Parameters: String args[]
        Method Description: This makes it all go.
      public static void main( String args[] )
        Balls app = new Balls();
        app.addWindowListener(
          new WindowAdapter()
                 public void windowClosing( WindowEvent e )
                                System.exit(0);
                 }//EOwindowClosing Method
          }//EOWindowAdapter Method
          );//EOaddWindowListener Argument
      }//EOMain
    public void mouseClicked( MouseEvent e ) { }
    public void mouseReleased( MouseEvent e ) { }
    public void mouseEntered( MouseEvent e ) { }
    public void mouseExited( MouseEvent e ) { }
}//EOFBall.java
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Ball extends JFrame //implements Runnable
        public static final int APP_SIZE = 400;//set bounds for screen area
     public static final int RADIUS = 15;//set size of balls
        private Color bgColor = java.awt.Color.lightGray;//may be used to clear background of JFrame
     private int x, y;//x & y coordinates
     private int speedX, speedY;//distances to use to redraw the balls
        private Color color = null;//the color of a ball
        Method Name: Ball(int initX, int initY, Color colorin) 
        Return Value: none
        Input Parameters: int, int , color
        Method Description: Constructor that creates a Ball object
     public Ball(int initX, int initY, Color colorin)
          x = initX;
          y = initY;
                color = colorin;
             speedX = (int)(1 + (Math.random() * 10));
          speedY = (int)(1 + (Math.random() * 10));
        Method Name: move()
        Return Value: none
        Input Parameters: none
        Method Description: This calculates the balls position and keeps it within
        the 400 pixel size of the application frame.
     public void move()
          x += speedX;
          y += speedY;
          if ((x - RADIUS < 0) || (x + RADIUS > APP_SIZE))
               speedX = -speedX;
               x += speedX;
          if ((y - RADIUS < 0) || (y + RADIUS > APP_SIZE))
               speedY = -speedY;
               y += speedY;
     } //EOMove
        Method Name: draw(Graphics bg) 
        Return Value: none
        Input Parameters: graphics
        Method Description: This method is how the ball draws itself
        public void draw(Graphics bg)
            bg.setColor( color );
            bg.fillOval(x - RADIUS, y - RADIUS, 2 * RADIUS, 2 * RADIUS);
//PROBLEM AREA PROBLEM AREA PROBLEM AREA PROBLEM AREA PROBLEM AREA PROBLEM AREA
        Method Name: run() 
        Return Value: none
        Input Parameters: none
        Method Description: This method is called by start() in the Balls.java file
        found in the mousePressed() method. however, it does not work properly.
     public void run()
           while(true)
          try
             Thread.sleep(100);
                   move();
                   draw(g);
                   repaint();
                catch(Exception e)
                e.printStackTrace( System.out );
    }//EOF

There needs to be only one thread. On every mouse pressed just add a new Ball object to the vector located in Balls class. That thread need only invoke a repaint on your main class called Balls.
public class Balls extends JFrame implements Runnable,MouseListener{
Vector vector = new Vector();
public static void main(String[] args){
Balls balls = new Balls(); balls.setSize(400,400);
balls.setVisible(true);
Thread thread = new Thread(this);
thread.start();
public void run(){ 
while(true){
repaint();
try{
Thread.sleep(4000); //delay
}catch(InterruptedException e){}
public void paint(Graphics){
for(i=0; i<vector.size(); i++){
Ball b = (Ball)vector.elementAt(i);
reposition(b);
g.drawArc(b.getX(),b.getY(),0,360);
public void reposition(Ball b){
// reposition ball using balls get/set methods.
public void MouseClicked(MouseEvent e){
// add a new ball to vector.
public class Ball{
int x,y;
public int getX(){ return x; }
public int getY(){ return y; }
public int setX(int x){ this.x = x; }
public int setY(int y){ this.y = y; }
Do check the syntax and compilation errors. The code above should give you some idea for approach.

Similar Messages

  • Can you share your iTunes purchases with family members

    Can you share your iTunes purchases with other family members.

    In your household, yes.
    BTW, your question has nothing to do with itunes U.

  • Can you share your keyboard and mouse when using S...

    can you share your keyboard and mouse when using Skype Screen share?
    I want to give a remote user access to a application on my computer.  Is this posisable with Skype?
    Can you share just one application on yourscreen and not the complete screen?

    you can share both your entire screen, or just a specific window of program in your computer.  it is not possible to give someone a remote access to your computer through skype, and it is also not possible to share your mouse and keyboard.
    IF YOU FOUND OUR POST USEFUL THEN PLEASE GIVE "KUDOS". IF IT HELPED TO FIX YOUR ISSUE PLEASE MARK IT AS A "SOLUTION" TO HELP OTHERS. THANKS!
    ALTERNATIVE SKYPE DOWNLOAD LINKS | HOW TO RECORD SKYPE VIDEO CALLS | HOW TO HANDLE SUSPICIOS CALLS AND MESSAGES
    SEE MORE TIPS, TRICKS, TUTORIALS AND UPDATES in
    | skypefordummies.blogspot.com | 

  • Can you share your itunes with someone over long distance

    can you share your library with someone that isn't on the same wifi network as you?

    No. Same wifi and same Apple ID is needed.

  • HT5035 Can you share your itunes balance with another person?

    Can You share your itunes balance with another person?

    No.  It can only be used in your own account, and cannot be used to buy gift cards.

  • HT4014 when you update to 10.6.3 will you loose your files and pictures?

    when you update to 10.6.3 will you loose your files and pictures?

    No.   But you probably need to go further than 10.6.3.   If you have already bought the retail disc you should read the link below (just to double check).
    Minimum specs for Snow Leopard.        Mac OS X v10.6 Snow Leopard -Read the Technical Specifications
    Once you have bought and upgraded you will need to apply the Combo updater for Snow Leopard.          Mac OS X 10.6.8 Update Combo v1.1
    And follow that by software update to pick up any iTunes or security updates that have since become available.  

  • Pls share your thoughts to rectify

    Dear Moderators,
        We have two storage locations of say X and Y, X should store the materials which has self life period 75% and above, and y should store SLE less than 25%, everyday batch job runs to transfer the stock from X to y....now the problem is it is happening exactly reverse SLE 75% is storing Y and Less 25% storing in x.... what could be the Problem and share me the idea's ..
    Thank you very Much
    RAM

    Hi,
    Are you having a daily run program which will make a transfer post from X to Y ?
    at the same time based upon the material master settings for shelf life , the GR in to any  location X or Y will  get controlled by the system . this is a standard functionality .
    when comes to your question 75% of total life is there for a product , to go into X and vis a vis , is not a standard functionality .Probably an enhancement attached to MIGO would control the same .please check it from your ABAP side and post us back which is controlling this phenominone in the system .
    your question is not clear for the transffering .does the system is transffering 75% --X to 25 %- Y or reverse  ?in both the ways , the effect is same .you are mixing x and y . Then what is the problem ?
    Could please be specifc so that much good answer can be expected.
    Regards,

  • HT1198 Can you share your iphoto library with two users? and can they use there own apple id for photo stream?

    My wife and i have two iphones and one mac mini, we basically want to share our photos and music but also have our individual settings, so I have set up two user accounts, i have managed to share itunes successfully however iphoto'11 will not seem to let us both use it without it needing 'repairing'? any help out there?

    You'll need to put the Library on an external disk or Disk Image set to ignore owner ship and permissions.
    Regards
    TD

  • Can you share your photos in iPhoto with other users on Mac and if so How?

    I am trying to share photos in iPhoto from one user to another user on my Mac computer.  Can this be done and how do you do it?

    I am trying to share photos in iPhoto from one user to another user on my Mac computer.  Can this be done and how do you do it?
    If you only want to share a few selected albums with your favourite photos, consider to use Shared Photo Streams / Shared Albums, if your Mac OS X version supports iCloud.
    See this link:  iCloud: iCloud Photo Sharing FAQ

  • When you restore from back up will you get your photos back

    i just want to know because my brother did that for his phone and got his photos back,so if i back up my ipod and then restore it from back up will the photos come back on the ipod?

    Yes, if you make a backup right now via iCloud or iTunes, you will get everything that you ever did on your iPod from the backup

  • How will you share to idvd with the new iMovie software?

    after i updated my iMovie, sharing to idvd is gone, how will i transfer my movie to a dvd now? I bought my macbook in early 2011, still have the dvd drive.

    The apps in the multitaskbar should appear like pages on the whole display. To close them, just swipe from the bottom to the top. you can select single apps for closing, when you swipe them like you would swipe your homescreens.

  • Where will you keep your device's private data?

    Hi:
    It seems we have 3 choices to keep a device's private data:
    1. call ddi_soft_state_zalloc and store private data in the allocated structure.
    2. allocate a block of kernel memory and call ddi_set_private_data with pointer to this memory.
    3. allocate a block of kernel memory and set gldm_private to point to this area (for gld only).
    Could you please tell me which one you prefer and the reason for your choice?
    Thanks
    Best regards
    Steven

    I had the 6 for a couple months and it fit in my cup holder but the plus does not and so I will either keep it on my lap or in this small space in between the cup holder and the middle console.  I used to have a suction cup holder for my IPhone but it was too hard to keep grabbing it and replacing it whenever I'd receive a text message so I did away with that.  I saw a phone mount at the bestbuy the other day but I can't recommend it.  Have you considered turning on the handicapped assistance function where it will read to you what a text message says when it comes through or it will alert you of the caller when the phone rings?  It may compromise some privacy if you are in your vehicle with others or become annoying as you have to turn it off and on when you get in and out of your car but that way it'll allow you to keep your phone either in a pocket, purse, wallet, etc etc without having to look at it to see who's trying to reach you.

  • Will you recieve your iPod sooner if you order by phone?

    I heard that you will get your iPod sooner if you order by phone rather than online because of processing delays. Anyone know if this is true or not? Thanks.

    Im really not sure, i suggest gettin it from the apple store, i ordered my 5g online 10/17 and on 10/19 was still porcessing called my apple store b4 and they said they didnt have it, called back on the 10/19 out of curiosity and they now have a "signifcant amount" in stock as i was told. Immediately cancelled online order and went to the apple store later that day and got my 5g, goin on 3 days now 1567 songs, 14 Music Videos, 1 Tv Show (Prison Break S01E01). And still growing, front screen still has plastic, and back has 4 hairline scratches already(not noticeable), awating invisble sheild. Whats funny about scratches you have no idea when or where it happened no matter how hard you try and take care of it.

  • Channel EQ , share your thoughts

    hi
    have hardly ever used channel eq in logic, ive always gone for Fat EQ.
    But looks like channel EQ is the tool of choice for eqing?
    Should a compressor be inserted after the eq or before?
    logic manual suggests using the channel eq as the first plug in on a channel strip/track.
    multimeter, match eq, analyse function on channel eq, all great tools to learn from while playing with audio.
    cheerio

    bob2131 wrote:
    Should a compressor be inserted after the eq or before?
    In most common presets you will find that the EQ is on top. In some scenarios ( depends on your musical material ) you may need to reverse that chain...
    multimeter, match eq, analyse function on channel eq, all great tools to learn from while playing with audio.
    I have not read this chapter of the manual but it looks like some kind of "Mastering Plugin Chain" using visual metering plugins in between...
    !http://img59.imageshack.us/img59/4967/aglogo45.gif! [www.audiogrocery.com|http://www.audiogrocery.com]

  • If you buy something for money and you delete it, will you get your money back?

    Can someone please answer?

    No, unfortunately not. But however, if you ever wish to reinstall that application, you can do so for free!
    Hope this helps!

Maybe you are looking for