FlowLayout是唯一支持将组件包装到新行中的标准JDK布局管理器。 (可能有支持此操作的MigLayout等第三方布局。)。
如果不喜欢默认功能,可以定制布局管理器。 这是一个简单的示例,允许FlowLayout执行默认布局并将每个组件重置到该行的顶部。
import java.awt.*;
import java.util.*;
import javax.swing.*;
publicclasstopflowlayoutextendsflowlayout
{
@Override
公共容器(容器容器) )。
{
super.layout container (container );
component c=container.get component (0;
int lineStart=getVgap (;
int line height=linestartc.getsize ().height;
for(intI=0; i container.getComponentCount (; I )
{
c=container.getcomponent(I;
Point p=c.getLocation (;
Dimension d=c.getSize (;
if(p.ylineheight )//still on current line
{
p.y=lineStart;
lineheight=math.max(lineheight,lineStart d.height );
}
else //start a new line
{
lineStart=lineHeight getVgap (;
p.y=lineStart;
lineHeight=lineStart d.height;
}
p.y=lineStart;
c .设置位置(p;
}
}
privatestaticvoidcreateandshowgui (
{
topflowlayoutlayout=new top flowlayout (;
layout.set alignment (flowlayout.left;
janelflowpanel=new jpanel (layout );
Random random=new Random (;
for(intI=0; i 10; I )
{
flowpanel.add(createbutton(I ',random.nextint ) 100 ),random.nextint (100 ) );
}
jrameframe=newjframe('sscce );
frame.setdefaultcloseoperation (jframe.exit _ on _ close );
frame.add(flowpanel );
frame.setlocationbyplatform () true;
frame.setsize (400,400 );
frame.setvisible(true;
}
privatestaticjbuttoncreatebutton (string text,int width,int height ) )。
{
Jbuttonbutton=newJbutton(Text );
dimensionsize=new dimension (width 50,height 50 );
Button.setpreferredsize(size;
返回按钮;
}
publicstaticvoidmain (string [ ] args ) )。
{
event queue.invoke la ter (new runnable ) )。
{
公共语音运行(
{
createAndShowGUI (;
}
);
}
}
您可能还需要考虑扩展基于同一个FlowLayout的Wrap Layout,但会添加其他功能。