我在使用Java的布局管理器时遇到了一个烦人的问题。我有以下情况:在一个面板A中,有两个其他的面板B和C,B面板采用绝对布局,C面板采用FlowLayout布局。B面板高度定制且通过setPreferredSize设置了固定大小。C面板应该具有与B面板相同的固定宽度,但是除此之外,其高度应该根据流中添加的组件数量而变化。最终的A面板应该具有固定的宽度和A.height + B.height作为高度 - 至少这就是我想要的。
然而,我得到的结果是面板A的宽度根本不固定(即使我设置了其首选大小),并且面板C中的内容没有自动换行,而是显示在一行中。当然,这也导致B面板的宽度比它应该的大。
我该怎么办才能解决这个问题?是否有更好的布局,还是我必须使用绝对布局来模拟所有内容?
然而,我得到的结果是面板A的宽度根本不固定(即使我设置了其首选大小),并且面板C中的内容没有自动换行,而是显示在一行中。当然,这也导致B面板的宽度比它应该的大。
我该怎么办才能解决这个问题?是否有更好的布局,还是我必须使用绝对布局来模拟所有内容?
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" ) );
}
}
WrapLayout
也是编写自己的管理器的一个很好的例子。 - trashgod