tags:

views:

68

answers:

1

I tried setting the position of child-panel at the center of parent-panel by using

parent_panel.setLayout(new BorderLayout());
parent_panel.add(child_panel, BorderLayout.CENTER);

But it's getting added at the middle of horizontal screen but vertically at top.

What do I need to do to add it at center of screen vertically and horizontally?

+1  A: 

If I understand correctly, you want an interface something like this:

+-------- Parent panel --------+
|                              |
|                              |
|    +--- Child panel ----+    |
|    |                    |    |
|    |                    |    |
|    |                    |    |
|    |                    |    |
|    +--------------------+    |
|                              |
|                              |
+------------------------------+

...and you have no other components being added to the parent panel.

If this is the case, you have two choices that I know of (based on this question, which I apparently answered):

  1. Use a GridBagLayout with an empty GridBagConstraints object, like this:

    parent_panel.setLayout(new GridBagLayout());
    parent_panel.add(child_panel, new GridBagConstraints());
    
  2. Use a BoxLayout, like this:

    parent_panel.setLayout(new BoxLayout(parent_panel, BoxLayout.PAGE_AXIS));
    Box horizontalBox = Box.createHorizontalBox(); 
    horizontalBox.add(Box.createHorizontalGlue()); 
    horizontalBox.add(child_panel); 
    horizontalBox.add(Box.createHorizontalGlue()); 
    Box verticalBox = Box.createVerticalBox(); 
    verticalBox.add(Box.createVerticalGlue()); 
    verticalBox.add(horizontalBox); // one inside the other
    verticalBox.add(Box.createVerticalGlue()); 
    
Michael Myers