简体   繁体   中英

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 . Any help?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM