[英]How to add 2 objects or more to one JFrame in Java?
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
. 它确实有效,将它们都看得见但是......它有两个方形面板,所以我不能靠近我的
player
block 1
。 Any help? 有帮助吗?
JFrame by default uses BorderLayout . 默认情况下,JFrame使用BorderLayout 。 If you don't specify where you will put the component, it's going to be put in
BorderLayout.CENTER
. 如果您没有指定放置组件的位置,那么它将放在
BorderLayout.CENTER
。 You can't put 2 or more components in the same position. 您不能将2个或更多组件放在同一位置。 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 . 阅读更多教程: 如何使用BorderLayout 。
If this layout don't fit what you need, try to use another LayoutManager or mix them. 如果此布局不符合您的需要,请尝试使用另一个LayoutManager或混合它们。
Take a look at A Visual Guide to LayoutManagers 看看LayoutManagers的可视指南
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.