简体   繁体   中英

Java add more than one JPanel objects into JFrame

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);
    }

}

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).

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.

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.

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