Search code examples
javaswingform-layout

set all components to be center of the JFrame


I used FormLayout and I want to set all my components(JLabel and JtextField) to be in the center of the JFrame.

I tried using panel.setAlignmentX and panel.setAlignmentY but it doesn't work.

 panel.setAlignmentX(Component.CENTER_ALIGNMENT);
 panel.setAlignmentY(Component.CENTER_ALIGNMENT);

shown below is my piece of code, please help thanks.

import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

@SuppressWarnings("serial")
public class UI extends JFrame {

    private JPanel panel = new JPanel();

    public UI() {

    FormLayout layout = new FormLayout(
            "pref, pref, pref, pref", 
            "pref, pref, pref, pref");

        panel.setLayout(layout);
        CellConstraints cc = new CellConstraints();

        panel = new JPanel (layout);

        panel.add(new JLabel("L1 "), cc.xy(2, 2));
        panel.add(new JTextField(15), cc.xy(3, 2));

        panel.add(new JLabel("L2 "), cc.xy(2, 3));
        panel.add(new JTextField(15), cc.xy(3, 3));    
        panel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.setAlignmentY(Component.CENTER_ALIGNMENT);
        add(panel);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setSize(510,400);
        setLocationRelativeTo(null);
        setResizable(false);
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new UI().setVisible(true);

            }
        });
    }
}

Solution

  • Use a GridBagLayout. By default any component (panel) added to the layout will be centered:

    //add(panel);
    setLayout( new GridBagLayout() );
    add(panel, new GridBagConstraints());
    

    This will allow you to use your FormLayout on the panel containing your components. Now the content pane is using the GridBagLayout, so your form will be centered.