Luciid Luciid - 7 months ago 13
Java Question

How to add a JPanel to a JFrame with Runnable method

When i create a JPanel and add it to my JFrame and add my canvas to it (space) it will show just the JPanel and not the any of the graphics. Why is it only showing the JPanel when i want it to show both of them at the same time?

Source Code:http://pastebin.com/Cw9E0a8j

Answer

If youre intent was to add the your canvas inside the jPanel you try change the following lines in your source

Original Code :

frame.add(p);
frame.add(space, BorderLayout.CENTER);

Suggested Code :

 p.add(space);
 frame.add(p, BorderLayout.CENTER);

If You are willing to view both JPanel and the canvas in the JFrame try giving positioning to the canvas also.But a different layout will do better. Try out the given example.

Original Code :

    frame.setLayout(new BorderLayout());

    frame.add(p);
    frame.add(space, BorderLayout.CENTER);

Suggested Code 1 : By providing the position to the JPanle in the Border Layout.

    frame.setLayout(new BorderLayout());

    frame.add(p, BorderLayout.NORTH);
    frame.add(space, BorderLayout.CENTER);

Suggested Code 2 : By Changing the Layout of the JFrame.

    frame.setLayout(new GridLayout(0,2));       

    frame.add(p);
    frame.add(space);

For more information please refer official documentation[1].
[1]. https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html

Comments