开发者

Top alignment for FlowLayout

I'm using a FlowLayout JPanel. The panel looks ugly when child component heights are different. I'm looking for a solution to make them top-align (simila开发者_JAVA百科r to valign="top" with table cells in HTML).


I realize this question was asked over a year ago, but like me, I thought many would stumble across this forum post and be left attempting to make a workaround like that one suggested in the bug report (failed to work for me just fyi).

Either way there is a better answer since JDK 1.6. Flowlayout has the following method:

public void setAlignOnBaseline(boolean alignOnBaseline)

If you use this method on your flowlayout and set it to true, then when flowlayout lays out the components it will check each component's baseline and align the component along this baseline.

But that's not all you need to do.

The component in question must override the following two methods in this way:

@Override
public Component.BaselineResizeBehavior getBaselineResizeBehavior() {
    return Component.BaselineResizeBehavior.CONSTANT_ASCENT;
}

@Override
public int getBaseline(int width, int height) {
    return 0;
}

They are methods in JComponent and layouts and layoutmanagers use these methods to determine how to layout the component.

If you take the steps mentioned above all the components will align themselves along the top of each row. Of course if you just want to use a component like JButton you will obviously have to extend it in order to achieve your desired goal... but it's not as much work as overriding layoutcontainer with a workaround that you have to debug. At least I think so.

Good luck, -Asaf


Someone else has wished for this, in the form of a bug-report (which also lists a workaround).

Have a look at

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4295966


You should be able to use a BoxLayout. It supports vertical alignment. The only problem is you need to manually insert horizontal strut components.

Or you could try using the Relative Layout. In your case you would use:

RelativeLayout rl = new RelativeLayout(RelativeLayout.X_AXIS, 5);
rl.setBorderGap(5);
rl.setAlignment(RelativeLayout.LEADING);
JPanel panel = new JPanel( rl );
panel.add(...);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜