2

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..

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Neo
  • 395
  • 2
  • 6
  • 23

3 Answers3

4

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
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 2
    @Neo: For reference, here's a basic [example](http://stackoverflow.com/a/5751044/230513) using `JLabel.CENTER`. – trashgod Jul 25 '13 at 00:51
1

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.

Achi113s
  • 55
  • 7
  • Thank's for your answer, but I could find the solution a few days ago, I forgot to mark the answer as "accepted". By the way, thank you ^^ – Neo Aug 15 '13 at 16:27
0

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);