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:
(source: gyazo.com)