JAVA - How to create a new stream with every mouse click

In java, how do you throw a ball on a panel with every mouse click? Say I pressed the panel 3 times, so there should be 3 balls in the panel.

I have this code:

ball = new Thread() {
    public void run() {
        while (true) { 
            x += speedX;
            y += speedY;
        }
    }
};
ball.start();

repaint();
try {Thread.sleep(100/3);}catch(InterruptedException ex){}

And the ball drawing method:

public void paintComponent(Graphics ball) {
  super.paintComponent(ball);
  if(clicks>0){
    ball.setColor(Color.BLUE);
    ball.fillOval((int) (x - rad), (int) (y - rad), (int)(2 * rad), (int)(2 * rad));
  }
}

But this thread only throws 1 ball into the panel. I also tried an array of threads, but that didn't work.

+4
source share
2 answers
  • Obviously, you need to store different (x, y) data for each ball, for example. have class Ball with x, y and thenList<Ball>

(if you did not calculate them for calculation, namely one x, y with balls computed at some offset)

  1. on paintComponent you need to draw all the balls, which means some loop 'fillOval'

  2. " repaint" x y. " sleep", .

  3. , MadProgrammer: , . ( ), , , . -

    List<Ball> balls= ...;
    
    Class BallRunnable implements Runnable{
      private Ball ball;
      private JComponent comp; // the one whose paintComponent does fillOval
      public BallRunnable(Ball ball, JComponent comp){
        this.ball=ball;
      }
      public void run(){
         while(true){
            ball.x +=speedX; ball.y+= speedY;
            Thread.sleep(200);
            comp.repaint();
         }
      }
    }
    
+1

MouseListener , .

    final JPanel p = new JPanel();
    p.addMouseListener(new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent e) {
            Thread ball = new Thread() {
                public void run() {
                    while (true) {
                        x += speedX;
                        y += speedY;
                    }
                }
            };
            ball.start();

            p.repaint();
        }

        @Override
        public void mousePressed(MouseEvent e) {

        }

        @Override
        public void mouseReleased(MouseEvent e) {

        }

        @Override
        public void mouseEntered(MouseEvent e) {

        }

        @Override
        public void mouseExited(MouseEvent e) {

        }
    });
0

Source: https://habr.com/ru/post/1611142/


All Articles