[ACCEPTED]-How to add multiple components to a JFrame?-jframe
You have 2 choices.
You can change the layout 19 of your frame:
JFrame frame;
frame.setLayout(new FlowLayout());
Now, if you add more than 18 one box, it will show up on the frame.
The 17 other option is to do what you said you 16 tried. (Adding a panel to the frame)
JPanel pane = new JPanel();
frame.add(pane);
(add the boxes to 'pane')
Also, you 15 should be careful with the sizing of your 14 Box
. You will probably want a call to setPreferredSize()
somewhere 13 in the creation of the Box
. This will tell 12 Java what size to make the box when it is 11 added to the layout.
You should also take 10 a look at the Java Layout Manager Tutorials. There is lots of great 9 info there.
And, one more thing. The reason 8 only one box at a time was being displayed 7 on the frame was because JFrame's layout 6 manager is BorderLayout
. And, when you call add
on a component 5 that has a BorderLayout, the component is 4 automatically added to the center of the 3 component. Subsequent calls to add
will overwrite 2 the center component, leaving only one component 1 in the middle.
You do need to check out other layout managers. JFrame 15 by default uses BorderLayout and without 14 specifying the "place" a component is added, they 13 get added to CENTER. Depending on what 12 you want your UI to look like depends on 11 the layout manager to use. I would suggest 10 maybe using Netbeans GUI builder.
EDIT: Missed 9 the part about what you want to add but 8 the concept is still the same, if you just 7 add these components to the default layout 6 manager, they will get overwritten. Sounds 5 like you may need to do your painting inside 4 of just one of your Box components or create 3 a JPanel and set the layout to null
but then 2 you would have to place them explicitly. Really 1 depends on what you want to do with it exactly.
Do your layout on paper first, then read 9 up on Swing layout managers.
Be aware that 8 some Swing components only allow one component 7 to be added to them. I've run across this 6 when using Tabbed panes. Each tab can only 5 accept one control (JPane?) so you have 4 to create a separate panel with a layout 3 to arrange the related controls and then 2 as a unit add the pane to the tab. There 1 are similar arrangements in the Swing library.
You could set the frame layout to null
and then 2 use setBounds()
to position your boxes exactly where 1 you want.
Thank you for all your answers.
Since I am 8 using my own custom class, Box, I have the 7 ability of setting the position of my the 6 rectangle through the paint method.
I realized 5 my Box class was extending the wrong thing. It 4 should have been extending javax.swing.Jcomponent.
If 3 I now use a panel with an OverlayLayout, add 2 my components to that panel, they all show 1 up properly.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.