Java add multiple JPanel objects to JFrame

I'm starting out and I don't know how to add more objects to the JFrame. How can I add multiple JPanels to a JFrame? Below I have tried.

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

}

      

+3


source to share


3 answers


Assuming JumpingBall

extends JPanel

, you can look at the java layout managers here: Link .



The default Layout

for JFrame

is located BorderLayout

, and if you did not specify where you want to add your component, then BorderLayout

by default it will center. As BorderLayout

you can not be more than one component in the same area. So, in your example, you will only have a second panel JumpingBall

in your frame. If you want to have more than one component in the center, you will need to create JPanel

and add those components to it using a different layout. The usual three layouts are BorderLayout

, FlowLayout

and GridLayout

. Take a look at the link above to see how the components are assembled.

+1


source


You can add multiple objects JPanel

to JFrame

using the method add

. If only one is shown, you may need to change the layout options or use the layout manager (see here for more).



+1


source


You only see one because it overlaps each other. Just specify setbound(x,y,x1,y1)

panels for your component and you will see your panel in place.

or use setLayout(new FlowLayout());

which one is going to order your component according to the other so that you don't override each other.

+1


source







All Articles