Reputation: 25
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();
}
}
Upvotes: 1
Views: 1157
Reputation: 285405
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.
Upvotes: 2