I am looking for a solution to align two JTextFields
with different sizes in a GridBagLayout
. Instead of maintaining the original size of the JTextField
I would prefer both to end in the same column.
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.ipady = 10;
JLabel lb1 = new JLabel("User: ");
JLabel lb2 = new JLabel("Name: ");
JLabel lb3 = new JLabel("First ");
JLabel nameLB = new JLabel("Last ");
JTextField tf1 = new JTextField(20);
JTextField tf2 = new JTextField(20);
JTextField nameTF = new JTextField(20);
gbc.gridx = 0;
gbc.gridy = 0;
add(lb1,gbc);
gbc.gridx = 0;
gbc.gridy = 1;
add(lb2,gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 2;
add(tf1,gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 1;
add(lb3,gbc);
gbc.gridx = 2;
gbc.gridy = 1;
gbc.gridwidth = 1;
add(tf2,gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridwidth = 1;
add(nameLB,gbc);
gbc.gridx = 2;
gbc.gridy = 2;
gbc.gridwidth = 1;
add(nameTF,gbc);
I assume tf1 is what causing the issue. If this text field is not extending to the end you could add the fill constraint. Try
gbc.fill = GridBagConstraints.HORIZONTAL;
pane.add(tf1, gbc);
If this is not working can you post your full code or more description about your problem?