我已经为一个项目自学了几天的 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);
我需要一种方法将用户名和密码居中,以便它们与其他所有内容匹配,并在底部的 2 个按钮之间添加一些空白垂直空间。抱歉,如果这是一个愚蠢的问题:|
最佳答案
您的用户名/密码包含两个不同列中的两个组成部分。因此,如果您希望所有组件居中,您有两个选择:
为每个标签/文本字段组件创建一个单独的面板。然后,您可以将面板添加为单个组件,这意味着它将与所有其他组件一起放置在第一列中。
让所有其他组件“跨越”两列。所以现在它们将占据与标签/文本字段组件相同的宽度。在这种情况下,您需要指定
gridWidth
约束。
阅读 Swing 教程中关于 How to Use GridBagLayout 的部分有关 GridBagLayout 使用的各种约束的更多信息。
also add some blank vertical space between the 2 buttons at the bottom
再次看看限制因素。您可以使用insets
约束。
关于java - 使用 gridbaglayout 在 javax swing 中定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48799351/