Reputation: 97
I'm relatively new to Java and I am creating a login form. The problem I am having is the position of the checkbox seen in the picture below, I am trying to assign it to start directly below the "P" in "Password.
Here is the code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Login extends JPanel{
private static JLabel usernameLabel, passwordLabel;
private static JTextField usernameField;
private static JPasswordField passwordField;
private static JCheckBox checkBox;
private static JButton loginButton;
GridBagConstraints gbc = new GridBagConstraints();
public Login(){
//layout
setLayout(new GridBagLayout());
//spacing between each component
gbc.insets = new Insets(1,1,1,1);
//new instance of objects
usernameLabel = new JLabel("Username:");
passwordLabel = new JLabel("Password:");
usernameField = new JTextField(10);
passwordField = new JPasswordField(10);
checkBox = new JCheckBox("Keep me logged in");
loginButton = new JButton("Login");
//username label
gbc.anchor = GridBagConstraints.LINE_END;
gbc.gridx = 0;
gbc.gridy = 0;
add(usernameLabel, gbc);
//password label
gbc.gridx = 0;
gbc.gridy = 1;
add(passwordLabel, gbc);
//username textfield
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 1;
gbc.gridy = 0;
add(usernameField, gbc);
//password textfield
gbc.gridx = 1;
gbc.gridy = 1;
add(passwordField, gbc);
//keep logged in checkbox
gbc.gridx = 0;
gbc.gridy = 2;
add(checkBox, gbc);
//login button
gbc.gridx = 1;
gbc.gridy = 3;
add(loginButton, gbc);
}
}
I'm not sure why the checkbox isn't in-line with the labels, any help will be appreciated. Thanks.
Upvotes: 2
Views: 1139
Reputation: 5818
You have to set the fill
Property of GridBagConstraints
//username label
gbc.anchor = GridBagConstraints.LINE_END;
gbc.fill=GridBagConstraints.BOTH;//this will do the trick
Upvotes: 0
Reputation: 35011
try this:
checkBox = new JCheckBox("");
checkBoxLabel = new JLabel("Keep me logged in");
Then when you are adding your components
//keep logged in checkbox
gbc.gridx = 0;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.WEST;
add(checkBox, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
add(checkBoxLabel);
Upvotes: 2