Java: Centering a component inside GridLayout
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 inGridLayout
has the same size on the screen, more in Oracle tutorial, for real and nice Swing GUI you would need to useGridBadLayout
orSpringLayout
, customMigLayout
,TableLayou
tsimple hacks for current code
- use
SwingConstants
forJLabel
e.g.labelIdCedula = new JLabel("ID / Cédula:", SwingConstants.CENTER/*RIGHT*/);
- don't to
setSize
(result shows quite terrible sizing forJTextFields
), define size forJTextField(int columns)
, then to callJFrame.pack()
instead of any sizing
- use
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, 2022Comments
-
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:
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 almost 11 years@Neo: For reference, here's a basic example using
JLabel.CENTER
. -
Neo almost 11 yearsThank'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 ^^