0

I have managed to draw a circle on a JFrame object I have in my Netbeans IDE. How can I make the circle bounce when I click my JFrame. I need help making the circle move down and as soon as it touches the lower border of my JFrame it bounces back up and so and so forth, Thank You for your precious code, time and effort.

package bouncingcircle;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/**
 *
 * @author Researcher
 */
public class BouncingCircle extends JFrame{
    
    //add custom logic to the constructor
      BouncingCircle(){
       setTitle("Bouncing Circle");
       setSize(new Dimension(500,500));
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setResizable(false);
       setVisible(true);
         getContentPane().addMouseListener(new MouseAdapter() {            
   public void mouseClicked(MouseEvent e) {
     //I need help here to start bouncing the circle, Thank You
   }
       
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    new BouncingCicrcle();
    }  
    @Override
    public void paint(Graphics g){
        //use the context to draw  circle
        Graphics2D g2d= (Graphics2D)g;
        g2d.drawOval(150, 150, 100, 100);
    }
    
}

  • Your custom painting is wrong. You should NOT override paint() on a JFrame. Read the section from the Swing tutorial on [Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) for step-by-step example of how to do custom painting. If you want animation then you need to use a Swing Timer. The tutorial also has a section on "Using a Swing Timer". You can then check out: https://stackoverflow.com/a/54028681/131872 for an example of randomly animation multiple balls. – camickr May 20 '22 at 13:45
  • Here is [another example](https://stackoverflow.com/a/66833594/1552534) that might offer some ideas. – WJS May 20 '22 at 17:27

0 Answers0