1

Hello I'm fairly new to java, i been working on learning graphics i made a code that displays a ball that moves around, this i understand how to make easy. but when i try to make multiple balls it gets complicated on how i should go about doing so, can anyone explain? basically i want to use this code to make multiple balls but i don't understand how. this is the code i made so far:

public class Main {

    public static void main(String args[]) {
        Ball b = new Ball();


        JFrame f = new JFrame();
        f.setSize(1000, 1000);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        f.add(b);



    }

}

    public class Ball extends JPanel implements ActionListener{

     Timer t = new Timer(5 , this);

    int x = 0, y = 0,speedx = 2, speedy = 2;



    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.CYAN);
        g.fillOval(x, y, 20, 20);
        t.start();
    }

    public void actionPerformed(ActionEvent e) {
        x += speedx;
            y += speedy;
            if(0 > x || x > 950){
                speedx = -speedx;
            }
            if(0 > y || y > 950){
                speedy = -speedy;
            }
           repaint();
    }

 }
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
Jole Mola
  • 25
  • 1
  • 8
  • 1
    Be careful with variables named `x` & `y`, they could cause problems with other parts of the system as `JPanel` actually has it's own (private) variables named the same - the problem arises when people override the `getX/Y` methods, but you should just be careful ;) – MadProgrammer Jun 03 '13 at 02:29
  • [Example](http://stackoverflow.com/questions/13022754/java-bouncing-ball/13022788#13022788), [example](http://stackoverflow.com/questions/14593678/multiple-bouncing-balls-thread-issue/14593761#14593761), [example](http://stackoverflow.com/questions/14886232/swing-animation-running-extremely-slow/14902184#14902184), [example](http://stackoverflow.com/questions/12642852/the-images-are-not-loading/12648265#12648265) ;) – MadProgrammer Jun 03 '13 at 02:30
  • @MadProgrammer good advice, never thought of that! – Mordechai Jun 03 '13 at 02:30
  • @MouseEvent Love those questions, unless you're paying attention, they're a pain to diagnose :P – MadProgrammer Jun 03 '13 at 02:32

1 Answers1

2

Do not have any program logic statements in your paintComponent(...) method ever. Get rid of the timer's start method from that method. You do not have full control over when or even if the method will be called.

If you want to show multiple balls, then give your GUI an ArrayList of Balls and then iterate through them, drawing them in paintComponent. Move them in the Timer.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • @joleMola You might also like to check out [Initial Threads](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html) – MadProgrammer Jun 03 '13 at 02:32