Question

I can't get GridBagLayout to work.

Here is a picture of a result I want(top left) and the result I am getting(center)

enter image description here

I want to have a text field followed by an add and remove button on the same row, and then have multiple rows like it shows in the top left.

I dont have a lot of experience with GridBagLayout and it is starting to get pretty frustrating. This is only a small portion of my GUI. GridBagLayout is the layout I want to use. How can I get the 3 component chunks to align on the Y-Axis and not keep adding to the X-Axis?

    file1_tf = new JTextField(20);
    file1_tf.setEditable(false);
    file_select_panel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();

    gbc.gridx = 0;
    gbc.gridy = 0;
    file_select_panel.add(file1_tf);
    gbc.gridx = 1;
    gbc.gridy = 0;
    file_select_panel.add(add_f1_button);
    gbc.gridx = 2;
    gbc.gridy = 0;
    file_select_panel.add(rem_f1_button);

    gbc.gridx = 0;
    gbc.gridy = 1;
    file_select_panel.add(file3_tf);
    gbc.gridx = 1;
    gbc.gridy = 1;
    file_select_panel.add(add_f3_button);
    gbc.gridx = 2;
    gbc.gridy = 1;
    file_select_panel.add(rem_f3_button);
Was it helpful?

Solution

There are a number of ways to achieve, but based on you code, the simplest would be to ensure you are passing the GridBagConstraints along with the component you are adding when you add them...

file_select_panel.add(file1_tf, gbc);
//...
file_select_panel.add(add_f1_button, gbc);
//...
file_select_panel.add(rem_f1_button, gbc);
//...etc...

You might find taking a closer look at How to Use GridBagLayout helps, in particular, take a look at the section labelled "Specifying Constraints"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top