Java Swing: FlowLayout JPanels sitting next to each other?

I have three JPanels written in JFrame. Currently, they are all configured to use the default FlowLayout stream. I would like them to be one above the other in one column.

However, I find that they float next to each other on the same line, while the components are inside them.

Is the natural width of a FlowLayout JPanel the sum of its contents? If so, is it possible to make the width of the region be the width of the JFrame?

Interestingly, I find that if the "top" and "bottom" panels have content that spans the entire width of the JFrame, and the "middle" panel remains empty, then the "middle" panel creates a space between them, just like the old "

html

Thanks,

Ben

+6
java swing flowlayout
source share
4 answers

As Jim said, BoxLayout is the right choice if you need to align components linearly.

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 should really read the introduction to layout managers to understand the basic set of LayoutManagers. When it comes time to make complex layouts, use MigLayout instead of trying to recognize the GridBagLayout - you'll thank me.

+4
source share

If you want to create a vertical layout, you can look at using BoxLayout for a container container. This can be configured to layout along the y axis.

+2
source share

You can use GridLayout to create a YxZ grid in a component. To build the layout more accurately, you can use the GridBagLayout , which provides full control over positioning and size for nested components.

+1
source share

I always ride with NetBeans . Since I can do Free Design without any problems with placing components on JPanel or JFrame :) You can think about it.

0
source share

All Articles