Component placement using GridBagLayout

3

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

The width of the panel occupies the full 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 within 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 was able to create the panel with the buttons with the layout that I want, but I can not 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 centralized.

I'm learning to use GridBagLayout , so I may be making some primary error.

    
asked by anonymous 26.04.2014 / 20:31

1 answer

2

Running your code I get this:

  

ImanagedtocreatethepanelwiththebuttonstothelayoutIwant,butIcannotputitintherightcornerofmycontainer.

AsimplesolutionistothrowyourGridBagLayoutinsideaborderlayout,choosingEASTposition,alsoknownasLINE_END.

Basically your code looks like this:

contentPane = createActionButtonPanel();
setContentPane(contentPane);    

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

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

You'll get this:

  

I'mdiggingtolearnhowtouseGridBagLayout,soifI'mmakingsomethingprimaryerrorletmeknow.

Basicallywhatyouhavetodoisknowthetimetousethebestlayoutforeveryoccasion,andonmanyoccasionsyouwillneedtousealayoutscomposition.

I'dadviseyoutostartstudyinghere: A Visual Guide to Layout Managers

    
26.04.2014 / 21:14