Javaのレイアウトマネージャーに厄介な問題があります。次の状況があります。パネルAには、絶対レイアウトの2つのパネルBとFlowLayoutのCがあります。Bは高度にカスタマイズされており、を介して固定サイズが設定されてsetPreferredSize
います。CはBと同じ固定幅である必要がありますが、それ以外の場合は、フローに追加されるコンポーネントの数に応じて高さが可変になります。結果として得られるAは、固定された幅と高さを持つ必要があります–少なくともそれが私が望むものです。A.height + B.height
ただし、パネル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" ) );
}
}