Search code examples
javaswinglayoutjlabeljtextfield

Center JTextField (not the text inside the field!)


How can I center a JTextField.

NOTE! I do not want to center the text in the JTextField (which is achieved using setHorizontalAlignment(JTextField.CENTER), but rather I want to center the actual JTextField in the space it is in, just as jLabel.setHorizontalAlignment(SwingConstants.CENTER) would do.


Solution

  • I recommend using GridBagLayout for this.

    panel.setLayout(new GridBagLayout());
    GridBagConstraints center = new GridBagConstraints();
    center.anchor = GridBagConstraints.CENTER;
    center.fill = GridBagConstraints.NONE;
    panel.add(textField, center);