Java: Centering a component inside GridLayout

10,544

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
Share:
10,544
Neo
Author by

Neo

Just a guy who likes to learn too much about computers and software, I'm student of Computer Science and also interested in the videogame development. Glad to share with this great community!

Updated on June 28, 2022

Comments

  • Neo
    Neo almost 2 years

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

  • trashgod
    trashgod almost 11 years
    @Neo: For reference, here's a basic example using JLabel.CENTER.
  • Neo
    Neo almost 11 years
    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 ^^