How to add multiple components to a JFrame?

I have a JFrame.

I also have a Box class which extends Component. This box class has a paint method which makes a filled rectangle.

When I add multiple of these Box components to my JFrame, only the most recently added one is displayed when I call repaint on the JFrame.

I took a look at the layout managers, but I am not sure that's what I want. All I want is to be able to make an animation of whole bunch of rectangles wherever I want on the screen.

(I also tried creating a panel, adding the panel to the JFrame, and then adding all the Box components to the panel. This did not work either).

Thanks in advance!


Solution 1:

You have 2 choices.

You can change the layout of your frame:

JFrame frame;
frame.setLayout(new FlowLayout());

Now, if you add more than one box, it will show up on the frame.

The other option is to do what you said you tried. (Adding a panel to the frame)

JPanel pane = new JPanel();
frame.add(pane);
(add the boxes to 'pane')

Also, you should be careful with the sizing of your Box. You will probably want a call to setPreferredSize() somewhere in the creation of the Box. This will tell Java what size to make the box when it is added to the layout.

You should also take a look at the Java Layout Manager Tutorials. There is lots of great info there.

And, one more thing. The reason only one box at a time was being displayed on the frame was because JFrame's layout manager is BorderLayout. And, when you call add on a component that has a BorderLayout, the component is automatically added to the center of the component. Subsequent calls to add will overwrite the center component, leaving only one component in the middle.