Reputation:
I have a JPanel that contains two JLabel. The panel uses a BorderLayout.
One JLabel is put into BorderLayout.CENTER
position, the other in BorderLayout.PAGE_END
When I resize the panel so that it does not have enough vertical space to show both labels, the centered label is always overwritten (cut off) by the label in the PAGE_END
position.
As the information displayed in the centered label is more important than the other, I would like the centered label to overlap (or cut off) the label below it.
It seems that BorderLayout (and GridBagLayout as well) always paints the components from "top to bottom" and those that are painted "later" will overwrite the ones painted before.
Is there some way I can convince BorderLayout (or any other LayoutManager) to assume that a certain component should always be "at the top"?
I tried using
panel.setComponentZOrder(label1, 1);
panel.setComponentZOrder(label2, 0);
but that didn't make a difference.
Upvotes: 2
Views: 1722
Reputation: 168845
Call setMinimumSize(Dimension)
on the top-level container when there is enough text in the center label.
Upvotes: 2
Reputation: 205875
One approach would be to use a custom variation of GridLayout
that respects preferred sizes. PreferredSizeGridLayout
using the PreferredBoundable
implementation is an example.
Addendum: Here's the test code I tried. Without change, the lower label "slides" beneath the upper, but you'll have to handle the horizontalAlignment
property.
public class PreferredLayoutTest extends JPanel {
public PreferredLayoutTest() {
this.setLayout(new PreferredSizeGridLayout(0, 1));
this.add(createLabel("One"));
this.add(createLabel("Two"));
}
private JLabel createLabel(String s) {
JLabel label = new JLabel(s);
label.setOpaque(true);
label.setBackground(Color.lightGray);
label.setFont(label.getFont().deriveFont(36f));
return label;
}
private void display() {
JFrame f = new JFrame("PreferredLayoutTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new PreferredLayoutTest().display();
}
});
}
}
Upvotes: 2