-2

Hello Guys I'm Trying Two Create a Program Which Has a Two ball in it. The One is Going right and the one is going down. i have a code but i don't know how to make the other ball going down... any help is much appreciate thanks...

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class move extends JPanel
{
   Timer timer;
   int x = 0, y = 10, width = 40, height = 40;
   int radius = (width / 2);
   int frXPos = 500;
   int speedX = 1;
   move()
   {
        ActionListener taskPerformer = new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                if (x == 0)
            {
                speedX = 1;
            }
            if (x > (frXPos - width)) 
            {
                x=0;
            }
        x = x + speedX;
        repaint();
        }
    };
timer = new Timer(2, taskPerformer);
timer.start();
}
@Override
public void paintComponent(Graphics g)
{
     super.paintComponent(g);
     g.setColor(Color.red);
     g.fillOval(x, y, width, height);
}
}
class MovingBall
{
MovingBall()
{
     JFrame fr = new JFrame("Two Balls Moving Other Ways");
     move o = new move();
     fr.add(o);
     fr.setVisible(true);
     fr.setSize(500, 500); 
     fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
        MovingBall movingBall = new MovingBall();
}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Reiqn
  • 11
  • 1

1 Answers1

2

Instead of trying to make each ball a component, Just use one drawing surface, and a Ball class that holds/draws/manipulates the state of each ball. Then have a List of Ball objects. As seen in this example.

The example uses a number of the "same" type of Balls that all move the same. But what you can do is Have a super abstract class Ball with an abstract method move(), and had two separate subclasses, UpDownBall, RightLeftBall and override the move() method for each of those classes.

You will also note in the example how the List<Ball> is iterated in the paintComponent method. That's what you should do.

For example (expanding on the linked example)

public interface Ball {
    void drawBall(Graphics g);
    void move();
}

public abstract class AbstractBall implements Ball {
    protected int x, y, width, height;
    ...
    @Override
    public void drawBall(Graphics g) {
        g.fillOval(x, y, width, height);
    }
    // getters and setters where needed
}

public class UpDownBall extends AbstractBall {
    ...
    @Override
    public void move() {
        // change y position
    }
}

public class RightLeftBall extends AbstractBall {
    ...
    public void move() {
        // change x position
    }
}
Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720