[英]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個按鈕之間添加一些垂直空白。 抱歉,這是一個愚蠢的問題:|
您的用戶名/密碼在兩個不同的列中包含兩個組件。 因此,如果要使所有組件居中,則有兩個選擇:
為每個標簽/文本字段組件創建一個單獨的面板。 然后,您可以將面板添加為單個組件,這意味着它將與所有其他組件一起放置在第一列中。
將所有其他組件“ span”分為兩列。 因此,現在它們將采用與標簽/文本字段組件相同的寬度。 在這種情況下,您將需要指定gridWidth
約束。
閱讀Swing教程中有關如何使用GridBagLayout的部分, 以獲取有關GridBagLayout使用的各種約束的更多信息。
在底部的兩個按鈕之間也添加一些垂直空白
再次,查看約束。 您可以使用insets
約束。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.