I have an annoying problem with Javas layout managers. I have the following situation: on panel A, there are two other panels B with absolute layout and C with FlowLayout. B is very tuned and has a fixed size set via setPreferredSize . C should have the same fixed width as B, but otherwise have a variable height, depending on how many components are added to the stream. As a result, A should have a fixed width and A.height + B.height as height - at least that is what I want.
However, I get that the width of Panel A is not fixed at all (even if I set its preferred size), and the content in Panel C does not automatically wrap, but displays in a long line. Of course, this also makes B wider than it should be.
What can I do to fix this? Is there any better layout, or do I need to emulate this 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" ) ); } }
java layout-manager swing fixed-width
poke
source share