3

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

}
2

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Ok, nice to hear. Do not forget to vote as best whatever answer you think it answers your question more completely.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.