我在 JPanel 中有 5 个组件。我添加的前 4 个组件看起来一切都很顺利。但是,当我尝试向 JPanel 添加第 5 个组件时,组件之间的间距会因任何原因发生变化!
没有第 5 个组件:
First Name: [..............]
Last Name: [..............]
和:
First Name:---------------- [.............]
Last Name:----------------- [.............]
What is your favorite sport:
假装标签和文本字段之间的破折号是空格
标签和文本字段之间的间距发生了变化!这是我的代码,请帮助我!
public static void main(String[] args)
{
JFrame frame = new JFrame("Survey");
frame.setSize(800, 600);
frame.setLayout(new FlowLayout(FlowLayout.CENTER));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p1 = new JPanel(new GridBagLayout());
//LINE.START = Top Left Corner
frame.add(p1);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 10, 10);
JLabel lblFirstN = new JLabel("First Name:");
JLabel lblLastN = new JLabel("Last Name:");
JLabel lblFavSport = new JLabel("What is your favorite sport:");
JTextField txtFirstN = new JTextField();
txtFirstN.setPreferredSize(new Dimension(100, 20));
JTextField txtLastN = new JTextField();
txtLastN.setPreferredSize(new Dimension(100, 20));
gbc.gridx = 0;
gbc.gridy = 0;
p1.add(lblFirstN, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
p1.add(txtFirstN, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
p1.add(lblLastN, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
p1.add(txtLastN, gbc);
//this block of code is what is screwing me
gbc.gridx = 0;
gbc.gridy = 2;
p1.add(lblFavSport, gbc);
}