Tokisaki Toru
Tokisaki Toru

Reputation: 1

JPanel gets smaller (a lot) after add to another JPanel

After I added my canvas (blue one) to canvas2 (green one), canvas got really small and I can't tell why. Help me! Here is my code:

public static void main(String[] args) {

    JPanel canvas = new JPanel();
    JPanel canvas2 = new JPanel();

    canvas.setBounds(40, 40, 200, 200);
    canvas.setBackground(Color.BLUE);

    canvas2.setBounds(40, 40, 200, 200);
    canvas2.setBackground(Color.GREEN);
    canvas2.add(canvas);

    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 600, 600);
    window.getContentPane().add(canvas2);
    window.setVisible(true);
}

and the result:

enter image description here

Upvotes: 0

Views: 51

Answers (2)

user9245461
user9245461

Reputation:

canvas (blue JPanel) is completely empty. Therefore, it's LayoutManager is resizing it to the smallest possible size. It'll get bigger if you add some components to it. Alternatively, you could do

 canvas.setPreferredSize(new Dimension(200, 200));

but this is generally a bad idea for several reasons.

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Your code is ignoring the container layout managers -- BorderLayout for the JFrame's contentPane and FlowLayout for the JPanel. The components added to these containers will be sized by these layout managers.

You can find the layout manager tutorial here: Layout Manager Tutorial, and you can find links to the Swing tutorials and to other Swing resources here: Swing Info.

Upvotes: 1

Related Questions