Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Need help making ball move and bounce off of sides of JPanel

807600Nov 30 2007 — edited Dec 1 2007
I'm currently working on a program that creates a ball of random color. I'm trying to make the ball move around the JPanel it is contained in and if it hits a wall it should bounce off of it. I have been able to draw the ball and make it fill with a random color. However, I cannot get it to move around and bounce off the walls. Below is the code for the class that creates the ball. Should I possible be using multithreads? As part of the project requirements I will need to utilizes threads and include a runnable. However, I wanted to get it working with one first and than add to it as the final product needs to include new balls being added with each mouse click. Any help would be appreciated.

Thanks
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class Ball extends JPanel{
    
    Graphics g;
    int rval; // red color value
    int gval; // green color value
    int bval; // blue color value
    private int x = 1;
    private int y = 1;
    private int dx = 2;
    private int dy = 2;
    
    public void paintComponent(Graphics g){
        
        for(int counter = 0; counter < 100; counter++){
            // randomly chooses red, green and blue values changing color of ball each time
            rval = (int)Math.floor(Math.random() * 256);
            gval = (int)Math.floor(Math.random() * 256);
            bval = (int)Math.floor(Math.random() * 256);
            
            
            super.paintComponent(g);
            g.drawOval(0,0,30,30);   // draws circle
            g.setColor(new Color(rval,gval,bval)); // takes random numbers from above and creates RGB color value to be displayed
            g.fillOval(x,y,30,30); // adds color to circle
            move(g);
            
            
        }
    } // end paintComponent
    
    public void move(Graphics g){
        
        g.fillOval(x, y, 30, 30);
        x += dx;
        y += dy;
        if(x < 0){
            x = 0;
            dx = -dx;
        }
        if (x + 30 >= 400) {
            x = 400 - 30;
            dx = -dx;
        }
        if (y < 0) {
            y = 0;
            dy = -dy;
        }
        if (y + 30 >= 400) {
            y = 400 - 30;
            dy = -dy;
        }
        g.fillOval(x, y, 30, 30);
        g.dispose();
        
    }   
} // end Ball class
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 29 2007
Added on Nov 30 2007
2 comments
466 views