Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7968689
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T07:06:59+00:00 2026-06-04T07:06:59+00:00

The problem is that this ball after it is dragged and exited click, it

  • 0

The problem is that this ball after it is dragged and exited click, it is supposed to repaint according to the new y component given. This is calculated from the gravity final and added to the velocity which is added to the existing y component in a loop.

I have debugged many times and I just cant hit it on the head.

Its supposed to..
move to where you drag it >>> when you let go it is supposed to fall until it hits the ground.

Thank you ahead of time.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DragBallPanel extends JPanel implements MouseListener, MouseMotionListener
{
     private static final int BALL_DIAMETER = 40;
     private int screen_size_x = 300;
     private int screen_size_y = 300;
     private int ground_lvl = screen_size_y - 15;

     private int _ballX     = ground_lvl/2;
     private int _ballY     = ground_lvl - BALL_DIAMETER;
     private final double GRAVITY = -9.8;
     private double velocity;
     private static final double TERM_VEL = -100;

     private int _dragFromX = 0;
     private int _dragFromY = 0;

     private boolean _canDrag  = false;


     public DragBallPanel() throws InterruptedException
     {
        setPreferredSize(new Dimension(screen_size_x, screen_size_y));
        setBackground(Color.darkGray);
        setForeground(Color.darkGray);

        this.addMouseListener(this); 
        this.addMouseMotionListener(this);
    }

    public void paintComponent(Graphics g)
     {
        super.paintComponent(g);   // Required for background.
          g.setColor (Color.green);
          g.fillRect (0, 280, 400, 50 );
          g.setColor (Color.black);
        g.fillOval(_ballX, _ballY, BALL_DIAMETER, BALL_DIAMETER);

    }

    public void mousePressed(MouseEvent e)
    {
        int x = e.getX();
        int y = e.getY();

        if (x >= _ballX && x <= (_ballX + BALL_DIAMETER)
                && y >= _ballY && y <= (_ballY + BALL_DIAMETER))\
          {
            _canDrag = true;
            _dragFromX = x - _ballX;
            _dragFromY = y - _ballY;
        } else
          {
            _canDrag = false;
        }
    }

    //===== mouseDragged ======
    /** Set x,y  to mouse position and repaint. */
    public void mouseDragged(MouseEvent e)
    {
        if (_canDrag)
          {   // True only if button was pressed inside ball.
            //--- Ball pos from mouse and original click displacement
            _ballX = e.getX() - _dragFromX;
            _ballY = e.getY() - _dragFromY;

            //--- Don't move the ball off the screen sides
            _ballX = Math.max(_ballX, 0);
            _ballX = Math.min(_ballX, getWidth() - BALL_DIAMETER);

            //--- Don't move the ball off top or bottom
            _ballY = Math.max(_ballY, 0);
            _ballY = Math.min(_ballY, getHeight() - BALL_DIAMETER);

            this.repaint();
        }
    }

    public void mouseExited(MouseEvent e)
    {
          while(_ballY < ground_lvl)
          {
                 simulateGravity();
          }   
    }

     public void simulateGravity()
     {
         if(_canDrag)
         {
             try{
                 velocity = velocity + GRAVITY;

               if (velocity < TERM_VEL)
                 {
                    velocity = TERM_VEL;
                 }

                if (_ballY >= ground_lvl - BALL_DIAMETER)
                {
                   velocity = velocity/4; 
                } 
                _ballY += velocity;
                 Thread.sleep(400);
                 this.repaint();//**problem occurs here**

              }catch(InterruptedException ie)
              {
              }
         }
     }

    public void mouseMoved   (MouseEvent e){}
    public void mouseEntered (MouseEvent e){}
    public void mouseClicked (MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
}

main() class

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;


public class DragDemo extends JApplet
{
    public static void main(String[] args) throws InterruptedException
    {
        JFrame window = new JFrame();
        window.setTitle("Drag Demo");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          //window.add(new DragBallPanel());
        window.setContentPane(new DragBallPanel());
          window.setResizable(false);
        window.pack();
        window.show();
    }

    public DragDemo() throws InterruptedException
    {
        new DragBallPanel();
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T07:07:00+00:00Added an answer on June 4, 2026 at 7:07 am

    This SSCCE begins to show the problems in the code.

    1. Compile the code.
    2. Run it.
    3. Drag the ball upwards.
    4. Release the ball.
    5. Remove the mouse from the drawing area, to see..
    6. The ball fall upwards!

    You seem to have gotten the Y values upside down. They start at top of screen, and go downwards. Also, the code was blocking the EDT in an infinite loop. To solve that, run the animation using a Swing Timer.

    Please read the document on the SSCCE & ask if there is anything in it you do not understand. I am well placed to explain. 🙂


    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class DragBallPanel extends JPanel implements MouseListener, MouseMotionListener
    {
    
        private static final int BALL_DIAMETER = 40; // Diameter of ball
    
        private int screen_size_x = 300;
        private int screen_size_y = 300;
        private int ground_lvl = screen_size_y - 15;
    
        private int _ballX     = ground_lvl/2;
        private int _ballY     = ground_lvl - BALL_DIAMETER;
        private final double GRAVITY = -9.8;
        private double velocity;
        private static final double TERM_VEL = 100;
    
        private int _dragFromX = 0;    // pressed this far inside ball's
        private int _dragFromY = 0;    // bounding box.
    
        /** true means mouse was pressed in ball and still in panel.*/
        private boolean _canDrag  = false;
    
        public DragBallPanel()
        {
            setPreferredSize(new Dimension(screen_size_x, screen_size_y));
            setBackground(Color.darkGray);
            setForeground(Color.darkGray);
    
            this.addMouseListener(this);
            this.addMouseMotionListener(this);
        }
    
        public void paintComponent(Graphics g)
         {
            super.paintComponent(g);   // Required for background.
              g.setColor (Color.green);
              g.fillRect (0, 280, 400, 50 );
              g.setColor (Color.black);
            g.fillOval(_ballX, _ballY, BALL_DIAMETER, BALL_DIAMETER);
    
        }
    
        public void mousePressed(MouseEvent e)
        {
            int x = e.getX();   // Save the x coord of the click
            int y = e.getY();   // Save the y coord of the click
    
            if (x >= _ballX && x <= (_ballX + BALL_DIAMETER)
                    && y >= _ballY && y <= (_ballY + BALL_DIAMETER)) {
                _canDrag = true;
                _dragFromX = x - _ballX;  // how far from left
                _dragFromY = y - _ballY;  // how far from top
            } else {
                _canDrag = false;
            }
        }
    
        //========= mouseDragged =================
        /** Set x,y  to mouse position and repaint. */
        public void mouseDragged(MouseEvent e)
        {
            if (_canDrag) {   // True only if button was pressed inside ball.
                //--- Ball pos from mouse and original click displacement
                _ballX = e.getX() - _dragFromX;
                _ballY = e.getY() - _dragFromY;
    
                //--- Don't move the ball off the screen sides
                _ballX = Math.max(_ballX, 0);
                _ballX = Math.min(_ballX, getWidth() - BALL_DIAMETER);
    
                //--- Don't move the ball off top or bottom
                _ballY = Math.max(_ballY, 0);
                _ballY = Math.min(_ballY, getHeight() - BALL_DIAMETER);
    
                this.repaint(); // Repaint because position changed.
            }
        }
    
        //====================================================== method mouseExited
        /** Turn off dragging if mouse exits panel. */
        public void mouseExited(MouseEvent e)
         {
             System.out.println("Exited: " + e);
            //_canDrag = false;
            runGravity();
            /*  while(_ballY < ground_lvl)
              {
                 simulateGravity();
              }*/
        }
    
        Timer timer;
        ActionListener animate;
    
        public void runGravity() {
            if (animate==null) {
                animate = new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        System.out.println("Ground: " + (_ballY-ground_lvl));
                        if (_ballY > ground_lvl) {
                            timer.stop();
                        } else {
                            simulateGravity();
                        }
                    }
                };
                timer = new Timer(100,animate);
            }
            timer.start();
        }
    
         public void simulateGravity()
         {
             System.out.println("_canDrag: " + _canDrag);
             if(_canDrag)
             {
    
                 velocity = velocity + GRAVITY;
    
               if (velocity > TERM_VEL)
                 {
                    velocity = TERM_VEL;
                 }
    
                if (_ballY >= ground_lvl - BALL_DIAMETER)
                {
                    //We have hit the "ground", so bounce back up. Reverse
                    //the speed and divide by 4 to make it slower on bouncing.
                    //Just change 4 to 2 or something to make it faster.
                   velocity = velocity/4;
                }
                _ballY += velocity;
                 //this.revalidate();
                 this.repaint();
             }
        }
    
        public void mouseMoved   (MouseEvent e){}
        public void mouseEntered (MouseEvent e){}
        public void mouseClicked (MouseEvent e){}
        public void mouseReleased(MouseEvent e){}
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater( new Runnable() {
                public void run() {
                    DragBallPanel dbp = new DragBallPanel();
                    JOptionPane.showMessageDialog(null, dbp);
                }
            });
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Update: After some more reading I see that this problem is totally general, you
In the end, I have decided that this isn't a problem that I particularly
I think that this problem can be sorted using reflection (a technology which I'm
I have this problem that my sites uses alot of ajax and when a
There was this problem that has been asked about implementing a load byte into
Ok I have this problem that I've never had before, it's really bugging me.
So we have this problem that we are trying to figure out. Heres what
THIRD EDIT: I now believe that this problem is due to a SOAP version
(I have a problem that I illustrated in this question but had no correct
I understand the problem that OSGI solved thanks to this question.... What does OSGi

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.