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?

Similar Messages

  • Running a java application without a main method

    class MainMethodNot
        static
            System.out.println("This java program have run without the run method");
            System.exit(0);
    }The reason this works is that static initialization blocks get executed as soon as the class is loaded, even before the main method is called. During run time JVM will search for the main method after exiting from this block. If it does not find the main method, it throws an exception. To avoid the exception System.exit(0); statement is used which terminates the program at the end of the static block itself.
    got it from http://www.java-tips.org/

    This has been published many times on this forum. What is your question?

  • How to repaint a JPanel in bouncing balls game?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package fuck;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("fuck");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            final JPanel canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  And when i press start button:
    Exception in thread "Thread-2" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-4" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    and line 153 is: balls.canvas.repaint(); in Method run() in First class.
    Please help.

    public RepaintManager manager;
    public BouncingBalls() {
            manager = new RepaintManager();
            manager.addDirtyRegion(canvas, 0, 0,canvas.getSize().width, canvas.getSize().height);
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.manager.paintDirtyRegions(); //////// line 153
       but when push start:
    Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    i'm newbie with Concurrency and i cant handle this exceptons.
    Is this the right way to do repaint?

  • Bouncing ball question

    Hi, I'm new to the forums and really new to java and I was wondering if anyone could help me with a simple java program that I'm writing.
    It deals simply with a bouncing ball (yes I know there's a topics on this one heh) that bounces aimlessly inside a drawing window.
    Here's my problem:
    I can make the ball bounce off two boundaries (top and right, left and bottom, right and bottom etc.) but when the ball reaches the 3rd boundary it just passes through it. It wont bounce off opposite sides (left and right, top and bottom) it only bounces off the first.
    I believe it has something to do with my if statements under the move method.
    I need to make some kind of loop so it keeps checking if the ball comes to a new boundary.
    Right now it's only checking it once and after it bounces the ball one time thats it.
    (I've tested all the boundaries to see if they bounce the ball and they all do, its just I can't bounce it more than 2 times)
    I'm stuck on how to write this loop statement. Any help would be greatly appreciated! Thanks.
    My code (If this isnt enough let me know please):
    (BallTester.java)
    import element.*;
    public class BallTester{
    public static void main(String[] args){
    int width = 500;
    int height = 400;
    DrawingWindow d = new DrawingWindow(width,height);      
    Ball b = new Ball(70,30,width,height);
    b.send(d);                                   
    (Ball.java)
    import element.*;
    public class Ball{
    int base; // center line of where the circle starts
    int size; // radius of circle
    int xPos,yPos; // circle ctr
    Circle c;
         int width, height;
         int dx,dy;
    public Ball(int base, int size, int width, int height) {
              this.base = base;
    this.size = size;
    c = new Circle(50,base,size);
              this.width = width; this.height = height;
              xPos = 50;
              yPos = base;
    public void drawOn(DrawingWindow d){
              //draws the circle
              c.drawOn(d);
    public void clearOn(DrawingWindow d){
              d.invertMode(); // black-> white
              drawOn(d); //redraw in white: erase!
              d.invertMode(); // white -> black
    public void move(int dx, int dy){
              //Sets boundaries for x values
              if((xPos<=size)||(xPos>=width-size)){
              dx = -dx;
              else
              xPos += dx;
              //Sets boundaries for y values
              if((yPos<=size)||(yPos>=height-size)){
              dy = -dy;
              else     
              yPos += dy;
              c.move(dx,dy);
    public void send(DrawingWindow d){
              Waiting w = new Waiting();
    //This below keeps the ball drawing up until j = width)
    for(int j = 0; j < width; j++){
              move(6,-3); // moves the circle based on dx, dy values
              this.drawOn(d);
    w.snooze(60);
    this.clearOn(d);}

    You don't need a loop to check - you just need to check every loop (before you repaint).
    I created an example for you. If this assignment is homework, don't hand it in - use it as a reference. Try to understand what's going on in the code and why it works.
    import java.awt.*;
    import javax.swing.*;
    public class Test extends JFrame {
        public Test () {
            getContentPane ().setLayout (new BorderLayout ());
            getContentPane ().add (new TestPanel ());
            setDefaultCloseOperation (DISPOSE_ON_CLOSE);
            setTitle ("Test");
            pack ();
            setLocationRelativeTo (null);
            setVisible (true);
        public static void main (String[] parameters) {
            new Test ();
        private class TestPanel extends JPanel {
            private Ball ball;
            public TestPanel () {
                ball = new Ball ();
                Thread painter = new Thread (new Runnable () {
                    public void run () {
                        while (true) {
                            try {
                                Thread.sleep (20);
                            } catch (InterruptedException exception) {}
                            repaint ();
                painter.setDaemon (true);
                painter.start ();
            public Dimension getPreferredSize () {
                return new Dimension (300, 200);
            public void paintComponent (Graphics g) {
                super.paintComponent (g);
                ball.move (getWidth (), getHeight ());
                ball.paint (g);
            private class Ball {
                private static final int W = 10;
                private static final int H = 10;
                private int x;
                private int y;
                private int dx;
                private int dy;
                public Ball () {
                    x = 0;
                    y = 0;
                    dx = 2;
                    dy = 2;
                public void move (int width, int height) {
                    int x = this.x + dx;
                    int y = this.y + dy;
                    if ((x < 0) || (x + W > width)) {
                        dx = -dx;
                        x = this.x + dx;
                    if ((y < 0) || (y + H > height)) {
                        dy = -dy;
                        y = this.y + dy;
                    this.x = x;
                    this.y = y;
                public void paint (Graphics g) {
                    g.fillOval (x, y, W, H);
    }

  • Java Bouncing Balls Threads problem?

    Hello,
    I am working on a homework assignment to represent a java applet with some bouncing balls inside. So far so good. The balls bounce and behave as they are supposed. The only thing is that I want to make 2 buttons, Start and Stop (this is not part of the assignment, but my free will to provide some extra stuff :) ) . I am implementing Runnable for the animation and ActionListener for the buttons. I did research on threading, but somehow I am still not getting quite the result I want. The applet is not displaying my buttons (I guess I am not implementing them correctly) and I dont know whether I have synchronized the threads correctly as well. So, I am asking for some guidance how can I do this? Thanks in advance!
    As a remark, I am new to Java, as I am just starting to learn it and this is my first assignment.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    public class Balls extends JApplet implements Runnable, ActionListener
         Thread runner = null;     
         Image img;
        Graphics gr;          
        BallCollision ball[];
        Balls can;
        JButton stopButton;
        JButton startButton;
        JPanel controls;
        boolean stop,start;
        //field for 10 balls
        static final int MAX=10;
         public void init()
              setSize(800,600);
              img = createImage(size().width,size().height);
              gr = img.getGraphics();     
              startButton = new JButton("Start");
              stopButton = new JButton("Stop");
              stopButton.addActionListener(this);
              startButton.addActionListener(this);
              controls = new JPanel();
              controls.setLayout(new FlowLayout());
              controls.add(startButton);
              controls.add(stopButton);
              //new Thread(this).start();
              ball = new BallCollision[MAX];
              int w=size().width;
              int h=size().height;          
              //creation of balls, which have different coordinates,
              //speed, direction and colors
              ball[0] = new BallCollision(w,h,50,20,1.5,7.5,Color.orange);
            ball[1] = new BallCollision(w,h,60,210,2.0,-3.0,Color.red);
            ball[2] = new BallCollision(w,h,15,70,-2.0,-2.5,Color.pink);
            ball[3] = new BallCollision(w,h,150,30,-2.7,-1.0,Color.cyan);
            ball[4] = new BallCollision(w,h,210,30,2.2,-12.5,Color.magenta);
              ball[5] = new BallCollision(w,h,360,170,2.2,-1.5,Color.yellow);
              ball[6] = new BallCollision(w,h,210,180,-1.2,-2.5,Color.blue);
              ball[7] = new BallCollision(w,h,330,30,-2.2,-1.8,Color.green);
              ball[8] = new BallCollision(w,h,180,220,-2.2,-1.8,Color.white);
              ball[9] = new BallCollision(w,h,330,130,-2.2,9.0,Color.gray);     
         public void actionPerformed(ActionEvent e)
              if(e.getSource() == startButton) start = true;
                   can.start();
              if(e.getSource() == stopButton) start = false;
                   can.stop();
         public void start()
              if (runner == null)
                   runner = new Thread (this);
                   runner.start();
         public void stop()
              if (runner != null)
                  runner.stop();
                    runner = null;
         public void run()
              while(true)
                   try {Thread.sleep(15);}
                     catch (Exception e) { }               
                   //move our balls around
                   for(int i=0;i<MAX;i++)
                        ball.move();
                   handleCollision();
                   repaint();     
         boolean collide(BallCollision b1, BallCollision b2)
              double wx=b1.getCenterX()-b2.getCenterX();
              double wy=b1.getCenterY()-b2.getCenterY();
              //the distance between 2 colling balls' centres is
              //calculated by the theorem of Pythagoras
              double distance=Math.sqrt(wx*wx+wy*wy);
              if(distance<b1.diameter)
                   return true;          
                   return false;     
         private void handleCollision()
              //ecah ball is checked for possible collisions
              for(int i=0;i<MAX;i++)
                   for(int j=0;j<MAX;j++)
                             if(i!=j)
                                  if(collide(ball[i], ball[j]))
                                       ball[i].hit(ball[j]);
                                       ball[j].hit(ball[i]);
         public void update(Graphics g)
              paint(g);
         public void paint(Graphics g)
              gr.setColor(Color.black);
              gr.fillRect(0,0,size().width,size().height);          
              //paint the balls
              for(int i=0;i<MAX;i++)
                        ball[i].paint(gr);          
              g.drawImage (img,0,0, this);                    
    class BallCollision
         int width, height;
         int diameter=30;
         //balls' coordinates and values to be incremented for directions
         double x, y, xIncremented, yIncremented, coll_x, coll_y;
         boolean collide;
         Color color;
         Graphics g;
         //constructor
         public BallCollision(int w, int h, int x, int y, double xInc, double yInc, Color c)
              width=w;
              height=h;
              this.x=x;
              this.y=y;
              this.xIncremented=xInc;
              this.yIncremented=yInc;          
              color=c;          
         public double getCenterX() {return x+diameter/2;}
         public double getCenterY() {return y+diameter/2;}
         public void move()
              if (collide)
                   double xvect=coll_x-getCenterX();
                   double yvect=coll_y-getCenterY();
                   if((xIncremented>0 && xvect>0) || (xIncremented<0 && xvect<0))
                        xIncremented=-xIncremented;
                   if((yIncremented>0 && yvect>0) || (yIncremented<0 && yvect<0))
                        yIncremented=-yIncremented;
                   collide=false;
              x+=xIncremented;
         y+=yIncremented;
              //if the ball reaches a wall, it bounces to the opposite direction
         if(x<1 || x>width-diameter)
              xIncremented=-xIncremented;
                   x+=xIncremented;
              if(y<1 || y>height-diameter)
                   yIncremented=-yIncremented;
                   y+=yIncremented;
         public void hit(BallCollision b)
              if(!collide)
                   coll_x=b.getCenterX();
                   coll_y=b.getCenterY();
                   collide=true;
         public void paint(Graphics graphics)
              g=graphics;
              g.setColor(color);
              //the coordinates in fillOval have to be int, so we cast
              //explicitly from double to int
              g.fillOval((int)x,(int)y,diameter,diameter);

    well i didnt arrive at this point without reading tutorials and researching.... sometimes other people can spot your mistakes a lot easier than you can, that's why I asked for help. 10x anyway for the interest!

  • Balls don't move in bouncing balls game.Please Help !?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package ****;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("****");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  This code draws only the first position of the ball:
    http://img267.imageshack.us/my.php?image=51649094by6.jpg

    I'm trying to draw everything first to a buffer:
    buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
    gBuffer=buffer.getGraphics();
    The buffer is for one JPanel and then i want to draw this buffer every time when balls change their possitions(collide or just move).
    The logic is something like this:
    startButton -> (ball.start() and add ball to List<balls>),
    ball.start() -> ball.run() -> (move allballs, paint to buffer and show buffer)
    In the first class:
    BouncingBalls balls; //A REFERENCE TO SECOND CLASS
    In the second class:
    private List<CollideBall> balls=new ArrayList();
    the tames are the same but this isn't an error.
    Edited by: vigour on Feb 14, 2008 7:57 AM

  • Many Bouncing Balls Program

    I am trying to create a program that can use one method to create many bouncing balls.I want each ball to function independently of each other.
    The problem I am having is that when I call my BouncingBall () method three times, it only creates one ball that moves randomly instead of three.
    If you have any idea of how to tackle this problem I would really appreciate if you shared them with me. I am relatively new to java.
    I read that threads might be a good option to work on this problem but I am not sure how to use them.
    *(Code Starts)*
    import acm.graphics.*;
    import acm.program.*;
    import acm.util.*;
    import java.awt.*;
    import java.awt.event.*;
    public class BouncingBalls extends GraphicsProgram {
         public void run(){
              BouncingBall(50, 50);
              BouncingBall(100, 100);
              BouncingBall(300, 300);
         public void BouncingBall(double width, double height) {
              //Create variables for x and y position of balls
              double xPosition = getWidth()/2;
              double yPosition = getHeight()/2;
              //Create Ball
              GOval Ball = new GOval (xPosition, yPosition, width, height);
              add (Ball);
              // Initialize variables for use in Random movement method
              double xMoveBall = rgen.nextDouble(-4.0, 4.0);
              double yMoveBall = rgen.nextDouble(-4.0, 4.0);
              //Ball's Random Movement
              while (true) {     
                        Ball.move(xMoveBall,yMoveBall);
                        pause(10);
                             xPosition += xMoveBall;
                             yPosition += yMoveBall;
                   //Ball's Collisions     with walls
                   if (xPosition >= (getWidth() - width)) {
                        xMoveBall = -(xMoveBall);
                        pause(10);
                   if (xPosition <= 0){
                        xMoveBall = -(xMoveBall);
                        pause(10);
                   if (yPosition <= 0){
                        yMoveBall = -(yMoveBall);
                        pause(10);
                   if (yPosition >= getHeight() - height){
                        yMoveBall = -(yMoveBall);
                        pause(10);
         private RandomGenerator rgen = RandomGenerator.getInstance();{}
    *(Code Ends)*

    Hi,
    I have been experimenting with threads for the last couple of days. Here is the code I have been working on. I explain what I am trying to do below it:
    import acm.graphics.*;
    import acm.program.*;
    import acm.util.*;
    import java.awt.*;
    import java.awt.event.*;
    public class BB5 extends GraphicsProgram implements Runnable{
         // Debbuging Label
         private GLabel label = new GLabel("");
         //Initialize variables for ball's position
         private double xPosition = getWidth()/2;
         private double yPosition = getHeight()/2;
         //Initialize variables for use in Random movement method
         private double yMoveBall;
         private double xMoveBall;
         //Initialize variables for width and height of ball, so that they can be used in both metods: bounce() and CreateBall()
         private double width;
         private double height;
         public void mouseClicked (MouseEvent e){
              new Thread(this).start();
         public void run() {
              CreateBall(50,50).bounce();
         public void CreateBall(double x, double y) {
              //Create variables for x and y position of balls
                 xPosition = getWidth()/2;
                 yPosition = getHeight()/2;
              //Create Ball
              x = width;
              y = height;
              GOval Ball = new GOval (xPosition, yPosition, width, height);
              add (Ball);
         public void bounce() {     
         yMoveBall = rgen.nextDouble(-4.0, 4.0);
         xMoveBall = rgen.nextDouble(-4.0, 4.0);
              //Ball's Random Movement
              while (true){
                   //Put thread to sleep for 5 milliseconds so that other balls can use bounce()
                   try { Thread.sleep(5); } catch(InterruptedException e) {}
                        //Move Ball created in previous methods
                        Ball.move(xMoveBall,yMoveBall);
                        pause(10);
                             xPosition += xMoveBall;
                             yPosition += yMoveBall;
                             label.setLabel(""+xPosition); add (label, 50, 50);
                   //Ball's Collisions     with walls
                   if (xPosition >= (getWidth() - width)) {
                        xMoveBall = -(xMoveBall);
                        pause(10);
                   if (xPosition  <= 0){
                        xMoveBall = -(xMoveBall);
                        pause(10);
                   if (yPosition  <= 0){
                        yMoveBall = -(yMoveBall);
                        pause(10);
                   if (yPosition  >= getHeight() - height){
                        yMoveBall = -(yMoveBall);
                        pause(10);
         private RandomGenerator rgen = RandomGenerator.getInstance();{}
    }The idea is that I have a method that creates the ball CreateBall(), and another that bounces the ball bounce().
    My init method creates one ball. Then, when I click the mouse, I create a new thread which applies the bounce method to the ball by running the run method.
    Inside the bounce method, I have a thread sleep so that other threads can be started.
    Eventually, what I would like to do, is that everytime I click the mouse, a new ball is created and the bounce is applied to it.
    I am also having trouble with getting the ball from my CreateBall() method, to work inside my bounce().
    Can you please help me understand what might be wrong with my code?
    Thank you!

  • Object life in main method after frame created

    hi
    i'm having a slight problem with the life of an object i'm creating in the main method of my application.
    i have a JDesktopPane that is initialised in the main class's main method and constructor. within the main method i also add the first internal frame to the desktop.
    after the user completes the details of the first frame, another is called (from this first frame) and the first frame is disposed.
    the problem is that although all subsequent internal frames added to the desktop outside the main class, they are garbage collected with no problems (i'm using a profiler), however the first frame and the frame created from that first frame are never collected due to the reference maintained in the main class. i've tried adding the creation of these frames outside the main class but given that these methods are called from main the reference is still maintained.
    is there any way to create those first 2 frames without the reference being maintained in the main class such that they become elegible for garbage collection? do i have it all wrong perhaps and my approach is bad?? any help would be greatly appreciated.
    thanks heaps.
    Takis

    hi
    thanks for your reply.
    i tried that and it didn't work. the instance of that first internal frame is still there.
    i really am at a loss with this one.
    any other suggestions would be greatly appreciated.
    Takis

  • Main Method issues

    import java.util.Scanner;
    public class Orbit
         public static void main(String[] args)
              int n;
              Scanner keyboard = new Scanner(System.in);
              System.out.print("Enter Number: ");
              n = keyboard.nextInt();          
                   double sum = 0.0;
                   for (int i = 1; i <= n; i++)
                        sum += 1.0/i;
                        System.out.println("Harmonic number: " + sum);     
    }So this code works, if you input 6 you get out the harmonic 2.449999997
    import java.util.Scanner;
    public class Orbit
         public static void main(String[] args)
              int n;
              Scanner keyboard = new Scanner(System.in);
              System.out.print("Enter Number: ");
              n = keyboard.nextInt();               
              int x = n;
                   for(int i = 1 ; i <= 10; i++)
                        if(isPali(x))
                             System.out.println("Palindrome number: " + x);
                             break;
                    StringBuffer sb = new StringBuffer(x + "");
                     StringBuffer sb2 = sb.reverse();
                     String s3 = sb2.toString();
                     int x2 = Integer.parseInt(s3);
                     x += x2;
           public static boolean isPali(int l)
                      String longAsString = l + "";
                   int x = longAsString.length();
                   if (x == 1)
                          return true;
                       if(x == 2)
                          char x1 = longAsString.charAt(0);
                          char x2 = longAsString.charAt(1);
                          return x1 == x2;
                   if( (x % 2) == 1)
                          StringBuffer newString = new StringBuffer();
                          int xx = x;
                          int y = (xx / 2);
                          newString.append(longAsString.substring(0, y));
                          newString.append(longAsString.substring(y + 1));
                          String ss = newString.toString();
                          int xxx = ss.length();
                               for(int i = 0; i < xxx/2; i++)
                                  char xFirst = ss.charAt(i);
                                  char xLast = ss.charAt(xxx - (i + 1));
                                       if(xFirst != xLast)
                                            return false;
                                    return true;      
                            if( (x % 2) == 0)
                               int xx = longAsString.length();
                                  for(int i = 0; i < xx/2; i++)
                                           char xFirst = longAsString.charAt(i);
                                       char xLast = longAsString.charAt(xx - (i + 1));
                                       if(xFirst != xLast)
                                              return false;
                                         return true;
                                 return false;
    }And then this code works to output any given number's palindrome, but when I attempt to add the first one onto the end of the second one, i get an error stating that the variable 'n' is not defined as is per this code
    import java.util.Scanner;
    public class Orbit
         public static void main(String[] args)
              int n;
              Scanner keyboard = new Scanner(System.in);
              System.out.print("Enter Number: ");
              n = keyboard.nextInt();               
              int x = n;
                   for(int i = 1 ; i <= 10; i++)
                        if(isPali(x))
                             System.out.println("Palindrome number: " + x);
                             break;
                    StringBuffer sb = new StringBuffer(x + "");
                     StringBuffer sb2 = sb.reverse();
                     String s3 = sb2.toString();
                     int x2 = Integer.parseInt(s3);
                     x += x2;
           public static boolean isPali(int l)
                      String longAsString = l + "";
                   int x = longAsString.length();
                   if (x == 1)
                          return true;
                       if(x == 2)
                          char x1 = longAsString.charAt(0);
                          char x2 = longAsString.charAt(1);
                          return x1 == x2;
                   if( (x % 2) == 1)
                          StringBuffer newString = new StringBuffer();
                          int xx = x;
                          int y = (xx / 2);
                          newString.append(longAsString.substring(0, y));
                          newString.append(longAsString.substring(y + 1));
                          String ss = newString.toString();
                          int xxx = ss.length();
                               for(int i = 0; i < xxx/2; i++)
                                  char xFirst = ss.charAt(i);
                                  char xLast = ss.charAt(xxx - (i + 1));
                                       if(xFirst != xLast)
                                            return false;
                                    return true;      
                            if( (x % 2) == 0)
                               int xx = longAsString.length();
                                  for(int i = 0; i < xx/2; i++)
                                           char xFirst = longAsString.charAt(i);
                                       char xLast = longAsString.charAt(xx - (i + 1));
                                       if(xFirst != xLast)
                                              return false;
                                         return true;
                                 return false;
                   double sum = 0.0;
                   for (int i = 1; i <= n; i++)
                        sum += 1.0/i;
                        System.out.println("Harmonic number: " + sum);     
    }Now the sad thing is I know exactly why this is happening, because the variable n is in the main method but the main method was forced to close to make room for the Boolean isPali, and it would make sense to place the Harmonic code in the main method but the output required for this is such that the harmonic needs to be after the Palindrome - I am currently asking for that to be changed but that never works. Now of course also I could prompt the user again but that is a little tacky and frowned upon.
    ~Thanks

    Ok, sorry let me clarify it a little bit.
    I define n as the user input variable. How I have the code set up currently is to create the palindrome of that number using a boolean expression. I have it set up currently to exit the main method and enter into the boolean expression because it seems to be the only way I can complete that part of code. Now as for my problem, with "int n" being defined in the main method, I can not access it without being in that main method.
    Orbit.java:138 cannot find symbol
    symbol : variable n
    location: class Orbit
    for (int i = 1; 1 <= n; i++)
    *as you would imagine, the '^' is under the sole n in the line of code                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Invoke jar main method in java code

    hi
    i have a jar that has a usage like this
    java -jar helper.jar arg1 arg2 etc...i want to invoke this helper main method in my java code.i've tried using reflection but it didn't quite work...
    String[] args = new String[]{"arg1","arg2"};
    Class c = Class.forName("com.helper.MainClass");
    Method mainMethod = c.getMethod("main", args.getClass());
    int mods = mainMethod.getModifiers();
    if(mainMethod.getReturnType() != void.class || !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
         throw new NoSuchMethodException("main");
    mainMethod.invoke(null, args);
    Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at Test.callJarMain(Test.java:50)
    at Test2.main(Test.java:34)thoughts???

    phychem wrote:
    i want to use this jar in a non-static way.
    public void useJar(String args[]){
    //somehow invoke jar method here...
    Sorry, I still don't get it. I don't know what you mean by a non-static way of using jars. The main method for launching an application is static so if you call that method, you will be using a static method. I don't know what you mean by a "jar method" either. Methods are inside classes. So far, all I can guess is you want to invoke a method in a class that happens to be inside a jar. Since people do this all the time without reflection, I don't see the problem.

  • Is it possible to run the java program without main?

    Hi,
    Is it possible to run the java program without main?
    if anybody know please tell me, how it is possible.
    Regards,
    Ramya

    Hi,
    Is it possible to run the java program without main?
    if anybody know please tell me, how it is possible.
    Regards,
    RamyaWhy do you ask? It sounds like an odd question. Your program can be an applet and it doesn't need a main method in that case.
    Kaj

  • Can users call main method??

    class MainDemo{
    public static void main(String args[]){
    System.out.println("First main method");
    MainDemo.main("hello");
    }Hi all,
    Why is the above code not compiling??

    By adding few lines right after the System.out.println("First main method");.
    class MainDemo
         public static void main(String args[])
              System.out.println("First main method");
              System.out.println("No.of args : " + args.length);
              if (args.length > 0)
                   System.out.println("Passed in : " + args[0]);
              System.out.println();
        static
             String args[] = {"hello"};
             MainDemo.main(args);
    }And the output gives :-
    First main method
    No.of args : 1
    Passed in : hello
    First main method
    No.of args : 0
    Press any key to continue...
    Why is it JVM executes the main() method in the static block instead of the calling the main() method (without argument) directly ?
    Edited by: TKH on Nov 14, 2007 1:08 AM

  • How To Pass A Value Read By A Loop To Main Method

    Hey everybody,
    I'm at this with my code.I'm reading the values of a text file in a loop.I want to pass these values to main method.The importhant point is I want to do this without using a field. The code is below. Thanks.
    //Main
    public static void main(String[] args)throws FileNotFoundException
              DoubleClass AvgScore=new DoubleClass();
    IntClass Messenger=new IntClass();
              PrintWriter writer1=new PrintWriter("D:\\JavaExercises\\CH07EX14out.txt");
              Scanner scan1=new Scanner(new FileReader("D:\\JavaExercises\\CH07EX14data.txt"));
         //1 ogrencinin notlarini okut ve ortalamas&#305;n&#305; hesaplat
         while(scan1.hasNext())
              writer1.print(scan1.next()+" ");
    calcAvg(AvgScore,scan1,Messenger);
    //AvgScore formatlanarak yazdirilacak
    writer1.print(""+AvgScore+" ");
    writer1.print(""+calcGrade(AvgScore)+"\n");
    writer1.close();
    //calcAvg
    public static void calcAvg(DoubleClass x,Scanner y,IntClass z)
         int counter=0;
         double TotalScore=0;
    int NumTests=1;
    int Score=0;
    //Bir ogrenci icin toplam notu ve test sayisini bul.
         while(counter<=4)
              Score=y.nextInt();
    TotalScore+=Score;
    counter++;
    NumTests++;
    //Bir ogrenci icin not ortalamsi bul.
    x.setNum(TotalScore/NumTests);
              }

    Malkavian187 wrote:
    Guys please pay attention,
    I already said I can't use a field(class scoped variable)and can't use a return type method.
    I ve heard that it can be done by passing a reference or primitive variable to my calcAvg method.And than assignin the read values back to this variable.
    But I can't figure out how to make it. I need a complete solution.Including modifications to calcAvg and main method.
    Take care,Malkavian187,
    Maybe you haven't seen other posters asking homework to be done for them, so here is basically what we tell them: DO IT YOURSELF.
    And we realize that very possibly you could fail your class from that and have to drop out. This may be a good thing because it will help keep the demand for technical workers up, and thus, keep the pay high.
    On the other hand, if you choose to actually do the assignment then we will be happy to give comments on your code. Please post it when you have some and until then, best wishes with what ever you choose to do.
    BTW: the solution you allude to requires a field also... and in reality, you already gave the answer--just implement it. If you do not know how: well, maybe you should do one of the following:
    1-read and study the Java Tutorial
    2-pay more attention to class
    3-read your textbook for your class
    4-go to class
    5-stay awake in class
    6-pay attention in class
    7-talk to your teacher
    8-withdraw from the class
    9-change your major

  • Can we make executable jar file which dont have main method?

    I have a problem.
    With whatever R&D i have done so far my understanding is that in order to create executable jar files i need a main method.
    my problem is i have certain MIS reports which are developed in java and deployed through JSP pages...so my java program has no Main Method and only objects of the classes are being called in the JSP pages.
    for e.g: i have a java class file BulkSms.class and i make an object of it in the JSP page through which my purpose is achieved by calling various method in the BulkSms through it s objects and there is no main method.
    Can i make an executable jar file without a main method and if so please give me a detailed procedure of how to go about it.
    i want to make it executable so tht on the click of it the MIS report is displayed from the JSP page.

    I am completely ignorant of JSPs, but you can not execute a jar or any java application unless you have a main method. It sounds like you need a way to launch the JSP - can't you do this with a browser?

  • Java Virtual Machine "Could not find main method"  what do i do?

    Hi I'm very new to java and for my class we are to make an applet and make a class. I figured out how to do it but the Java Virtual Machine gives me an error when I go to run the applet."Could not find the main method. Program Will exit!" . I am using Jbuilder8 personal to compile the code. Using j2sdk1.4.0_03. Could someone tell me how to fix this? Or what I'm doing wrong?
    Here is my code.
    package assignment5;
      Program: Program 5.2
      Author: Will W.
      Date: 02/20/03
      Description: Create a student class that holds the
      student name, student ID, phone and number of units
      completed. Create methods and a applet to input data
      Dispay the student name, student ID, phone, units
      completed in a text area.
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Assignment5Applet extends Applet implements ActionListener
         //Create Components
         //TextFields
         TextField txtName = new TextField(25);
         TextField txtId  = new TextField(15);
         TextField txtPhone = new TextField(15);
         TextField txtUnits = new TextField(4);
         //TextArea
         TextArea txaList = new TextArea(20,40);
         //Button
         Button btnAdd = new Button("Go");
         //Labels mostly debugging purposes.
         Label lblOutput = new Label();
         Label lblNumberProcessed = new Label();
         Label lblError = new Label();
         public void init()
              //Create the interface for the applet
              Panel pnlLayout = new Panel(new GridLayout(5, 2));
              pnlLayout.add(new Label("Name:"));
              pnlLayout.add(txtName);
              pnlLayout.add(new Label("Student Id:"));
              pnlLayout.add(txtId);
              pnlLayout.add(new Label("Phone #:"));
              pnlLayout.add(txtPhone);
              pnlLayout.add(new Label("Num Units:"));
              pnlLayout.add(txtUnits);
              add(pnlLayout);
              add(btnAdd);
              add(txaList);
              txtName.requestFocus();
              btnAdd.addActionListener(this);
              txtName.addActionListener(this);
              txtId.addActionListener(this);
              txtPhone.addActionListener(this);
              txtUnits.addActionListener(this);
         public void actionPerformed(ActionEvent evt)
                    //Variables to hold the data in the textboxes
              String strName;
              String strId;
              String strPhone;
              String strUnits;
              try
                   //Get the data
                   strName = txtName.getText();
                   strId = txtId.getText();
                   strPhone = txtPhone.getText();
                   strUnits = txtUnits.getText();
                            //Instantiate a student object
                            Student aStudent = new Student(strName, strId, strPhone, strUnits);
                            //Use get student to get the output
                         txaList.append("Output:" + aStudent.getStudent());
                   lblOutput.setText("");
              catch(NumberFormatException e)
                   lblOutput.setText("Error");
    }The my student class
    package assignment5;
      * Program: Student.java
      * Author: Will W.
      * Date: 02/20/03
      * Descrip:
      * Student Class for Assignment5Applet.java
      * Contains one constructor and 5 other methods
      * for the class
    public class Student
            //Class Variables
            private String  strName;
            private String strId;
            private String strPhone;
            private String strUnits;
            private String strOutput;
            //Constructor
            public Student(String strNewName, String strNewId, String strNewPhone, String strNewUnits)
              setName(strNewName);
              setId(strNewId);
              setPhone(strNewPhone);
              setUnits(strNewUnits);
            //Methods
            public void setName(String strNewName)
                    //Assign new value to private variable
                    strName = strNewName;
            public void setId(String strNewId)
                    strId = strNewId;
            public void setPhone(String strNewPhone)
                    strPhone = strNewPhone;
            public void setUnits(String strNewUnits)
                    strUnits = strNewUnits;
            public String getStudent()
                    //Put the output together
                    strOutput = strName + "\n" + strId + "\n" + strPhone + "\n" + strUnits;
                    return strOutput;
    }Everythings seems to compile correctly without errors it's just when I execute to the running program that the Java Virtual Machine throws me that error saying it can't find the main method.

    Java Virtual Machine "Could not find main method" what do i do?
    Ok Ok OK I got the solution for you ,this is what you do you put your hands inbetweenj you leggs and run around in a circle can scream me nuts me nuts me nuts are on fire,then come back and tell use if the problem is solved or not
    Good luck hehehehe:P

Maybe you are looking for