If I put a JLabel
inside of a JPanel
with no rigid boundaries, it does not truncate the text when the JPanel
is sized to be smaller than the text. Why does this happen? Shouldn't the JPanel
realize that there isn't enough room & truncate the text accordingly, regardless of its layout?
As an example, I created a JFrame
with a GridLayout
with two rows & one column. In that, I placed a JPanel
with a FlowLayout
on top, & a JPanel
with a BoxLayout
on the bottom. Each JPanel
contains a JLabel
.
In short: Why doesn't the JLabel
on the top truncate its text?
Images to demonstrate what I mean:
As well, this is the SSCCE to demonstrate the effect:
import javax.swing.*;
import java.awt.*;
public class TruncationTest1
{
public static void main(String[] args)
{
JFrame f = new JFrame("Truncation Test");
JPanel panel = new JPanel(); //Default layout, aka FlowLayout
JLabel label = new JLabel("Try resizing the frame: This will not be truncated for some reason.");
JLabel label2 = new JLabel("However, this JLabel, on the other hand, will become truncated.");
f.setLayout(new GridLayout(2,1));
f.setBackground(Color.BLACK);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel);
panel.setBackground(Color.WHITE);
panel.add(label);
f.add(label2);
label2.setHorizontalAlignment(JLabel.CENTER);
label2.setForeground(Color.WHITE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
FlowLayout
does not resize components inside it. It shows the components with preferred size.
You need to use different layout in place of FlowLayout
for proper resizing. For instance you could use BorderLayout
with the label at LINE_START
or WEST
.