Reputation: 1703
I am a beginer and I dont know how to add more objects into JFrame. How could I add more than one JPanel objects into JFrame? Below is what I have tried.
Thanks for your help.
public class Init extends JFrame{
public Init(){
super("Ball");
Buttons t = new Buttons();
JumpingBall b1 = new JumpingBall();
JumpingBall b2 = new JumpingBall();
t.addBall(b1);
t.addBall(b2);
add(b1);
add(b2);
setSize(500,500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
}
Upvotes: 3
Views: 1184
Reputation: 610
You are seeing only one because it overlapping each other. Just provide setbound(x,y,x1,y1)
for you panel component and you will see your panel at location.
or use setLayout(new FlowLayout());
which is going to order your component in respective to other so you will not override each-other.
Upvotes: 1
Reputation: 111
Assuming that JumpingBall
extends JPanel
, you might want to have a look at the java layout managers here: Link.
The default Layout
for a JFrame
is the BorderLayout
and if you didn't specify where you want to add your component, The BorderLayout
will put it in the center by default. In BorderLayout
, you cannot have more that one component in the same area. So, in your example you will end up having only the second JumpingBall
panel in your frame. If you want to have more than one component at the center, then you will have to create a JPanel
and add those components to it using different Layout. The common three Layouts are the BorderLayout
, FlowLayout
and GridLayout
Please have a look at the provided link above to see how the components are arranged.
Upvotes: 1
Reputation: 6005
You can add a number of JPanel
objects in a JFrame
, using the add
method. If only one is displayed, you might need to change your Layout options or use a Layout Manager (Look here for more).
Upvotes: 1