How to add multiple components to a JFrame?

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.

Leave a Comment