I have an annoying problem with Java’s layout managers. I have the following situation: In a panel A are two other panels B with an absolute layout and C with a FlowLayout. B is highly customized and has a fixed size set via setPreferredSize
. C should have the same fixed width as B but otherwise be of a variable height, depending on how many components are added in the flow. The resulting A should then have the fixed width and A.height + B.height
as the height – at least that is what I want.
However what I get is that the width of the panel A is not fixed at all (even if I set its preferred size), and the contents in panel C are not automatically wrapping but instead are displayed in a long line. Of course this also makes B having a larger width than it should be.
What can I do to fix that? Is there any better layout, or do I have to emulate that all using an absolute layout?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Test extends JPanel
{
public Test ()
{
this.setLayout( new BoxLayout( this, BoxLayout.Y_AXIS ) );
JPanel top = new JPanel( null );
top.setBackground( Color.GREEN );
top.setPreferredSize( new Dimension( 200, 20 ) );
JPanel flowPanel = new JPanel( new FlowLayout( FlowLayout.LEFT, 2, 2 ) );
this.add( top );
this.add( flowPanel );
flowPanel.add( new JButton( "x" ) );
flowPanel.add( new JButton( "x" ) );
flowPanel.add( new JButton( "x" ) );
flowPanel.add( new JButton( "x" ) );
flowPanel.add( new JButton( "x" ) );
flowPanel.add( new JButton( "x" ) );
flowPanel.add( new JButton( "x" ) );
flowPanel.add( new JButton( "x" ) );
flowPanel.add( new JButton( "x" ) );
flowPanel.add( new JButton( "x" ) );
flowPanel.add( new JButton( "x" ) );
flowPanel.add( new JButton( "x" ) );
}
}