I use WrapLayout which extends FlowLayout
Now, I have this GUI:
What I want is this:
I tried some things like: label.setVerticalAlignment(JLabel.TOP); but the layout does not seem to respect it. I guess this behavior is inherited from FlowLayout?
Full code:
public class WrapLayoutExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(WrapLayoutExample::runGui);
}
private static void runGui() {
JFrame frame = new JFrame("A");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new WrapLayout());
JLabel l = new JLabel("CCC");
l.setBorder(BorderFactory.createLineBorder(Color.red, 10));
l.setVerticalAlignment(JLabel.TOP);
panel.add(l);
l = new JLabel("BBBB");
l.setBorder(BorderFactory.createLineBorder(Color.red, 20));
panel.add(l);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(panel));
frame.pack();
frame.setVisible(true);
}
}


From @camickr's comment in my question:
In FlowLayout, in
moveComponentsmethod, there is this line:Changing the line to:
achieves what I want.
It probably breaks the
flowLayout.setAlignOnBaselinefunctionality. But I don't use it anyway.Layout code (WrapLayout and custom FlowLayout combined):
Example code:
Result: