0

Hello I have a JPanel which holds many components in it. Now I have a JPanel component which holds some input forms in it, the component is sized as 400x400 px.

I need this component to be centered in the JPanel component that holds it, horizontally and vertically, so the 400x400 px component will be in the center.

I could simply do setLayout(null); to disable the layout and then do:

component.setLocation( ( width / 2) - 400, (height / 2) - 400);

But this is a bad practice IMO and should be done using Layout managers.

I've tired using the BorderLayout, using BorderLayout.CENTER, but it just makes the component on fullscreen, not an 400x400 area.

I've tried using BoxLayout, using Box.createHorizontalBox but it seems like it only supports either horizontal or vertical, one at once, correct me if I am wrong.

Is there a simple way to center a component in a component using Layout Managers without losing the component's size?

@Override
public void init() throws Exception {
    GridBagLayout layout = new GridBagLayout();
    super.setLayout(layout);
    this.loginPane = new JPanel();
    this.loginPane.setSize(400, 400);
    this.loginPane.setBackground(Color.RED);
    JTextField username = new JTextField();
    username.setSize(200, 45);

    super.add(loginPane, null);
}

Shows this:

img
(source: gyazo.com)

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Artemkller545
  • 979
  • 3
  • 21
  • 55
  • You could use GridBagLayout, which centers everything by default (your panel will be in the center). Insets allow you to give outter-padding, or you could just make the frame a bigger size than the panel to give the look that you want – Vince Jul 25 '14 at 15:21
  • @VinceEmigh The duplicate question doesn't answer my question. I asked to add JPanel component, not an image. I get a small 16x16 red background centered (i used setBacground to red), instead of 400x400? see my modified code. – Artemkller545 Jul 25 '14 at 19:59
  • You must be using `GridBagConstraints` with GBL. Create an instance of it, and insteald of setting the constraints parameter to `null`, set it to the constraints. Also, you shouldn't use setSize to size your compoment; the LayoutManager should be managing that. You can increase the size of your panel by increasing the `ipadx` and `ipady` (inner padding) of your constraints. Keep in mind that you must reset these values after adding, or else they will apply to the next component that uses the constraints – Vince Jul 25 '14 at 20:40

0 Answers0