Java复选框定位

时间:2015-07-10 09:52:19

标签: java swing

我是Java的新手,我正在创建一个登录表单。我遇到的问题是下图中看到的复选框的位置,我试图将其指定为直接从“密码”中的“P”下方开始。

this is the application when it is running

以下是代码:

    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);
    }
  }

我不确定为什么复选框不符合标签,任何帮助将不胜感激。感谢。

2 个答案:

答案 0 :(得分:2)

试试这个:

checkBox = new JCheckBox("");
checkBoxLabel = new JLabel("Keep me logged in");

然后在添加组件时

//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);

答案 1 :(得分:0)

您必须设置fill

GridBagConstraints属性
  //username label    
    gbc.anchor = GridBagConstraints.LINE_END;
    gbc.fill=GridBagConstraints.BOTH;//this will do the trick