Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing: FlowLayout JPanels are sitting next to each other?

I have three JPanels painted onto a JFrame. These are currently all set to use the default FlowLayout. I would like for these to be one above the other in a single column.

However, I am finding that these are floating next to each other on the same line, so long as the components within them.

Is the natural width of a FlowLayout JPanel the sum of its contents? If so, is there any way to force the width of the region to be the width of the JFrame?

Interestingly, I am finding that, if the "top" and "bottom" panels have content which spans the entire width of the JFrame, and the "middle" panel is left empty, that the "middle" panel creates a space between the two, much like the old "

of html.

Thanks,

Ben

like image 578
Ben Avatar asked Nov 22 '10 10:11

Ben


1 Answers

As Jim stated, BoxLayout is the correct choice if you need to linearly align components.

Here is an example:

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author nicholasdunn
 */
public class BoxLayoutExample extends JPanel {

    public BoxLayoutExample() {
        JPanel topPanel = new JPanel();
        JPanel middlePanel = new JPanel();
        JPanel bottomPanel = new JPanel();

        topPanel.setBorder(BorderFactory.createEtchedBorder());
        middlePanel.setBorder(BorderFactory.createEtchedBorder());
        bottomPanel.setBorder(BorderFactory.createEtchedBorder());

        topPanel.add(new JLabel("Top"));
        middlePanel.add(new JLabel("Middle"));
        bottomPanel.add(new JLabel("Bottom"));

        BoxLayout boxLayout = new BoxLayout(this, BoxLayout.PAGE_AXIS);
        setLayout(boxLayout);
        add(topPanel);
        add(middlePanel);
        add(bottomPanel);

    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new BoxLayoutExample();
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

alt text

You would do well to really read through the introduction to layout managers to understand the base set of LayoutManagers. When it comes time to do complex layouts, please use MigLayout instead of trying to learn the GridBagLayout - you will thank me.

like image 62
I82Much Avatar answered Oct 06 '22 16:10

I82Much