I do realize there is another topic very similar to my question here
Differs from here due to the method of adding balls to the panel (not content Panes)
However the issue addressed in that topic doesn't really answer my question and explain why the problem I'm having is occuring
I'm trying to create a very simple program that can create multiple balls which can bounce independently and do not interact with eachother however whenever I create one ball successfully the next attempted implementation is overwritten and the previous ball is not shown
I believe that a possible cause to this is due to the layout and how adding a multiple balls is not possible on a default Center layout
I saw some suggestions and examples using lists and/or a null layout and after attempting some of these none worked
The program consists of two classes one "GUI" for creating the window and adding the balls and the "Ball" class which is the ball itself
Here is the GUI class
import javax.swing.JFrame;
import java.awt.*;
public class Gui extends JFrame{
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Ball());
frame.add(new Ball(200,200,8,8,25,25)); //This overwrites above line
frame.setSize(500,400);
frame.setVisible(true);
}
}
Here is the ball class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
public class Ball extends JPanel implements ActionListener{
Timer timer = new Timer(10,this);
double x_coord = 250, y_coord = 250, x_vector = 5, y_vector = 5, x_size = 50, y_size = 50;
public Ball(double x_c, double y_c, double x_v, double y_v, double x_s, double y_s){
x_coord = x_c;
y_coord = y_c;
x_vector = x_v;
y_vector = y_v;
x_size = x_s;
y_size = y_s;
timer.start();
setFocusable(true);
}
public Ball(){
timer.start();
setFocusable(true);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Rectangle rect = g2d.getClipBounds();
rect.x = (int) x_coord;
rect.y = (int) y_coord;
g2d.fill(new Ellipse2D.Double(rect.getX(), rect.getY(), x_size, y_size));
if(rect.getY() < 0 || rect.getY() > (getHeight()-y_size)){
y_vector *= -1;
}else if(rect.getX() < 0 || rect.getX() > (getWidth()-x_size)){
x_vector *= -1;
}
}
public void actionPerformed(ActionEvent e) {
repaint();
x_coord += x_vector;
y_coord += y_vector;
}
}
I would very much appreciate a well explaining answer since I still am quite green with JPanel and JFrame, Thanks!