I have a case where I am adding JPanels to a FlowLayout, and they are not aligning themselves to the bottom of the layout. I'm using this layout.setAlignOnBaseline(true)
and it properly aligns JLabels to the bottom of the panel. However, once those labels are wrapped in panels themselves it no longer works. Here is an example of what I mean, with two panels top and bottom.
import javax.swing.*;
import java.awt.*;
public class BadLayout {
private static final Font font1 = new Font("Arial", Font.BOLD, 14);
private static final Font font2 = new Font("Arial", Font.BOLD, 30);
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Bad layout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout layout = new FlowLayout(FlowLayout.LEADING, 0, 0);
layout.setAlignOnBaseline(true);
JPanel topPanel = new JPanel();
topPanel.setLayout(layout);
topPanel.setBackground(Color.BLACK);
for (int i = 0; i < 10; i++) {
JLabel label = new JLabel("Foo");
label.setForeground(Color.WHITE);
label.setBackground(Color.RED);
label.setOpaque(true);
label.setFont(i % 2 == 0 ? font1 : font2);
JPanel subPanel = new JPanel();
subPanel.setLayout(layout);
subPanel.setBackground(Color.RED);
subPanel.add(label);
subPanel.setAlignmentY(Component.BOTTOM_ALIGNMENT);
topPanel.add(subPanel);
}
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(layout);
bottomPanel.setBackground(Color.DARK_GRAY);
for (int i = 0; i < 10; i++) {
JLabel label = new JLabel("Foo");
label.setForeground(Color.WHITE);
label.setBackground(Color.RED);
label.setOpaque(true);
label.setFont(i % 2 == 0 ? font1 : font2);
bottomPanel.add(label);
}
JPanel parentPanel = new JPanel();
parentPanel.setLayout(new BorderLayout());
parentPanel.add(topPanel, BorderLayout.NORTH);
parentPanel.add(bottomPanel, BorderLayout.SOUTH);
frame.getContentPane().add(parentPanel);
frame.pack();
frame.setVisible(true);
});
}
}
If you run this code you'll notice the top panel has the smaller "Foo"s centered in the panel, while the one on the bottom has the desired 'bottom-aligned' behavior I'm hoping for. Any ideas how to get the sub JPanels to behave the same?