我在CS课程中一直在研究这个程序,我不确定为什么GridBagLayout或GridBagConstraints不能正常工作。
现在,我试图让这些标签像他们应该的那样对齐(根据这本Java书籍),但他们目前没有做任何事情。
任何帮助都将不胜感激。
我的代码:
public class Main {
private static final int WIDTH = 1920, HEIGHT = 1080;
private Database database = new Database();
public static void main(String[] args) {
// Swing GUI
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JPanel formPanel = new JPanel(new GridBagLayout());
JLabel header = new JLabel();
GridBagConstraints gbc = new GridBagConstraints();
frame.setMinimumSize(new Dimension(WIDTH/2, HEIGHT/2));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
mainPanel.add(formPanel);
gbc.gridx = 0;
gbc.gridy = 0;
header.setText("First Name: ");
formPanel.add(header, gbc);
gbc.gridy++;
formPanel.add(new JLabel("Last Name: "));
gbc.gridy++;
formPanel.add(new JLabel("Email: "));
gbc.gridy++;
formPanel.add(new JLabel("Username: "));
gbc.gridy++;
formPanel.add(new JLabel("Password: "));
gbc.gridy++;
}
}