Wojciech Kazior Wojciech Kazior - 2 months ago 18
Java Question

GridBagLayout issue

I am trying to use GridBagLayout. I need one JLabel centered vertically and horizontally - that is easy, I do not even have to create any GridBagConstraints. I also want to put a JButton in right-bottom corner and when I try to do it, my centered panel is moving to left or the button is moving up.

EXPECTING GETTING THIS OR THIS
+-----------+ +-----------+ +-----------+
| | | | | |
| | | | | |
| | | | | |
| +---+ | | +---+ | | +---+ |
| | | | | | | | | | | |
| +---+ | | +---+ | | +---++---+|
| | | | | | ||
| | | | | +---+|
| +---+ | +---+ | |
| | | | | | | |
+-------+---+ +-------+---+ +-----------+

bigPanel = new JPanel();
bigPanel.setPreferredSize(new Dimension(320, 640));
bigPanel.setLayout(new GridBagLayout());

label = new JLabel();
label.setPreferredSize(new Dimension(100,95));

button = new JButton();
button.setPreferredSize(new Dimension(100,25));

GridBagConstraints c = new GridBagConstraints();

c.anchor = GridBagConstraints.CENTER;
bigPanel.add(label, c);

c.anchor = GridBagConstraints.LAST_LINE_END;
bigPanel.add(button, c);


I was also trying to use other constraints which are described here http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html but every time something goes wrong.

Answer

anchorset the component position inside its cell, if the component doesn't fill the cell.

You have not define the grid of your layout. the default behaviour is to add the components from left to right.

Here is an example to achieve what you want using a GridBagLayout. The label and the button are put in the same cell, that fills the panel.

public class Test extends JPanel {
    public Test() {
        super();
        GridBagLayout gridBagLayout = new GridBagLayout();
        gridBagLayout.columnWeights = new double[] { 1.0 }; // expands the  1rst cell of the layout on the vertical axis
        gridBagLayout.rowWeights = new double[] { 1.0 }; // expands the 1rst cell of the layout on the horizontal axis
        setLayout(gridBagLayout);

        JLabel label = new JLabel("test");          
        label.setOpaque(true);
        label.setBackground(Color.RED);
        label.setPreferredSize(new Dimension(100, 95));
        GridBagConstraints gbc_label = new GridBagConstraints();
        gbc_label.gridx = 0; // set label cell (0,0)
        gbc_label.gridy = 0;
        gbc_label.insets = new Insets(0, 0, 5, 5);

        add(label, gbc_label);

        JButton button = new JButton("button");
        GridBagConstraints gbc_button = new GridBagConstraints();
        gbc_button.gridx = 0; // set buttoncell (0,0)
        gbc_button.gridy = 0;
        gbc_button.anchor = GridBagConstraints.SOUTHEAST;

        add(button, gbc_button);
        button.setPreferredSize(new Dimension(100, 25));
    }
}