Search code examples
javaswinglayout-managergridbaglayout

GridBagLayout ignores anchor


I have some problems with my GridBagLayout I want to put the buttons to the left side of the screen exactly like they are now. I know I have my weight to 0 but changing it to 1 breaks the constellation and I don't know how I can archive both.

How it looks atm

If that helps

public class CreatePanel extends JPanel {

    private static final Insets WEST_INSETS = new Insets(5, 0, 5, 1);;

    public CreatePanel(JPanel mainPanel) {
        setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
        this.mainPanel = mainPanel;
        setPreferredSize(new Dimension(400, 200));
        setBackground(Color.GRAY);

        add(Box.createVerticalGlue());
        add(createGameLabel());
        add(Box.createRigidArea(new Dimension(0,100)));
        add(createJPanel());
        add(Box.createVerticalGlue());
        add(Box.createVerticalGlue());
    }

    private GridBagConstraints createGbc(int x, int y) {

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = 1;
        gbc.gridheight = 1;

        gbc.anchor = GridBagConstraints.FIRST_LINE_START;

        gbc.insets = WEST_INSETS;
        gbc.weightx = 0.0;
        gbc.weighty = 0.0;
        return gbc;
    }

    private JPanel createJPanel() {
        bottemPanel = new JPanel();
        bottemPanel.setBackground(Color.ORANGE);
        bottemPanel.setLayout(new GridBagLayout());

        gbc = createGbc(0,0);
        gbc.gridwidth=2;
        bottemPanel.add(createRandomWordButton(),gbc);
        gbc = createGbc(0,1);
        bottemPanel.add(createWordTextField(),gbc);
        gbc = createGbc(1,1);
        bottemPanel.add(createUseWordButton(),gbc);

        return bottemPanel;
    }

    private JLabel createGameLabel() {...}

    private JButton createUseWordButton() {...}

    private JTextField createWordTextField() {...}
}

Solution

  • I know I have my weight to 0 but changing it to 1 breaks...

    It looks like you are using the BoxLayout to vertically center the child panel. However by default a JPanel is centered horizontally in the space available. So in your createJPanel method try adding:

    bottom.setAlignmentX(0.0f);
    

    If that doesn't work you may instead need to use a wrapper panel for the bottom panel:

    //return bottemPanel;
    JPanel wrapper = new JPanel(); // 
    wrapper.setAlignmentX(0.0f);
    wrapper.add(bottom);
    return bottomPanel;
    

    Or another solution is to add a dummy component with a weightx value of 1.0f.

    JLabel dummy = new JLabel(" "); 
    gbc.gridx = ?;
    gbc.weightx = 1.0f;
    add(dummy, gbc);