Reputation: 267
I tried looking but no questions were helpful. Here's my code to begin with:
Player player = new Player();
Block1 block1 = new Block1();
JFrame ow = new JFrame();
ow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ow.setSize(500,500);
ow.setTitle("My Game");
ow.setVisible(true);
ow.setLocation(400, 100);
ow.add(block1);
ow.add(player);
but it will only add the last one, someone said (when I searched old questions) that it erases the previous one because they are both in the same location. So I modified it this way:
JPanel jp = new JPanel();
jp.setSize(500, 500);
Player player = new Player();
Block1 block1 = new Block1();
JFrame ow = new JFrame();
jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));
jp.add(player);
jp.add(block1);
ow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ow.setSize(500,500);
ow.setTitle("My Game");
ow.setVisible(true);
ow.setLocation(400, 100);
ow.add(jp);
It did work, putting them both visible but... it sort of made two square panels so I can't go near block 1
with my player
.
Any help?
Upvotes: 0
Views: 226
Reputation: 14413
JFrame by default uses BorderLayout. If you don't specify where you will put the component, it's going to be put in BorderLayout.CENTER
. You can't put 2 or more components in the same position. To prevent this undesired behaviour you have to set different constraints.
For example:
jframe.add(someComponent, BorderLayout.LINE_END);//constraint indicating position
Read more in tutorials : How to use BorderLayout.
If this layout don't fit what you need, try to use another LayoutManager or mix them.
Take a look at A Visual Guide to LayoutManagers
Upvotes: 2