Positioning components using GridBagLayout

I'm making a panel and I want to have the following layout:

The width of the panel occupies the entire width of the frame, and I want to have 4 buttons in the right corner of that panel.

I created a panel as container, and inside that panel I created another panel with the 4 buttons. The idea is that this panel with the buttons is in the right corner of the"container panel".

I managed to create the panel with the buttons with the layout I want, but I can't put it in the right corner of my container.

Follow My Code:

/**
 * @return {@link JPanel} com botões de ação.
 */
private JPanel createActionButtonPanel() {
    JPanel buttonPanel = new JPanel();
    GridBagLayout grid = new GridBagLayout();

    GridBagConstraints cons = new GridBagConstraints();
    cons.fill = GridBagConstraints.NONE;  
    cons.insets = new Insets(1,1,1,1);  
    cons.gridy = 0;

    buttonPanel.setBackground(backgroundColor);
    buttonPanel.setLayout(grid);

    cons.gridx = 0;
    buttonPanel.add(new JButton("Pesquisar"), cons);
    cons.gridx = 1;
    buttonPanel.add(new JButton("Novo"), cons);
    cons.gridx = 2;
    buttonPanel.add(new JButton("Editar"), cons);
    cons.gridx = 3;
    buttonPanel.add(new JButton("Excluir"),cons);

    JPanel panel = new JPanel();
    panel.setBackground(backgroundColor);
    cons.anchor = GridBagConstraints.EAST;
    cons.fill = GridBagConstraints.NONE;
    cons.gridwidth = 1;

    panel.setLayout(grid);
    panel.add(buttonPanel,cons);
    return panel;
}

Doing this way the panel with the buttons are centered.

I'm trying to learn how to use GridBagLayout, so I may be making some primary mistake.

Author: Maniero, 2014-04-26

1 answers

Running your code I got this:

insert the description of the image here

I managed to create the panel with the buttons with the layout I want, but I can not put it in the right corner of my container.

A simple solution is to throw your GridBagLayout inside a BorderLayout by choosing the EAST position, also known as LINE_END.

insert the description of the image here

Basically your code looked like this:

contentPane = createActionButtonPanel();
setContentPane(contentPane);    

Where the Panel created by your method was the child of the JFrame. To make BorderLayout the child of Jframe and parent of GridBagLyout do this:

contentPane = new JPanel(new BorderLayout());
setContentPane(contentPane);
contentPane.add(createActionButtonPanel(), BorderLayout.EAST);

You will get this:

insert the description of the image here

I'm trying to learn how to use GridBagLayout, so if I'm making a primary mistake let me know.

Basically what you have to do is know the time to use the best layout for each occasion, and on many occasions you will need to use a layout composition.

I advise you to start studying here: A Visual Guide to Layout Managers

 2
Author: Math, 2014-04-26 19:14:47