Java layout center with two panels

2019-03-03 10:18发布

问题:

In Java, when using the BorderLayout, is it possible to have two panels in the CENTER, but both be visible on the form.

Here is my code:

    guiFrame.add(guiFieldsPanel, BorderLayout.CENTER);
    guiFrame.add(guiButtonsPanel, BorderLayout.CENTER);        
    guiFrame.setVisible(true);

In the above code, both panels are set to the center, yet I can only see the guiButtonsPanel as it is 'on top' of the guiFieldsPanel.

Can i group both panels together, and then set them to be displayed in the CENTER?

回答1:

See the Nested Layout Example for ideas about how to combine layouts to create the required layout. E.G.

Perhaps use a single row GridLayout for the center.

guiFrame.add(guiFieldsPanel, BorderLayout.CENTER);
guiFrame.add(guiButtonsPanel, BorderLayout.CENTER);        

But that suggests a 2 column GroupLayout as seen in this answer. E.G.



回答2:

You will need to create an intermediate panel that will contain both guiFieldsPanel and guiButtonsPanel, and then add that to the border layout.

final JPanel centre = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
centre.add(guiFieldsPanel);
centre.add(guiButtonsPanel);

guiFrame.add(centre, BorderLayout.CENTER);
guiFrame.setVisible(true);

You can adjust the layout of centre as appropriate for your needs with respect to the relative positioning of guiFieldsPanel and guiButtonsPanel.