javaswinggridbaglayout

Java setBorder breaks component padding


When I set a border color to every item in a JPanel with GridBagLayout, the components collapse.

Collapsed

but when I remove the border off just one component, the padding stays as expected.

Normal

What am I doing wrong?

Border Setting:

    setBorder(BorderFactory.createLineBorder(Color.decode("#"+Constants.Display.OPTIONS_BORDER_COLOR)));

JPanel:

public class OptionsPanel extends JPanel {
    private AddMachineBtn addMachineBtn;
    private SearchField searchField;
    private SearchBtn searchBtn;

    private GridBagConstraints gbc;

    public OptionsPanel() {
        init();
        config();
        build();
    }

    private void init() {
        addMachineBtn = new AddMachineBtn("Add Machine");
        searchField = new SearchField("Search...");
        searchBtn = new SearchBtn("S");

        gbc = new GridBagConstraints();
        int i = Constants.Display.OPTIONS_PANEL_PADDING;
        gbc.insets = new Insets(i, i, i, i);
    }

    private void config() {
        setLayout(new GridBagLayout());
        setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.decode("#"+Constants.Display.OPTIONS_BORDER_COLOR)));
        setPreferredSize(new Dimension(0, Constants.Display.OPTIONS_PANEL_HEIGHT));
        gbc.gridy = 0;
        gbc.weightx = 1;
        gbc.weighty = 1;
        gbc.anchor = gbc.LINE_START;
    }

    private void build() {
        gbc.gridx = 0;
        add(addMachineBtn, gbc);

        gbc.weightx = 0;
        gbc.gridx = 1;
        add(searchField, gbc);

        gbc.gridx = 2;
        add(searchBtn, gbc);
    }
}

Solution

  • The fix to this was changing the following

    setSize(new Dimension(w,h));
    setMinimumSize(new Dimension(w,h));
    setMaximumSize(new Dimension(w,h));
    

    to

    setPreferredSize(new Dimension(w,h));
    setMinimumSize(new Dimension(w,h));
    setMaximumSize(new Dimension(w,h));