使用gridbaglayout在javax swing中定位

使用gridbaglayout在javax swing中定位,java,swing,gridbaglayout,Java,Swing,Gridbaglayout,我为一个项目自学了几天swing,现在我正试图找出如何使用网格袋布局定位组件。除了一些小问题,我得到了大部分。如果有人能帮忙,我们将不胜感激。我尝试过很多不同的方法D: ... titlePanel.setLayout(new GridBagLayout()); titlePanel.setBackground(BLUE); header = new JLabel ("Gradebook"); header.setLocation(200,400);

我为一个项目自学了几天swing,现在我正试图找出如何使用网格袋布局定位组件。除了一些小问题,我得到了大部分。如果有人能帮忙,我们将不胜感激。我尝试过很多不同的方法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);
因此,当我运行登录屏幕的代码时,它会显示以下内容


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

您的用户名/密码在两个不同的列中包含两个组件。因此,如果希望所有组件居中,有两个选项:

  • 为每个标签/文本字段组件创建单独的面板。然后可以将面板作为单个构件添加,这意味着它将与所有其他构件一起放置在第一列中

  • 让所有其他组件“跨越”两列。因此,现在它们将占用与标签/文本字段组件相同的宽度。在这种情况下,需要指定
    gridWidth
    约束

  • 有关GridBagLayout使用的各种约束的更多信息,请阅读上的Swing教程部分

    同时在底部的两个按钮之间添加一些空白垂直空间


    再次,看看约束。您可以使用
    插入约束。

    谢谢MUCH@bobbybobbins,忘记了教程链接。有关建议约束,请参见教程。您还可能会发现未来问题的其他约束。