I'm working on a game with a few people. This game requires us to create subclasses of JComponent, which each have their own paintComponent() method, invoked when it is added to a container. These subclasses are called Block, Goal, Spike, Ball, and Pit. Adding a single one of these components to a frame is no problem, since nothing else is being added along with it. I already added more than one JButton in the same JPanel in the main menu, and JButton also extends JComponent, so we all assumed our subclasses would work as well. However, when we try to add more than one of these (even of the same type), only one of them, if any, show up in the frame. We also track mouse clicks and mouse motion which are used for drawing lines with the window (for Balls to bounce off of), and adding a Line and another component does not work either. This so far is the only way we thought would fix our problem, but did not:
Container c = this.getContentPane();
c.setLayout(null);
Block b = new Block(200, 200);
Block b1 = new Block(220, 200);
b.setBounds(200, 200, 20, 20);
b1.setBounds(220, 200, 20, 20);
c.add(b);
c.add(b1);
c.revalidate();
This method attempts to add two Blocks in the same container. Since I set the layout of the Container to null
, I can specify the exact location and size of the Block. When initializing a Block, the constructor takes in the x and y coordinate of the top left of the block, and the default size is 20x20 pixels. I also call setBounds()
on both Blocks, so that they would be right next to each other, theoretically. However, when I compile and execute the code, Only the first one shows up. Any reason as to why, and how can this be fixed?
Also, how would you add a Line and, a Block, for example? I have it so that creating two lines works, which creates an ArrayList
of Lines, and after a new one is drawn, it is added to the ArrayList
, after the previously added lines in the ArrayList
are painted in the container. When I tried to add a Block and draw a Line, I could not start drawing a Line, which I presume is because even though the Block only takes up 20x20 space, it "takes up" the entire container, so that nothing else can be added.