Neo
Neo

Reputation: 397

Java: Centering a component inside GridLayout

I have the following java code that creates a basic window:

JPanel panelCampos, panelBoton;
JLabel labelIdCedula, labelContrasena;
JTextField textFieldIdCedula, textFieldContrasena;
JButton buttonLogin;

panelCampos = new JPanel();
labelIdCedula = new JLabel("ID / Cédula:");
textFieldIdCedula = new JTextField();
labelContrasena = new JLabel("Contraseña:");
textFieldContrasena = new JTextField();
panelBoton = new JPanel();
buttonLogin = new JButton("Iniciar sesión");

setIconImage(Config.ICONO);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(380, 214);
setLayout(new BorderLayout());
setLocationRelativeTo(null);
setResizable(false);

panelCampos.setLayout(new GridLayout(2, 2));
panelCampos.add(labelIdCedula);
panelCampos.add(textFieldIdCedula);
panelCampos.add(labelContrasena);
panelCampos.add(textFieldContrasena);

panelBoton.add(buttonLogin);

add(panelCampos, BorderLayout.CENTER);
add(panelBoton, BorderLayout.SOUTH);
setVisible(true);

The result is:

Window result

And I want that each component of the matrix (GridLayout) stays centered instead of displaying at the left and with different size, how can I do that?

Thank you..

Upvotes: 2

Views: 13121

Answers (3)

Jordan Doerksen
Jordan Doerksen

Reputation: 46

another trick to fix what you have would be to add the JTextFields to JPanels and apply GridBagLayout to the Panels

JPanel pnlMain = new JPanel();
pnlMain.setLayout(New GridLayout(2,2));
JPanel pnl1 = new JPanel();
pnl1.setLayout(new GridBagLayout());
JTextField txtField = new JTextField();
pnl1.add(txtField);
pnlMain.add(pnl1);

Upvotes: 0

Achi113s
Achi113s

Reputation: 55

To center them I'd put each component(Or more if you want them right next to each other) In a JPanel that is using FlowLayout(the default Layout manager) and then add those JPanels to the JFrame. The JPanels adjust to the GridLayout but the components on the JPanels stay in the same position.

Upvotes: 1

mKorbel
mKorbel

Reputation: 109823

And I want that each component of the matrix (GridLayout) stays centered instead of displaying at the left and with different size, how can I do that?

  • not possible with GridLayout, because all elements in GridLayout has the same size on the screen, more in Oracle tutorial, for real and nice Swing GUI you would need to use GridBadLayout or SpringLayout, custom MigLayout, TableLayout

  • simple hacks for current code

    1. use SwingConstants for JLabel e.g. labelIdCedula = new JLabel("ID / Cédula:", SwingConstants.CENTER/*RIGHT*/);
    2. don't to setSize(result shows quite terrible sizing for JTextFields), define size for JTextField(int columns), then to call JFrame.pack() instead of any sizing

Upvotes: 4

Related Questions