使用gridbaglayout在javax swing中定位

Positioning in javax swing with gridbaglayout

为了一个项目,我自学了几天摇摆舞,现在我正试图弄清楚如何使用网格包布局来定位组件。除了一些小问题,我得到了大部分。如果有人可以提供帮助,将不胜感激。我已经尝试了很多不同的方法 D:

    ...
    titlePanel.setLayout(new GridBagLayout());
    titlePanel.setBackground(BLUE);

    header = new JLabel ("Gradebook");
    header.setLocation(200,400);
    header.setFont(new Font("Serif", Font.BOLD, 50));
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.anchor = GridBagConstraints.CENTER;
    titlePanel.add(header,gbc);

    date = new Date();
    currentDate = new JLabel (fmt.format(date));
    currentDate.setFont(new Font("Serif", Font.PLAIN, 14));
    ActionListener updateTime = new ActionListener() {
        public void actionPerformed (ActionEvent e) {
            date = new Date();
            currentDate.setText(fmt.format(date));
        }
    };
    Timer timer = new Timer (1000, updateTime);
    timer.start();
    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.anchor = GridBagConstraints.CENTER;
    titlePanel.add(currentDate, gbc);

    JLabel userName = new JLabel ("Username:  ");
    gbc.gridx = 0;
    gbc.gridy = 2;
    gbc.anchor = GridBagConstraints.EAST;
    titlePanel.add(userName, gbc);

    JTextField username = new JTextField (10);
    gbc.gridx = 1;
    gbc.gridy = 2;
    gbc.anchor = GridBagConstraints.WEST;
    titlePanel.add(username, gbc);

    JLabel password = new JLabel ("Password:  ");
    gbc.gridx = 0;
    gbc.gridy = 3;
    gbc.anchor = GridBagConstraints.EAST;
    titlePanel.add(password, gbc);

    JPasswordField Password = new JPasswordField (10);
    gbc.gridx = 1;
    gbc.gridy = 3;
    gbc.anchor = GridBagConstraints.WEST;
    titlePanel.add(Password, gbc);
    JButton login = new JButton ("Login");
    gbc.gridx = 0;
    gbc.gridy = 4;
    gbc.anchor = GridBagConstraints.CENTER;
    titlePanel.add(login, gbc);

    JButton newAccount = new JButton ("Create New Account");
    gbc.gridx = 0;
    gbc.gridy = 5;
    gbc.anchor = GridBagConstraints.CENTER;
    titlePanel.add(newAccount, gbc);
    mainFrame.add(titlePanel);

所以当我 运行 登录屏幕的代码时,它出现了这个

我需要一种方法将用户名和密码居中,以便它们与其他所有内容匹配,并在底部的 2 个按钮之间添加一些垂直的空白 space。对不起,如果这是一个愚蠢的问题:|

您的 username/password 在两个不同的列中包含两个组件。因此,如果您希望所有组件居中,您有两个选择:

  1. 为每个 label/text 字段组件创建一个单独的面板。然后您可以将面板添加为单个组件,这意味着它将与所有其他组件一起放置在第一列中。

  2. 所有其他组件 "span" 两列。所以现在它们将占用与 label/text 字段组件相同的宽度。在这种情况下,您需要指定 gridWidth 约束。

阅读有关 How to Use GridBagLayout 的 Swing 教程部分,了解有关 GridBagLayout 使用的各种约束的更多信息。

also add some blank vertical space between the 2 buttons at the bottom

再次,查看约束条件。您可以使用 insets 约束。