简体   繁体   中英

Center components inside JPanel using GridBagLayout

I am trying to center some components inside a JPanel, everything works when I press "Test Layout" inside "Customize Layout" option of JPanel's GridBagLayout, but it looks different when I run the program.

It should look like this: 在此处输入图片说明

Instead, when I run the program, it looks like this:

在此处输入图片说明

The program is structured like this:

在此处输入图片说明

So there are two problems:

  1. The password field is larger than the email address field. I have tried setting minimum, maximum and preferred size to (14, 22) to both of them but it doesn't work.

  2. Why are the buttons separated and how can I make them connect? (the right button has 0 left Inset)

Here is the initComponents() function:

private void initComponents()
    {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        loginButton = new javax.swing.JButton();
        signUpLabel = new javax.swing.JLabel();
        emailTextField = new javax.swing.JTextField();
        passwordField = new javax.swing.JPasswordField();
        star1 = new javax.swing.JLabel();
        star2 = new javax.swing.JLabel();
        loginToggleButton = new javax.swing.JToggleButton();
        signUpToggleButton = new javax.swing.JToggleButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(42, 46, 55));
        jPanel1.setLayout(new java.awt.GridBagLayout());

        loginButton.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
        loginButton.setText("Login");
        loginButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                loginButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.ipadx = 42;
        gridBagConstraints.ipady = 14;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(79, 116, 0, 0);
        jPanel1.add(loginButton, gridBagConstraints);

        signUpLabel.setFont(new java.awt.Font("Dialog", 1, 13)); // NOI18N
        signUpLabel.setText("Don't have an account?");
        signUpLabel.setPreferredSize(new java.awt.Dimension(149, 12));
        signUpLabel.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                signUpLabelMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt)
            {
                signUpLabelMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt)
            {
                signUpLabelMouseExited(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 6;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(18, 100, 42, 0);
        jPanel1.add(signUpLabel, gridBagConstraints);

        emailTextField.setMaximumSize(new java.awt.Dimension(14, 22));
        emailTextField.setMinimumSize(new java.awt.Dimension(14, 22));
        emailTextField.setPreferredSize(new java.awt.Dimension(14, 22));
        emailTextField.addFocusListener(new java.awt.event.FocusAdapter()
        {
            public void focusGained(java.awt.event.FocusEvent evt)
            {
                emailTextFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt)
            {
                emailTextFieldFocusLost(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 6;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.ipadx = 199;
        gridBagConstraints.ipady = 10;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(97, 70, 0, 0);
        jPanel1.add(emailTextField, gridBagConstraints);

        passwordField.setMaximumSize(new java.awt.Dimension(14, 22));
        passwordField.addFocusListener(new java.awt.event.FocusAdapter()
        {
            public void focusGained(java.awt.event.FocusEvent evt)
            {
                passwordFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt)
            {
                passwordFieldFocusLost(evt);
            }
        });
        passwordField.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                passwordFieldActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 6;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.ipadx = 199;
        gridBagConstraints.ipady = 10;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(18, 70, 0, 0);
        jPanel1.add(passwordField, gridBagConstraints);

        star1.setForeground(new java.awt.Color(255, 0, 0));
        star1.setText("*");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 6;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(106, 10, 0, 49);
        jPanel1.add(star1, gridBagConstraints);

        star2.setForeground(new java.awt.Color(255, 0, 0));
        star2.setText("*");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 6;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(25, 10, 0, 49);
        jPanel1.add(star2, gridBagConstraints);

        loginToggleButton.setBackground(new java.awt.Color(0, 224, 208));
        loginToggleButton.setText("Log In");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 4;
        gridBagConstraints.ipadx = 34;
        gridBagConstraints.ipady = 8;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(44, 0, 0, 0);
        jPanel1.add(loginToggleButton, gridBagConstraints);

        signUpToggleButton.setBackground(new java.awt.Color(48, 199, 32));
        signUpToggleButton.setText("Sign Up");
        signUpToggleButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                signUpToggleButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 25;
        gridBagConstraints.ipady = 8;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(44, 80, 0, 0);
        jPanel1.add(signUpToggleButton, gridBagConstraints);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>

Don't use setPreferredSize().

Each Swing component will determine its own size based on the properties of the component. In many cases this will be based on the text of the component.

For text fields that don't have default text you should create the components like:

//emailTextField = new javax.swing.JTextField();
//passwordField = new javax.swing.JPasswordField();
emailTextField = new javax.swing.JTextField(20);
passwordField = new javax.swing.JPasswordField(10);

So the component can determine its preferred size to display 20/10 characters. (It actually sizes itself to display "W" characters).

Also, there is generally no need to set the min/max size of the component as GridBagLayout will repect the preferred size unless you fill the cell.

Have you tried to use a different gridBagConstraints variable? As not doing so for two different components might cause some problems.

public class TestStack {
private static JTextField txtOne;
private static JTextField txtTwo;

public static void main(String[] args) {
    JFrame frame = new JFrame();
    GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[]{0, 0};
    gridBagLayout.rowHeights = new int[]{0, 0, 0, 0};
    gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
    gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
    frame.getContentPane().setLayout(gridBagLayout);

    txtOne = new JTextField();
    txtOne.setHorizontalAlignment(SwingConstants.CENTER);
    txtOne.setText("one");
    GridBagConstraints gbc_txtOne = new GridBagConstraints();
    gbc_txtOne.insets = new Insets(0, 0, 5, 0);
    gbc_txtOne.gridx = 0;
    gbc_txtOne.gridy = 0;
    frame.getContentPane().add(txtOne, gbc_txtOne);
    txtOne.setColumns(10);

    txtTwo = new JTextField();
    txtTwo.setHorizontalAlignment(SwingConstants.CENTER);
    txtTwo.setText("twodwqadadsadasdsa");
    GridBagConstraints gbc_txtTwo = new GridBagConstraints();
    gbc_txtTwo.insets = new Insets(0, 0, 5, 0);
    gbc_txtTwo.gridx = 0;
    gbc_txtTwo.gridy = 1;
    frame.getContentPane().add(txtTwo, gbc_txtTwo);
    txtTwo.setColumns(10);

    JLabel lblThree = new JLabel("three");
    lblThree.setHorizontalAlignment(SwingConstants.CENTER);
    GridBagConstraints gbc_lblThree = new GridBagConstraints();
    gbc_lblThree.gridx = 0;
    gbc_lblThree.gridy = 2;
    frame.getContentPane().add(lblThree, gbc_lblThree);
    frame.setVisible(true);
}
}

Try it

I'm not sure about the password field but for the separated buttons, you may create a new panel with a box layout. Then, you can put your buttons in there. After that, you can put your new panel inside your main panel. That worked in my current project. Hope it'd also work for yours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM