Animation Thread

Hey, I have a program that performs an animation using a timer just like the Java Tutorial has for animations. The animation plots a histogram with data when the user clicks on a button. There is also some statistical data the pops up when the user clicks on the button. The statistical data shows up right away after the user clicks on the button, but the animation takes a few seconds. This makes perfect sense as the animation is a seperate thread. Well, my boss would like the statistical data to update after the animation is finished. I'm not sure at all how I would go about doing that.
Basically what I want to do is wait for the timer to stop before returning to the calling method:
timer.start();
// delay until timer is stopped.
return(1);I tried this, but it didn't work:
timer.start();
while(timer.isRunning());
return(1);Any help would be great!

I suggest giving the animation and the calculation of the statistical data their own functions, then calling each of them when the button is clicked. Example:
// The event handling code
public void actionPerformed(ActionEvent e)
// Test if the button is being pressed
if(e.getActionCommand() == "calculate")
doAnimation();
calculateData();
}Could you post some of your code? I might be able to give more specific help if so.
-Eric

Similar Messages

  • Animation thread not using repaint help

    hi
    I have made a simple applet moving a circle across the screen.
    But the animation is jerky,I use buffering but the circle still
    gets sudden bigger moves though it should only move 1 pixel at each repaint.
    Could this be fixed with making a new thread that updates the position of the circle instead of updating it in paint() ?
    And why is it normal to use sleep() in the animation thread, isnt it possible to just paint as fast as possible? instead of using sleep(25),why not just tell the thread to wait for the "calculation" thread to be finished,and then continue? isn't that what the sleep() is for?waiting for the other stuff to be done so the rendering doesnt take all the processor time? So it would be better to just tell the animation thread to wait until the other thread is finished. This would make the animation be as fast as possible..and faster on a fast machine.
    Any ideas?
    Here is the source code to my applet test. If you want to comment then please do.
    import java.awt.*;
    import java.applet.Applet;
    public class Class1 extends Applet implements Runnable
    private Thread anim;
    private Thread calc;
    private boolean running = false;
    private boolean running2 = false;
    int x = 0;
    int y = 40;
    Dimension minBufferDimension;
    Image minBufferImage;
    Graphics minBufferGraphics;
    public void init()
    minBufferDimension = getSize();
    minBufferImage = createImage( 300, 300 );
    minBufferGraphics = minBufferImage.getGraphics();
    public void run()
    Thread currentThread = Thread.currentThread();
    while(currentThread == anim)
    repaint();
    try
    anim.sleep(15);
    catch (InterruptedException e){}
    while(currentThread == calc)
    x++;
    try
    calc.sleep(15);
    catch (InterruptedException e) {}
    public synchronized void start()
    if(anim == null || !anim.isAlive())
    anim = new Thread(this);
    anim.setPriority(Thread.MIN_PRIORITY + 1);
    if(calc == null || !calc.isAlive())
    calc = new Thread(this);
    calc.setPriority(Thread.MIN_PRIORITY + 1);
    calc.start();
    anim.start();
    public synchronized void stop()
    running = false;
    running2 = false;
    public void update( Graphics g )
    paint(g);
    public void paint(Graphics g)
    minBufferGraphics.setColor( getBackground() );
    minBufferGraphics.fillRect(     0 , 0 , 300, 300 );
    minBufferGraphics.setColor( Color.black );
    minBufferGraphics.drawOval(x,y,40,40);
    g.drawImage( minBufferImage, 0, 0, this );
    }

    so many threads for so little work.
    import java.awt.*;
    import java.applet.Applet;
    public class Class1 extends Applet implements Runnable{
         private Thread thread;
         private boolean running = true;
         int x = 1;
         int y = 40;
         int direction=1;
         int changeDirection=-1;
         Image minBufferImage;
         Graphics minBufferGraphics;
         public void init(){
         public void run(){
              while(running){
                   repaint();
                   move();
                   try{
                   thread.sleep(15);
                   }catch (InterruptedException e){}
         public synchronized void start(){
              thread = new Thread(this);
              thread.start();
         public synchronized void stop(){
              running = false;
         public void move(){
              if(x>getSize().width-40 || x<0){
                   direction=direction*changeDirection;
              x=x+direction;
         public void paint(Graphics g){
              g.setColor(Color.black);
              g.drawOval(x,y,40,40);
         public void update(Graphics g) {
              if(minBufferImage==null){
                   minBufferImage=createImage(getSize().width,getSize().height);
              minBufferGraphics=(minBufferImage.getGraphics());
              minBufferGraphics.setColor(getBackground());
              minBufferGraphics.fillRect(0,0,getSize().width,getSize().height);
              paint(minBufferGraphics);
              g.drawImage(minBufferImage,0,0,this);
    }the sleep method is used to slow down the animation, and to allow time for garbage collection. it doesn't need to be as high as it is, but a least a few millisecs is recommended.

  • Animation & Threads

    Hi,
    I have a swing application and I have picked out code from
    http://java.sun.com/docs/books/tutorial/uiswing/painting/movingImage.html.
    On a background I would like to move an image across the screen at various intervals of time. i.e if I start an animator loop at the beginning I would like to start another animation after 10ms at a different position on the screen. How can I do this? Does this need to be multi threaded and where can I add the Labels on the JPanel?
    Thanks in advance.

    you havn't stated in what context you want this

  • Problem with animation and separate CPU intensive thread.

    Hi All,
    I'm in the process of writing a Java chess game with a computer AI. I've got everything working except for the animation of the computer making its move. Sometimes it works, sometimes it doesnt.
    Here's the problem:
    After the computer has finished deciding what move to make (CPU intensive - using standard Minimax w/ Alpha Beta pruning), the thread terminates passing the move to the animation thread (implemented using javax.swing.Timer). My delay is set to 50. But the multiple calls to repaint() in the Timer thread all get collapsed into one (they somehow get bunched up) causing a major display glitch!
    Sometimes this happens, sometimes it doesnt. I wanted to know if i could write some kind of wait function to wait until the CPU is free to process quick repaint() requests so that my animation can look descent all the time.
    Thanks for any help.
    jairam at ecf dot utoronto dot ca

    In the javax.swing.Timer class is a method called
    setCoalesque(boolean) (I think I spelled that wrong, but you will find it)
    By default the Timer class does exacltly what you mentioned, it merges multiple events into one when the application is too busy. Call setCoalesque(false) to receive all the events from the Timer.

  • Animation problem ( badly needs) ?

    Hello,
    Sorry i 'm posting again and again. because nobody couldn't respond . I badly need this application to be run. Here is what am doing. First applet should start and display '+'( by painting) after keypressed(eg spacebar) then sleep for a while and paint rectangles and next arrow then sleep and etc . this goes on until i keypressed again. Here is that i wrote code , could u please check and modify it. Where i stucked is that KeyPressed code is not working. Please see the code modify it wherever is necessary.
    Thanks in advance,
    - Balaji
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Color;
    import java.awt.Rectangle;
    import java.awt.GradientPaint;
    import java.awt.geom.GeneralPath;
    import java.awt.Polygon;
    //<applet code="ExptA4.class" width=300 height=300></applet>
    public class ExptA4 extends Applet implements Runnable {
         Thread animator;
         Dimension appSize;
         boolean frozen = false;
         int appWidth = 1000, appHeight = 800;
         int delay = 500;
         java.awt.geom.Ellipse2D.Double circle;
         public void init(){
              appSize = new Dimension(appWidth,appHeight);
              this.setSize(appSize);
             addKeyListener(new KeyAdapter(){
                  public void keyPressed(KeyEvent e){
                  ExptA4 exptA4 = (ExptA4) e.getSource();
                  if (e.getKeyCode() == KeyEvent.VK_SPACE)
                       System.out.println("in the keypressed method ");
                  }// end of if      
                  } // end of keyPressed method
         } // end of init
         public void start(){
              if(frozen)
               { // do nothing
              else
                 if(animator == null) {
                           animator = new Thread(this);
                animator.start();  
               } // end of else
               requestFocus(); 
         } // end of start
         public void stop(){
              // stop the animation thread
              animator = null ;
         } // end of stop
         public void run(){
              Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
              while(Thread.currentThread() == animator)
                      repaint();
                      try {
                     Thread.sleep(5400);
                       } catch (InterruptedException e) {
                             break;
         } // end of run
         public void paint(Graphics g){
              Graphics2D g2 = (Graphics2D)g;
            Rectangle leftRect,rightRect,plus_horz,plus_vert;
            Polygon downArrow = new Polygon();    
           // drawing the plus               
           int xHPoint = 440,yHPoint = 350, widthP = 30, heightP = 30;
           plus_horz = new Rectangle(xHPoint,yHPoint,widthP,heightP-27);
           plus_vert = new Rectangle(xHPoint+10,yHPoint-10,widthP-17,heightP-10);
           // black interior
            g2.setColor(Color.black);
            g2.fill(plus_horz);
            // black border
            g2.setColor(Color.black);
            g2.draw(plus_horz);
           // black interior
            g2.setColor(Color.black);
            g2.fill(plus_vert);
            // black border
            g2.setColor(Color.black);
            g2.draw(plus_vert);
               try{
                     Thread.sleep(4000);
                 } catch (InterruptedException ie)
           // drawing the Rectangle
                  leftRect = new Rectangle(300,300,100,100);
             rightRect = new Rectangle(500,300,100,100);
             // white interior
            g2.setColor(Color.white);
            g2.fill(leftRect);
            // black border
            g2.setColor(Color.black);
            g2.draw(leftRect);
            // white interior
            g2.setColor(Color.white);
            g2.fill(rightRect);
            // black border
            g2.setColor(Color.black);
            g2.draw(rightRect);
           try{
                     Thread.sleep(4000);
                 } catch (InterruptedException ie)
           // drawing downArrow
            int xPointA = 340,yPointA = 340, widthA = 30, heightA = 30;
             downArrow.addPoint(xPointA,yPointA);
            downArrow.addPoint(xPointA+25,yPointA-25);
            downArrow.addPoint(xPointA+13,yPointA-25);
            downArrow.addPoint(xPointA+13,yPointA-75);
            downArrow.addPoint(xPointA-13,yPointA-75);
            downArrow.addPoint(xPointA-13,yPointA-25);
            downArrow.addPoint(xPointA-25,yPointA-25);
            g2.setColor(Color.white);
            g2.fill(downArrow);
            // black border
            g2.setColor(Color.black);
            g2.draw(downArrow);
           try{
                     Thread.sleep(4000);
                 } catch (InterruptedException ie)
       // drawing circle             
           int xPoint = 340,yPoint = 340, width = 30, height = 30;
           circle = new java.awt.geom.Ellipse2D.Double(xPoint,yPoint,width,height);
            // black interior
            g2.setColor(Color.black);
            g2.fill(circle);
            // black border
            g2.setColor(Color.black);
            g2.draw(circle);
           try{
                     Thread.sleep(4000);
                 } catch (InterruptedException ie)
         } // end of paint method
    }

    hi ,
    here is modified code . I kept all sleep methods in the run method.
    But the problem is i couldn't get any response from the keyboard.
    What i need is that whenever key presses then animation should starts.
    please help me in this regard.i 'm putting my code here, please modify
    it according to my requirements. Once again i badly need this one to be run. i really appreciate if anyone help in this one.
    Thanks,
    -balaji
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Color;
    import java.awt.Rectangle;
    import java.awt.GradientPaint;
    import java.awt.geom.GeneralPath;
    import java.awt.Polygon;
    //<applet code="ExptA5.class" width=300 height=300></applet>
    public class ExptA5 extends Applet implements Runnable,KeyListener {
         Thread animator;
         Dimension appSize;
         boolean frozen = false;
         int appWidth = 1000, appHeight = 800;
         int delay = 500;
      // drawing circle and arrow.
         DrawCircle circle = new DrawCircle();
        DrawArrow downArrow = new DrawArrow();
         public void init(){
            // setting dimension for applet
              appSize = new Dimension(appWidth,appHeight);
              this.setSize(appSize);
              // adding key listener
             addKeyListener(this);
         } // end of init
    // to activate keys
         public void keyPressed(KeyEvent e ){
              System.out.println("in the keypressed method ");
              ExptA5 exptA5 = (ExptA5) e.getSource();
        // when space bar presses then start the thread and animation starts
              if( e.getKeyCode() == KeyEvent.VK_SPACE)
               if ( Thread.currentThread() == animator)
                     exptA5.animator.start();
              } // end of if
         } // end of keyPressed
    // other key methods
         public void keyTyped(KeyEvent e){}
         public void keyReleased(KeyEvent e){}
         // applet starts and animation starts .
         public void start(){
              if(frozen)
               { // do nothing
              else
                 if(animator == null) {
                           animator = new Thread(this);
                animator.start();
               } // end of else
         } // end of start
         public void stop(){
              // stop the animation thread
              animator = null ;
         } // end of stop
         public void run(){
              Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
              while(Thread.currentThread() == animator)
              try {
                 Graphics g = getGraphics();
                   Graphics2D g2 = (Graphics2D)g;          
                  // drawing arrow which is calling from other class
                 downArrow.drawPoly(g2);
                 // sleeps for a while                               
                 Thread.sleep(5400);
                    // drawing circle which is calling from other class
                    circle.drawCircle(g2);
                    // sleeps for a while
                 Thread.sleep(5400);
                 repaint();   
                       } catch (InterruptedException e) {
                             break;
         } // end of run
         public void paint(Graphics g){
         } // end of paint method
    // drawing circle
    public class DrawCircle{
       java.awt.geom.Ellipse2D.Double circle;
       public void drawCircle(Graphics2D g2)
              int xPoint = 340,yPoint = 340, width = 30, height = 30;
          circle = new java.awt.geom.Ellipse2D.Double(xPoint,yPoint,width,height);
          // black interior
          g2.setColor(Color.black);
          g2.fill(circle);
            // black border
          g2.setColor(Color.black);
          g2.draw(circle);
    // drawing Arrow
    public class DrawArrow{
          Polygon downArrow = new Polygon();
       public void drawPoly(Graphics2D g2)
              // drawing downArrow
            int xPointA = 340,yPointA = 340, widthA = 30, heightA = 30;
             downArrow.addPoint(xPointA,yPointA);
            downArrow.addPoint(xPointA+25,yPointA-25);
            downArrow.addPoint(xPointA+13,yPointA-25);
            downArrow.addPoint(xPointA+13,yPointA-75);
            downArrow.addPoint(xPointA-13,yPointA-75);
            downArrow.addPoint(xPointA-13,yPointA-25);
            downArrow.addPoint(xPointA-25,yPointA-25);
            g2.setColor(Color.white);
            g2.fill(downArrow);
            // black border
            g2.setColor(Color.black);
            g2.draw(downArrow);
    }

  • Animation is a dirty word

    HI everyone, I've been struggling with this animation malarky for a while now and was wondering if anyone would give me some input on the little snippet below. The idea was to create a generic animation class, that was double buffered and could operate on any JComponent?
    btw it doesn't seem to work and I'm stumped as to why not!!
    public class Animation implements Runnable {
         private double _time = 0;
         private double _timestep = 5;
         private double _duration = 100;
         private JComponent target;
         private Graphics2D offscreenG2D;
         private Image offscreenImage;
         private Thread animationThread;
         public Animation() {
              super();
         public void rewind() {
              _time = 0;
              stop();
         public void pause() {
              if (animationThread != null) {
                   try {
                        animationThread.wait();
                   } catch (InterruptedException e) {
         public void stop() {
              animationThread = null;
         public void play() {
              if (animationThread == null) {
                   //if the animation is stopped we create a new thread and start it
                   animationThread = new Thread(this, "Animation Thread");
                   animationThread.setPriority(Thread.MIN_PRIORITY);
                   animationThread.start();
              } else {
                   // if the animation is paused then we wake it up;
                   if (animationThread.isAlive()) {
                        animationThread.notify();
         public void forward() {
              _time = _duration;
              stop();
         public void setTime(double time) {
              _time = time;
         public void setTimeStep(double step) {
              _timestep = step;
         public void setTarget(JComponent component) {
              target = component;
         public void run() {
              offscreenImage = target.createImage(target.WIDTH, target.HEIGHT);
              offscreenG2D = (Graphics2D) offscreenImage.getGraphics();
              while (_time < _duration) {
                   // draw everything to offscreenG2D
                   target.update(offscreenG2D)
    }

    Hi,
    I always use a JPanel as the drawing surface of my animations since it is double buffered by default. Did you try that?
    If you have time take a look at one of my animations at http://academic.evergreen.edu/c/celber20/java/fan.html and if you have any other questions let me know.
    Berk Can Celebisoy

  • Waiting for a thread to die.

    Hello, I hope you can help me...
    I am writting a jdk1.4.1 Swing application that displays a small animation. This animation is processed from within a separate thread. My program makes a call starting this 'animation thread'. For practical reasons my program needs to wait for this thread to die (and thus the full animation to be shown) before it can continue. I am waiting for the animation thread to die using Threads 'join' method. However the problem with this is that I am forcing the GUI thread to wait resulting in the animation being calculated but not displayed. And so... how can I fix this... all I want is to wait until the animation is shown.
    What I would like to do is:
    1. Start animation;
    2. wait intil animation has completed;
    3. continue with program.
    Any help or advice will be greatly appreciated.
    Thank you in advance.

    Maybe this design could work for you. You divide your program into three parts running in three separate threads.
    1. The main thread handling GUI stuff and coordination of the two other threads.
    2. A working thread doing most of what the main thread is now doing.
    3. The animation thread.
    With this division of labour the working thread is waiting for the animation thread to finish (the main GUI thread isn't). The main thread will be free at all times to react to the users input or updating the screen or whatever, while the other two threads are cooperating to produce the animation.

  • Problem with simple animation.  Any help greatly appreciated.

    I am trying to make a circle (which is actually an array of polygons in the shape of a circle) change color over time. Basically what the inner loop does is assign each polygon a random color. The desired effect here is for the circle to be assigned a certain array of colors then have swing repaint the component so we can see the change and repeat, resulting in a nice animation of colors changing over time. What ends up happening is the applet only updates after it has done the entire outer loop. So only the last color state of the circle is seen after it has done all the computations. So it goes from the intial color to the end color, without showing the states in between. What can I do for it to repaint for each of the recolorings? The computation is complex enough so it's not as if it displays the colors so fast that you only notice the end state.
    for (int year=0; year<500000; year+=500)
    for (int x=0; x<180; x++)
    polys[x].setColor(generator.nextInt(250),generator.nextInt(250),generator.nextInt(250));
    repaint();
    poly.update(polys);
    }

    I was struggling to find a relevant piece of code to demonstrate how this can be done. I eventually ended up with the ugliest animation ever.import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    public class AnimationDemo extends JPanel {
         private static final Color[] COLORS = {Color.WHITE, Color.RED, Color.BLUE, Color.YELLOW, Color.BLACK};
         private static int getNextColorIndex(int aColorIndex) {
              return ++aColorIndex % COLORS.length;
         private static class ColoredSquare {
              int theColorIndex;
              Rectangle theRectangle;
              public ColoredSquare(int aColorIndex, Rectangle aRectangle) {
                   theColorIndex = aColorIndex;
                   theRectangle = aRectangle;
         private static class Mozaic extends JComponent implements Runnable {
              private ColoredSquare[] theColoredSquares;
              public Mozaic() {
                   int width = 49;
                   int height = 49;
                   Dimension squareDimension = new Dimension(10, 10);
                   theColoredSquares = new ColoredSquare[width * height];
                   int index = 0;
                   int colorIndex = 0;
                   Point currentPoint;
                   for (int x = 0; x < width; x++) {
                        for (int y = 0; y < height; y++) {
                             currentPoint = new Point(x * squareDimension.width, y * squareDimension.height);
                             theColoredSquares[index] = new ColoredSquare(colorIndex, new Rectangle(currentPoint, squareDimension));
                             index++;
                             colorIndex = getNextColorIndex(colorIndex);
                   setPreferredSize(new Dimension(width * squareDimension.width, height * squareDimension.height));
              protected void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   Graphics2D g2D = (Graphics2D)g;
                   Color tempColor = g2D.getColor();
                   for (int i = 0; i < theColoredSquares.length; i++) {
                        ColoredSquare coloredSquare = theColoredSquares;
                        int colorIndex = getNextColorIndex(coloredSquare.theColorIndex);
                        g2D.setColor(COLORS[colorIndex]);
                        g2D.fill(coloredSquare.theRectangle);
                        coloredSquare.theColorIndex = colorIndex;
                   g2D.setColor(tempColor);
              public void run() {
                   try {
                        for (int year = 0; year < 500000; year += 500) {
                             repaint();
                             Thread.sleep(50);
                   } catch (InterruptedException e) {
                        e.printStackTrace();
         public AnimationDemo() {
              super(new BorderLayout());
              final Mozaic mozaic = new Mozaic();
              add(new JScrollPane(mozaic), BorderLayout.CENTER);
              add(new JButton(new AbstractAction("start animation") {
                   public void actionPerformed(ActionEvent e) {
                        new Thread(mozaic, "Animation Thread").start();
              }), BorderLayout.SOUTH);
         public static void main(String[] args) {
              final JFrame frame = new JFrame("Animation Demo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new AnimationDemo());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.setSize(400, 300);
                        frame.show();

  • User inputs and simple anim.

    I know this is a bit basic, but I'm having trouble getting this animation to respond to user inputs. I want the circle to start near the centre of the screen and move up until it hits Y less than 10. Here, I've started the animation thread as a response to the user input, I know this probably isn't the best way to do it.
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.awt.Color;
    import java.awt.*;
    import java.awt.event.*;
    public class basicAnimation extends Applet implements Runnable, KeyListener
    {Thread aThread;
            public int Y;
         public void start()
              if (aThread == null)
              {aThread = new Thread(this);
                   aThread.start();}
         public void stop()
              if (aThread != null)
              {aThread = null;}
         public void run()
              while (true)
                   for(Y=350; Y<10; Y--)
                   {repaint();
                        try { Thread.sleep(100); }
                        catch (InterruptedException e) { }}
         public void init()
         {Y=350;}
         public void paint(Graphics g)
         {g.fillOval (415, Y, 10, 10);}
       public void keyPressed(KeyEvent e)
           int keyCode = e.getKeyCode();
           switch(keyCode)
           {case KeyEvent.VK_SPACE:
                   aThread.start();
                 break;}
       public void keyTyped(KeyEvent e){}
       public void keyReleased(KeyEvent e){}
    }

    Sorry, now that I have gotten a better look at your run() method. You need to replace what you have with the code that I gave you in the previous post. If you run a for loop that is inside the thread, you will change Y from being at the center to Y == 10 in one thread iteration. This is much too fast for what you want to do.
    Don't forget that the thread is executing something like 1000 times every second (depending on how you set it up and the speed of your machine). So if you put a for loop inside the thread you are running the for loop about 1000 times a second when all you meant to do is run through one time.

  • Thread question - unknown method exception!?!

    I am using the following code:
    public void killAnimal(Animal a) //Animal extend Thread
    a.stop();
    a.destroy(); //unknown method exception at this line!
    Basically a thread sends another thread into this method (to kill the Animal/thread when it eats it), but i get an unknown method expection and both threads stop updating
    Any advice

    i have recompiled it. And .destroy() is a built
    method within Thread class is it not?
    And my class EXTENDS Thread so it automaticaly has
    s access to the methods present in the Thread class
    right?. And the fact it compiles and runs means the
    method is detected. Its only when it gets to that
    point that it outputs the exception.Yes but that really wasn't clear from your post. And the name of the class("Animal") is misleading as well.
    The Thread.destroy() method specifically throws the NoSuchMethodError.
    It probably does that because there is no other appropriate unchecked error, although UnsupportedOperationException might be more appropriate.
    >
    Do i need to use .destroy()? Would using .stop() be
    efficient enough? or would that thread still be
    suckin up memory and other system resources?Until the run() method exits the thread exists. How you stop it other than that does not have any impact.

  • Fast animation in a scalable window

    I've written an animator thread, but the Toolkit.sync() method does nothing, so I have to make the thread sleep to wait for the copying of the backbuffer to the screen. The problem is, that the necessary sleeping time is different by different window sizes, and if the thread sleeps too much, the animation is too slow, if it sleeps not enough, the opeerating system (Windows) gets not enough time to do it's job, so the event dispatching slows down, even the mouse cursor moves with latency.
    How could I make this double buffered interactive animation fast but not OS-killer?
    How should I use the Toolkit.sync() method to see any effect of it? Now it seems an empty method to me.

    I use the following approach:
    public void run()
      long wakeTime, sleepTime;
      while(Thread.currentThread() == animateThread)
        wakeTime = System.currentTimeMillis() + FRAME_DURATION;
        calculateFrame();
        repaint();
        sleepTime = wakeTime - System.currentTimeMillis();
        if(sleepTime <= 0)
          Thread.yield();
        else
          Thread.sleep(sleepTime);
    }

  • Applications and Animation

    I want to develop animations for use in an educational environment. I have a drawing program that will produce java animations, but it will not let me control them interactively. What do I need to help me develop interactive Java animations?

    Assuming you have access to the source, you will need to add components that allow you to control the animation thread. Here is a website that will get you started:
    http://java.sun.com/docs/books/tutorial/applet/practical/threadExample.html

  • How to develop a GUI in my game

    Hi,
    I'm working on a multiplayer game in Java 1.4. This is more like a prototype than a commercial quality game, and since the focus of my work is on the networking capabilities of the game, I want to spend the least possible time with mundane things like how to type information and select things on my game...in other words, having a GUI that can provide the game with a menu/submenus, buttons, textfields and the like.
    I've done several Swing applications before but this is different, since the event loop is provided by me (as any other game) and I'm using "active rendering" to display the graphics on screen.
    Does anyone knows how can I use the Swing (or AWT) components in my game?
    Thanks in advance.
    Gabriel

    Hi,
    Thanks for the ansewr. I've been doing an example and I could get my Swing dialog to appear in the screen.
    Below is thesource code of my example. It works but it seems to me that the animation of the square is flickering somehow (I think is double buffered) and the frame rate is somewhat low.
    I would like to know how to improve those things in the example so I could use it in my game.
    Regards,
    Gabriel
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.sun.j3d.utils.timer.*;
    public class ActiveSwingTest implements Runnable {
      static final int VEL = 1;
      // Number of frames with a delay of 0 ms before the animation thread yields
      // to other running threads.
      private static final int NO_DELAYS_PER_YIELD = 16;
      // no. of frames that can be skipped in any one animation loop
      // i.e the games state is updated but not rendered
      private static int MAX_FRAME_SKIPS = 5; // was 2;
      JFrame f;
      JPanel panel;
      Image backBuffer;
      JDialog dialog;
      private long gameStartTime;
      private long prevStatsTime;
      private boolean running;
      private Graphics2D graphics;
      private long period;
      private long framesSkipped = 0;
      int x = 0;
      int y = 0;
      int vx = VEL;
      int vy = VEL;
      public ActiveSwingTest() {
        initGraphics();
      public void initGraphics() {
        panel = new JPanel();
        panel.setPreferredSize(new Dimension(800, 600));
        panel.setFocusable(true);
        panel.requestFocus();
        panel.setIgnoreRepaint(true);
        readyForTermination();
        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(panel);
        f.setIgnoreRepaint(true);
        f.setResizable(false);
        f.pack();
        backBuffer = createBackBuffer();
        if(backBuffer == null) {
          return;
        f.setVisible(true);
      public void run() {
        long timeDiff = 0;
        long overSleepTime = 0L;
        int noDelays = 0;
        long excess = 0L;
        gameStartTime = J3DTimer.getValue();
        prevStatsTime = gameStartTime;
        long beforeTime = gameStartTime;
        running = true;
        graphics = (Graphics2D) backBuffer.getGraphics();
        while(running) {
          update(timeDiff);
          render(graphics);
          paintScreen();
          long afterTime = J3DTimer.getValue();
          timeDiff = afterTime - beforeTime;
          long sleepTime = (period - timeDiff) - overSleepTime;
          if(sleepTime > 0) { // some time left in this cycle
            try {
              Thread.sleep(sleepTime / 1000000L); // nano -> ms
            catch(InterruptedException ex) {}
            overSleepTime = (J3DTimer.getValue() - afterTime) - sleepTime;
          else { // sleepTime <= 0; the frame took longer than the period
            excess -= sleepTime; // store excess time value
            overSleepTime = 0L;
            if(++noDelays >= NO_DELAYS_PER_YIELD) {
              Thread.yield(); // give another thread a chance to run
              noDelays = 0;
          beforeTime = J3DTimer.getValue();
          /* If frame animation is taking too long, update the game state
             without rendering it, to get the updates/sec nearer to
             the required FPS. */
          int skips = 0;
          while((excess > period) && (skips < MAX_FRAME_SKIPS)) {
            excess -= period;
            update(timeDiff); // update state but don't render
            skips++;
          framesSkipped += skips;
        System.exit(0); // so window disappears
      private void showDialogo() {
        if ( dialog == null ) {
          dialog = new JDialog(f, "Example dialog", true);
          final JTextField t = new JTextField("hello");
          JButton bok = new JButton("OK");
          bok.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  System.out.println("text="+t.getText());
                  dialog.setVisible(false);
                  dialog.dispose();
                  dialog = null;
          JButton bcancel = new JButton("Cancel");
          bcancel.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                      dialog.setVisible(false);
          final Container c = dialog.getContentPane();
          c.setLayout(new BorderLayout());
          c.add(t, BorderLayout.CENTER);
          final JPanel buttonPanel = new JPanel();
          buttonPanel.add(bok);
          buttonPanel.add(bcancel);
          c.add(buttonPanel, BorderLayout.PAGE_END);
          dialog.pack();
          dialog.setLocationRelativeTo(f);
          dialog.setVisible(true);
        else {
          dialog.setVisible(true);
      private void paintScreen() {
        // use active rendering to put the buffered image on-screen
        try {
          final Graphics g = panel.getGraphics();
          if(g != null) {
            g.drawImage(backBuffer, 0, 0, null);
          g.dispose();
        catch(Exception e) {
          System.out.println("Graphics context error: " + e);
      private Image createBackBuffer() {
        final Image dbImage = panel.createImage(800, 600);
        if(dbImage == null) {
          System.out.println("could not create the backbuffer image!");
        return dbImage;
      private void readyForTermination() {
        panel.addKeyListener(new KeyAdapter() {
          // listen for esc, q, end, ctrl-c on the canvas to
          // allow a convenient exit from the full screen configuration
          public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            if((keyCode == KeyEvent.VK_ESCAPE) || (keyCode == KeyEvent.VK_Q) ||
               (keyCode == KeyEvent.VK_END) ||
               ((keyCode == KeyEvent.VK_C) && e.isControlDown())) {
              running = false;
            else if ( keyCode == KeyEvent.VK_D ) {
              showDialogo();
      private void update(long dt) {
        x += vx;
        y += vy;
        if ( x < 0 ) {
          x = 0;
          vx = VEL;
        else if ( x > 700 ) {
          x = 700;
          vx = -VEL;
        if ( y < 0 ) {
          y = 0;
          vy = VEL;
        else if ( y > 500 ) {
          y = 500;
          vy = -VEL;
      private void render(Graphics2D g) {
        g.setColor(Color.RED);
        g.fillRect(0, 0, 800, 600);
        g.setColor(Color.WHITE);
        g.fillRect(x, y, 100, 100);
      public static void main(String[] args) {
        ActiveSwingTest test = new ActiveSwingTest();
        new Thread(test).start();
    }

  • Bouncing Ball without Main Method

    Hi. I needed to reserch on the Internet sample code for a blue bouncing ball which I did below. However, I try coding a main class to start the GUI applet and it's not working. How can I create the appropriate class that would contain the main method to start this particular application which the author did not provide? The actual applet works great and matches the objective of my research (http://www.terrence.com/java/ball.html). The DefaultCloseOperation issues an error so that's why is shown as remarks // below. Then the code in the Ball.java class issues some warning about components being deprecated as shown below. Thank you for your comments and suggestions.
    Compiling 2 source files to C:\Documents and Settings\Fausto Rivera\My Documents\NetBeansProjects\Rivera_F_IT271_0803B_01_PH3_DB\build\classes
    C:\Documents and Settings\Fausto Rivera\My Documents\NetBeansProjects\Rivera_F_IT271_0803B_01_PH3_DB\src\Ball.java:32: warning: [deprecation] size() in java.awt.Component has been deprecated
        size = this.size();
    C:\Documents and Settings\Fausto Rivera\My Documents\NetBeansProjects\Rivera_F_IT271_0803B_01_PH3_DB\src\Ball.java:93: warning: [deprecation] mouseDown(java.awt.Event,int,int) in java.awt.Component has been deprecated
      public boolean mouseDown(Event e, int x, int y) {
    2 warnings
    import javax.swing.*;
    public class BallMain {
    * @param args the command line arguments
    public static void main(String[] args) {
    Ball ball = new Ball();
    //ball.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    ball.setSize( 500, 175 ); // set frame size
    ball.setVisible( true ); // display frame
    import java.awt.*;*
    *import java.applet.*;
    import java.util.Vector;
    // Java Bouncing Ball
    // Terrence Ma
    // Modified from Java Examples in a Nutshell
    public class Ball extends Applet implements Runnable {
    int x = 150, y = 100, r=50; // Position and radius of the circle
    int dx = 8, dy = 5; // Trajectory of circle
    Dimension size; // The size of the applet
    Image buffer; // The off-screen image for double-buffering
    Graphics bufferGraphics; // A Graphics object for the buffer
    Thread animator; // Thread that performs the animation
    boolean please_stop; // A flag asking animation thread to stop
    /** Set up an off-screen Image for double-buffering */
    public void init() {
    size = this.size();
    buffer = this.createImage(size.width, size.height);
    bufferGraphics = buffer.getGraphics();
    /** Draw the circle at its current position, using double-buffering */
    public void paint(Graphics g) {
    // Draw into the off-screen buffer.
    // Note, we could do even better clipping by setting the clip rectangle
    // of bufferGraphics to be the same as that of g.
    // In Java 1.1: bufferGraphics.setClip(g.getClip());
    bufferGraphics.setColor(Color.white);
    bufferGraphics.fillRect(0, 0, size.width, size.height); // clear the buffer
    bufferGraphics.setColor(Color.blue);
    bufferGraphics.fillOval(x-r, y-r, r*2, r*2); // draw the circle
    // Then copy the off-screen buffer onto the screen
    g.drawImage(buffer, 0, 0, this);
    /** Don't clear the screen; just call paint() immediately
    * It is important to override this method like this for double-buffering */
    public void update(Graphics g) { paint(g); }
    /** The body of the animation thread */
    public void run() {
    while(!please_stop) {
    // Bounce the circle if we've hit an edge.
    if ((x - r + dx < 0) || (x + r + dx > size.width)) dx = -dx;
    if ((y - r + dy < 0) || (y + r + dy > size.height)) dy = -dy;
    // Move the circle.
    x += dx; y += dy;
    // Ask the browser to call our paint() method to redraw the circle
    // at its new position. Tell repaint what portion of the applet needs
    // be redrawn: the rectangle containing the old circle and the
    // the rectangle containing the new circle. These two redraw requests
    // will be merged into a single call to paint()
    repaint(x-r-dx, y-r-dy, 2*r, 2*r); // repaint old position of circle
    repaint(x-r, y-r, 2*r, 2*r); // repaint new position of circle
    // Now pause 50 milliseconds before drawing the circle again.
    try { Thread.sleep(50); } catch (InterruptedException e) { ; }
    animator = null;
    /** Start the animation thread */
    public void start() {
    if (animator == null) {
    please_stop = false;
    animator = new Thread(this);
    animator.start();
    /** Stop the animation thread */
    public void stop() { please_stop = true; }
    /** Allow the user to start and stop the animation by clicking */
    public boolean mouseDown(Event e, int x, int y) {
    if (animator != null) please_stop = true; // if running request a stop
    else start(); // otherwise start it.
    return true;
    }

    FRiveraJr wrote:
    I believe that I stated that this not my code and it was code that I researched.and why the hll should this matter at all? If you want help here from volunteers, your code or not, don't you think that you should take the effort to format it properly?

  • Problem converting a (working) Java program into an applet

    When I'm trying to access an Image through a call to :
    mediaTracker = new MediaTracker(this);
    backGroundImage = getImage(getDocumentBase(), "background.gif");
    mediaTracker.addImage(backGroundImage, 0);
    I'm getting a nullPointerException as a result of the call to getDocumentBase() :
    C:\Chantier\Java\BallsApplet
    AppletViewer testBallsApplet.htmljava.lang.NullPointerException
    at java.applet.Applet.getDocumentBase(Applet.java:125)
    at Balls.<init>(Balls.java:84)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
    orAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
    onstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
    at java.lang.Class.newInstance0(Class.java:296)
    at java.lang.Class.newInstance(Class.java:249)
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:548)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:477)
    at sun.applet.AppletPanel.run(AppletPanel.java:290)
    at java.lang.Thread.run(Thread.java:536)
    It seems very weird to me... :-/
    (all the .gif files are in the same directory than the .class files)
    The problem appears with AppletViewer trying to open an HTML file
    containing :
    <HTML>
    <APPLET CODE="Balls.class" WIDTH=300 HEIGHT=211>
    </APPLET>
    </HTML>
    (I tried unsuccessfully the CODEBASE and ARCHIVE attributes, with and without putting the .gif and .class into a .jar file)
    I can't find the solution by myself, so, I'd be very glad if someone could help
    me with this... Thank you very much in advance ! :-)
    You'll find below the source of a small game that I wrote and debugged (without
    problem) and that I'm now (unsuccessfully) trying to convert into an Applet :
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.URL;
    public class Balls extends java.applet.Applet implements Runnable, KeyListener
    private Image offScreenImage;
    private Image backGroundImage;
    private Image[] gifImages = new Image[6];
    private Image PressStart ;
    private Sprite pressStartSprite = null ;
    private Image YouLose ;
    private Sprite YouLoseSprite = null ;
    private Image NextStage ;
    private Sprite NextStageSprite = null ;
    private Image GamePaused ;
    private Sprite GamePausedSprite = null ;
    //offscreen graphics context
    private Graphics offScreenGraphicsCtx;
    private Thread animationThread;
    private MediaTracker mediaTracker;
    private SpriteManager spriteManager;
    //Animation display rate, 12fps
    private int animationDelay = 83;
    private Random rand = new Random(System.currentTimeMillis());
    private int message = 0 ; // 0 = no message (normal playing phase)
    // 1 = press space to start
    // 2 = press space for next level
    // 3 = game PAUSED, press space to unpause
    // 4 = You LOSE
    public static void main(String[] args)
    try
    new Balls() ;
    catch (java.net.MalformedURLException e)
    System.out.println(e);
    }//end main
    public void start()
    //Create and start animation thread
    animationThread = new Thread(this);
    animationThread.start();
    public void init()
    try
    new Balls() ;
    catch (java.net.MalformedURLException e)
    System.out.println(e);
    public Balls() throws java.net.MalformedURLException
    {//constructor
    // Load and track the images
    mediaTracker = new MediaTracker(this);
    backGroundImage = getImage(getDocumentBase(), "background.gif");
    mediaTracker.addImage(backGroundImage, 0);
    PressStart = getImage(getDocumentBase(), "press_start.gif");
    mediaTracker.addImage(PressStart, 0);
    NextStage = getImage(getDocumentBase(), "stage_complete.gif");
    mediaTracker.addImage(NextStage, 0);
    GamePaused = getImage(getDocumentBase(), "game_paused.gif");
    mediaTracker.addImage(GamePaused, 0);
    YouLose = getImage(getDocumentBase(), "you_lose.gif");
    mediaTracker.addImage(YouLose, 0);
    //Get and track 6 images to use
    // for sprites
    gifImages[0] = getImage(getDocumentBase(), "blueball.gif");
    mediaTracker.addImage(gifImages[0], 0);
    gifImages[1] = getImage(getDocumentBase(), "redball.gif");
    mediaTracker.addImage(gifImages[1], 0);
    gifImages[2] = getImage(getDocumentBase(), "greenball.gif");
    mediaTracker.addImage(gifImages[2], 0);
    gifImages[3] = getImage(getDocumentBase(), "yellowball.gif");
    mediaTracker.addImage(gifImages[3], 0);
    gifImages[4] = getImage(getDocumentBase(), "purpleball.gif");
    mediaTracker.addImage(gifImages[4], 0);
    gifImages[5] = getImage(getDocumentBase(), "orangeball.gif");
    mediaTracker.addImage(gifImages[5], 0);
    //Block and wait for all images to
    // be loaded
    try {
    mediaTracker.waitForID(0);
    }catch (InterruptedException e) {
    System.out.println(e);
    }//end catch
    //Base the Frame size on the size
    // of the background image.
    //These getter methods return -1 if
    // the size is not yet known.
    //Insets will be used later to
    // limit the graphics area to the
    // client area of the Frame.
    int width = backGroundImage.getWidth(this);
    int height = backGroundImage.getHeight(this);
    //While not likely, it may be
    // possible that the size isn't
    // known yet. Do the following
    // just in case.
    //Wait until size is known
    while(width == -1 || height == -1)
    System.out.println("Waiting for image");
    width = backGroundImage.getWidth(this);
    height = backGroundImage.getHeight(this);
    }//end while loop
    //Display the frame
    setSize(width,height);
    setVisible(true);
    //setTitle("Balls");
    //Anonymous inner class window
    // listener to terminate the
    // program.
    this.addWindowListener
    (new WindowAdapter()
    {public void windowClosing(WindowEvent e){System.exit(0);}});
    // Add a key listener for keyboard management
    this.addKeyListener(this);
    }//end constructor
    public void run()
    Point center_place = new Point(
    backGroundImage.getWidth(this)/2-PressStart.getWidth(this)/2,
    backGroundImage.getHeight(this)/2-PressStart.getHeight(this)/2) ;
    pressStartSprite = new Sprite(this, PressStart, center_place, new Point(0, 0),true);
    center_place = new Point(
    backGroundImage.getWidth(this)/2-NextStage.getWidth(this)/2,
    backGroundImage.getHeight(this)/2-NextStage.getHeight(this)/2) ;
    NextStageSprite = new Sprite(this, NextStage, center_place, new Point(0, 0),true);
    center_place = new Point(
    backGroundImage.getWidth(this)/2-GamePaused.getWidth(this)/2,
    backGroundImage.getHeight(this)/2-GamePaused.getHeight(this)/2) ;
    GamePausedSprite = new Sprite(this, GamePaused, center_place, new Point(0, 0),true);
    center_place = new Point(
    backGroundImage.getWidth(this)/2-YouLose.getWidth(this)/2,
    backGroundImage.getHeight(this)/2-YouLose.getHeight(this)/2) ;
    YouLoseSprite = new Sprite(this, YouLose, center_place, new Point(0, 0),true);
    BackgroundImage bgimage = new BackgroundImage(this, backGroundImage) ;
    for (;;) // infinite loop
    long time = System.currentTimeMillis();
    message = 1 ; // "press start to begin"
    while (message != 0)
    repaint() ;
    try
    time += animationDelay;
    Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
    catch (InterruptedException e)
    System.out.println(e);
    }//end catch
    boolean you_lose = false ;
    for (int max_speed = 7 ; !you_lose && max_speed < 15 ; max_speed++)
    for (int difficulty = 2 ; !you_lose && difficulty < 14 ; difficulty++)
    boolean unfinished_stage = true ;
    spriteManager = new SpriteManager(bgimage);
    spriteManager.setParameters(difficulty, max_speed) ;
    //Create 15 sprites from 6 gif
    // files.
    for (int cnt = 0; cnt < 15; cnt++)
    if (cnt == 0)
    Point position = new Point(
    backGroundImage.getWidth(this)/2-gifImages[0].getWidth(this)/2,
    backGroundImage.getHeight(this)/2-gifImages[0].getHeight(this)/2) ;
    spriteManager.addSprite(makeSprite(position, 0, false));
    else
    Point position = spriteManager.
    getEmptyPosition(new Dimension(gifImages[0].getWidth(this),
    gifImages[0].getHeight(this)));
    if (cnt < difficulty)
    spriteManager.addSprite(makeSprite(position, 1, true));
    else
    spriteManager.addSprite(makeSprite(position, 2, true));
    }//end for loop
    time = System.currentTimeMillis();
    while (!spriteManager.getFinishedStage() && !spriteManager.getGameOver())
    // Loop, sleep, and update sprite
    // positions once each 83
    // milliseconds
    spriteManager.update();
    repaint();
    try
    time += animationDelay;
    Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
    catch (InterruptedException e)
    System.out.println(e);
    }//end catch
    }//end while loop
    if (spriteManager.getGameOver())
    message = 4 ;
    while (message != 0)
    spriteManager.update();
    repaint();
    try
    time += animationDelay;
    Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
    catch (InterruptedException e)
    System.out.println(e);
    }//end catch
    you_lose = true ;
    if (spriteManager.getFinishedStage())
    message = 2 ;
    while (message != 0)
    spriteManager.update();
    repaint();
    try
    time += animationDelay;
    Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
    catch (InterruptedException e)
    System.out.println(e);
    }//end catch
    } // end for difficulty loop
    } // end for max_speed
    } // end infinite loop
    }//end run method
    private Sprite makeSprite(Point position, int imageIndex, boolean wind)
    return new Sprite(
    this,
    gifImages[imageIndex],
    position,
    new Point(rand.nextInt() % 5,
    rand.nextInt() % 5),
    wind);
    }//end makeSprite()
    //Overridden graphics update method
    // on the Frame
    public void update(Graphics g)
    //Create the offscreen graphics
    // context
    if (offScreenGraphicsCtx == null)
    offScreenImage = createImage(getSize().width,
    getSize().height);
    offScreenGraphicsCtx = offScreenImage.getGraphics();
    }//end if
    if (message == 0)
    // Draw the sprites offscreen
    spriteManager.drawScene(offScreenGraphicsCtx);
    else if (message == 1)
    pressStartSprite.drawSpriteImage(offScreenGraphicsCtx);
    else if (message == 2)
    NextStageSprite.drawSpriteImage(offScreenGraphicsCtx);
    else if (message == 3)
    GamePausedSprite.drawSpriteImage(offScreenGraphicsCtx);
    else if (message == 4)
    YouLoseSprite.drawSpriteImage(offScreenGraphicsCtx);
    // Draw the scene onto the screen
    if(offScreenImage != null)
    g.drawImage(offScreenImage, 0, 0, this);
    }//end if
    }//end overridden update method
    //Overridden paint method on the
    // Frame
    public void paint(Graphics g)
    //Nothing required here. All
    // drawing is done in the update
    // method above.
    }//end overridden paint method
    // Methods to handle Keyboard event
    public void keyPressed(KeyEvent evt)
    int key = evt.getKeyCode(); // Keyboard code for the pressed key.
    if (key == KeyEvent.VK_SPACE)
    if (message != 0)
    message = 0 ;
    else
    message = 3 ;
    if (key == KeyEvent.VK_LEFT)
    if (spriteManager != null)
    spriteManager.goLeft() ;
    else if (key == KeyEvent.VK_RIGHT)
    if (spriteManager != null)
    spriteManager.goRight() ;
    else if (key == KeyEvent.VK_UP)
    if (spriteManager != null)
    spriteManager.goUp() ;
    else if (key == KeyEvent.VK_DOWN)
    if (spriteManager != null)
    spriteManager.goDown() ;
    if (spriteManager != null)
    spriteManager.setMessage(message) ;
    public void keyReleased(KeyEvent evt)
    public void keyTyped(KeyEvent e)
    char key = e.getKeyChar() ;
    //~ if (key == 's')
    //~ stop = true ;
    //~ else if (key == 'c')
    //~ stop = false ;
    //~ spriteManager.setStop(stop) ;
    }//end class Balls
    //===================================//
    class BackgroundImage
    private Image image;
    private Component component;
    private Dimension size;
    public BackgroundImage(
    Component component,
    Image image)
    this.component = component;
    size = component.getSize();
    this.image = image;
    }//end construtor
    public Dimension getSize(){
    return size;
    }//end getSize()
    public Image getImage(){
    return image;
    }//end getImage()
    public void setImage(Image image){
    this.image = image;
    }//end setImage()
    public void drawBackgroundImage(Graphics g)
    g.drawImage(image, 0, 0, component);
    }//end drawBackgroundImage()
    }//end class BackgroundImage
    //===========================
    class SpriteManager extends Vector
    private BackgroundImage backgroundImage;
    private boolean finished_stage = false ;
    private boolean game_over = false ;
    private int difficulty ;
    private int max_speed ;
    public boolean getFinishedStage()
    finished_stage = true ;
    for (int cnt = difficulty ; cnt < size(); cnt++)
    Sprite sprite = (Sprite)elementAt(cnt);
    if (!sprite.getEaten())
    finished_stage = false ;
    return finished_stage ;
    public boolean getGameOver() {return game_over ;}
    public void setParameters(int diff, int speed)
    difficulty = diff ;
    max_speed = speed ;
    finished_stage = false ;
    game_over = false ;
    Sprite sprite;
    for (int cnt = 0;cnt < size(); cnt++)
    sprite = (Sprite)elementAt(cnt);
    sprite.setSpeed(max_speed) ;
    public SpriteManager(BackgroundImage backgroundImage)
    this.backgroundImage = backgroundImage ;
    }//end constructor
    public Point getEmptyPosition(Dimension spriteSize)
    Rectangle trialSpaceOccupied = new Rectangle(0, 0,
    spriteSize.width,
    spriteSize.height);
    Random rand = new Random(System.currentTimeMillis());
    boolean empty = false;
    int numTries = 0;
    // Search for an empty position
    while (!empty && numTries++ < 100)
    // Get a trial position
    trialSpaceOccupied.x =
    Math.abs(rand.nextInt() %
    backgroundImage.
    getSize().width);
    trialSpaceOccupied.y =
    Math.abs(rand.nextInt() %
    backgroundImage.
    getSize().height);
    // Iterate through existing
    // sprites, checking if position
    // is empty
    boolean collision = false;
    for(int cnt = 0;cnt < size(); cnt++)
    Rectangle testSpaceOccupied = ((Sprite)elementAt(cnt)).getSpaceOccupied();
    if (trialSpaceOccupied.intersects(testSpaceOccupied))
    collision = true;
    }//end if
    }//end for loop
    empty = !collision;
    }//end while loop
    return new Point(trialSpaceOccupied.x, trialSpaceOccupied.y);
    }//end getEmptyPosition()
    public void update()
    Sprite sprite;
    // treat special case of sprite #0 (the player)
    sprite = (Sprite)elementAt(0);
    sprite.updatePosition() ;
    int hitIndex = testForCollision(sprite);
    if (hitIndex != -1)
    if (hitIndex < difficulty)
    { // if player collides with an hunter (red ball), he loose
    sprite.setEaten() ;
    game_over = true ;
    else
    // if player collides with an hunted (green ball), he eats the green
    ((Sprite)elementAt(hitIndex)).setEaten() ;
    //Iterate through sprite list
    for (int cnt = 1;cnt < size(); cnt++)
    sprite = (Sprite)elementAt(cnt);
    //Update a sprite's position
    sprite.updatePosition();
    //Test for collision. Positive
    // result indicates a collision
    hitIndex = testForCollision(sprite);
    if (hitIndex >= 0)
    //a collision has occurred
    bounceOffSprite(cnt,hitIndex);
    }//end if
    }//end for loop
    }//end update
    public void setMessage(int message)
    Sprite sprite;
    //Iterate through sprite list
    for (int cnt = 0;cnt < size(); cnt++)
    sprite = (Sprite)elementAt(cnt);
    //Update a sprite's stop status
    sprite.setMessage(message);
    }//end for loop
    }//end update
    public void goLeft()
    Sprite sprite = (Sprite)elementAt(0);
    sprite.goLeft() ;
    public void goRight()
    Sprite sprite = (Sprite)elementAt(0);
    sprite.goRight() ;
    public void goUp()
    Sprite sprite = (Sprite)elementAt(0);
    sprite.goUp() ;
    public void goDown()
    Sprite sprite = (Sprite)elementAt(0);
    sprite.goDown() ;
    private int testForCollision(Sprite testSprite)
    //Check for collision with other
    // sprites
    Sprite sprite;
    for (int cnt = 0;cnt < size(); cnt++)
    sprite = (Sprite)elementAt(cnt);
    if (sprite == testSprite)
    //don't check self
    continue;
    //Invoke testCollision method
    // of Sprite class to perform
    // the actual test.
    if (testSprite.testCollision(sprite))
    //Return index of colliding
    // sprite
    return cnt;
    }//end for loop
    return -1;//No collision detected
    }//end testForCollision()
    private void bounceOffSprite(int oneHitIndex, int otherHitIndex)
    //Swap motion vectors for
    // bounce algorithm
    Sprite oneSprite = (Sprite)elementAt(oneHitIndex);
    Sprite otherSprite = (Sprite)elementAt(otherHitIndex);
    Point swap = oneSprite.getMotionVector();
    oneSprite.setMotionVector(otherSprite.getMotionVector());
    otherSprite.setMotionVector(swap);
    }//end bounceOffSprite()
    public void drawScene(Graphics g)
    //Draw the background and erase
    // sprites from graphics area
    //Disable the following statement
    // for an interesting effect.
    backgroundImage.drawBackgroundImage(g);
    //Iterate through sprites, drawing
    // each sprite
    for (int cnt = 0;cnt < size(); cnt++)
    ((Sprite)elementAt(cnt)).drawSpriteImage(g);
    }//end drawScene()
    public void addSprite(Sprite sprite)
    addElement(sprite);
    }//end addSprite()
    }//end class SpriteManager
    //===================================//
    class Sprite
    private Component component;
    private Image image;
    private Rectangle spaceOccupied;
    private Point motionVector;
    private Rectangle bounds;
    private Random rand;
    private int message = 0 ; // number of message currently displayed (0 means "no message" = normal game)
    private int max_speed = 7 ;
    private boolean eaten = false ; // when a green sprite is eaten, it is no longer displayed on screen
    private boolean wind = true ;
    private boolean go_left = false ;
    private boolean go_right = false ;
    private boolean go_up = false ;
    private boolean go_down = false ;
    public Sprite(Component component,
    Image image,
    Point position,
    Point motionVector,
    boolean Wind
    //Seed a random number generator
    // for this sprite with the sprite
    // position.
    rand = new Random(position.x);
    this.component = component;
    this.image = image;
    setSpaceOccupied(new Rectangle(
    position.x,
    position.y,
    image.getWidth(component),
    image.getHeight(component)));
    this.motionVector = motionVector;
    this.wind = Wind ;
    //Compute edges of usable graphics
    // area in the Frame.
    int topBanner = ((Container)component).getInsets().top;
    int bottomBorder = ((Container)component).getInsets().bottom;
    int leftBorder = ((Container)component).getInsets().left;
    int rightBorder = ((Container)component).getInsets().right;
    bounds = new Rectangle( 0 + leftBorder, 0 + topBanner
    , component.getSize().width - (leftBorder + rightBorder)
    , component.getSize().height - (topBanner + bottomBorder));
    }//end constructor
    public void setMessage(int message_number)
    message = message_number ;
    public void setSpeed(int speed)
    max_speed = speed ;
    public void goLeft()
    go_left = true ;
    public void goRight()
    go_right = true ;
    public void goUp()
    go_up = true ;
    public void goDown()
    go_down = true ;
    public void setEaten()
    eaten = true ;
    setSpaceOccupied(new Rectangle(4000,4000,0,0)) ;
    public boolean getEaten()
    return eaten ;
    public Rectangle getSpaceOccupied()
    return spaceOccupied;
    }//end getSpaceOccupied()
    void setSpaceOccupied(Rectangle spaceOccupied)
    this.spaceOccupied = spaceOccupied;
    }//setSpaceOccupied()
    public void setSpaceOccupied(
    Point position){
    spaceOccupied.setLocation(
    position.x, position.y);
    }//setSpaceOccupied()
    public Point getMotionVector(){
    return motionVector;
    }//end getMotionVector()
    public void setMotionVector(
    Point motionVector){
    this.motionVector = motionVector;
    }//end setMotionVector()
    public void setBounds(Rectangle bounds)
    this.bounds = bounds;
    }//end setBounds()
    public void updatePosition()
    Point position = new Point(spaceOccupied.x, spaceOccupied.y);
    if (message != 0)
    return ;
    //Insert random behavior. During
    // each update, a sprite has about
    // one chance in 10 of making a
    // random change to its
    // motionVector. When a change
    // occurs, the motionVector
    // coordinate values are forced to
    // fall between -7 and 7. This
    // puts a cap on the maximum speed
    // for a sprite.
    if (!wind)
    if (go_left)
    motionVector.x -= 2 ;
    if (motionVector.x < -15)
    motionVector.x = -14 ;
    go_left = false ;
    if (go_right)
    motionVector.x += 2 ;
    if (motionVector.x > 15)
    motionVector.x = 14 ;
    go_right = false ;
    if (go_up)
    motionVector.y -= 2 ;
    if (motionVector.y < -15)
    motionVector.y = -14 ;
    go_up = false ;
    if (go_down)
    motionVector.y += 2 ;
    if (motionVector.y > 15)
    motionVector.y = 14 ;
    go_down = false ;
    else if(rand.nextInt() % 7 == 0)
    Point randomOffset =
    new Point(rand.nextInt() % 3,
    rand.nextInt() % 3);
    motionVector.x += randomOffset.x;
    if(motionVector.x >= max_speed)
    motionVector.x -= max_speed;
    if(motionVector.x <= -max_speed)
    motionVector.x += max_speed ;
    motionVector.y += randomOffset.y;
    if(motionVector.y >= max_speed)
    motionVector.y -= max_speed;
    if(motionVector.y <= -max_speed)
    motionVector.y += max_speed;
    }//end if
    //Move the sprite on the screen
    position.translate(motionVector.x, motionVector.y);
    //Bounce off the walls
    boolean bounceRequired = false;
    Point tempMotionVector = new Point(
    motionVector.x,
    motionVector.y);
    //Handle walls in x-dimension
    if (position.x < bounds.x)
    bounceRequired = true;
    position.x = bounds.x;
    //reverse direction in x
    tempMotionVector.x = -tempMotionVector.x;
    else if ((position.x + spaceOccupied.width) > (bounds.x + bounds.width))
    bounceRequired = true;
    position.x = bounds.x +
    bounds.width -
    spaceOccupied.width;
    //reverse direction in x
    tempMotionVector.x =
    -tempMotionVector.x;
    }//end else if
    //Handle walls in y-dimension
    if (position.y < bounds.y)
    bounceRequired = true;
    position.y = bounds.y;
    tempMotionVector.y = -tempMotionVector.y;
    else if ((position.y + spaceOccupied.height)
    > (bounds.y + bounds.height))
    bounceRequired = true;
    position.y = bounds.y +
    bounds.height -
    spaceOccupied.height;
    tempMotionVector.y =
    -tempMotionVector.y;
    }//end else if
    if(bounceRequired)
    //save new motionVector
    setMotionVector(
    tempMotionVector);
    //update spaceOccupied
    setSpaceOccupied(position);
    }//end updatePosition()
    public void drawSpriteImage(Graphics g)
    if (!eaten)
    g.drawImage(image,
    spaceOccupied.x,
    spaceOccupied.y,
    component);
    }//end drawSpriteImage()
    public boolean testCollision(Sprite testSprite)
    //Check for collision with
    // another sprite
    if (testSprite != this)
    return spaceOccupied.intersects(
    testSprite.getSpaceOccupied());
    }//end if
    return false;
    }//end testCollision
    }//end Sprite class
    //===================================//
    Thanks for your help...

    Sorry,
    Can you tell me how do you solve it because I have got the same problem.
    Can you indicate me the topic where did you find solution.
    Thank in advance.

Maybe you are looking for

  • Regarding the Smartforms

    HI All, Its an very urgent requirement . I have to create the second page in smartforms in that i need to print the text , so iam creating the second page in that i placed the normal window , in that i created the text , but in attributes i keeping b

  • Create LDAP directory for company address book

    What is the easiest way to create an LDAP company directory. OSX Server is clear on how to access such an entity, but I cannot find any way to create one and populate it. I have seen some things that require UNIX commands, which I'm not comfortable w

  • On Mac OS X where does Firefox keep these following files?

    Where are these files kept? Temporary Internet Files? Cookies? Browser history? Cache?

  • Sync albums from multiple libraries??

    Hi, I use multiple iPhoto libraries to faster handle my photos with the app, iPhoto Buddy. Does anyone know how I can sync albums from different libraries with my iPod photo?? I'm out of ideas... Any help is greatly appreciated. -SS

  • Frieght Charges in Scheduling Aggreement

    HI ALL, Please can any one tell me where exactly we have to update the Frieght charges, CVD and other Conditions in a Scheduling Aggreement for an IMPORT Vendor. Pls let me know. Regards, Nagaraj S