Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 481
tprieboj Avatar asked Nov 19 '25 03:11

tprieboj


1 Answers

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.

like image 153
mosemos Avatar answered Nov 21 '25 17:11

mosemos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!