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 (similar to valign="top"
with table cells in HTML).
Flow layouts are typically used to arrange buttons in a panel. It arranges buttons horizontally until no more buttons fit on the same line. The line alignment is determined by the align property.
When the FlowLayout object controls a container with a left-to right component orientation (the default), the LEADING value specifies the components to be left-aligned and the TRAILING value specifies the components to be right-aligned.
A flow layout arranges components in a left-to-right flow, much like lines of text in a paragraph. Flow layouts are typically used to arrange buttons in a panel. It will arrange buttons left to right until no more buttons fit on the same line.
FlowLayout is a simple layout manager that tries to arrange components at their preferred sizes, from left to right and top to bottom in the container. A FlowLayout can have a specified row justification of LEFT , CENTER , or RIGHT and a fixed horizontal and vertical padding.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With