I need a label that will line wrap the containing text according to the available size. Since a JTextArea
can line wrap, I used that and styled it accordingly so it resembles a JLabel
.
The problem is that the JTextArea
only increases it's width, but never shrinks it again. So I have an initial window size with some wrapped text, then I resize the window to be wider and the text will adjust accordingly, but making the window smaller again won't make the JTextArea
smaller, instead a scrollbar appears.
This only happens when both:
- The
JTextArea
is on aJPanel
that itself is in aJScrollPane
setLineWrap(true)
is used on theJTextArea
Removing the JScrollPane
will yield the expected behaviour, but I do need the whole thing to scroll since there are other elements on the JPanel
that may require it.
How can I tell it to get smaller again when the window is made smaller?
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
/**
* SSCCE to demonstrate the JTextArea behaviour
*/
public class WrapLabelTest {
public static final void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
testGui();
}
});
}
private static final String TEST_TEXT = "Textfortestingandstufflongenough"
+ "foralinebreak";
private static void testGui() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1;
gbc.weighty = 1;
panel.add(new WrapLabel(TEST_TEXT), gbc);
//
// gbc.gridy = 1;
// panel.add(new WrapLabel(TEST_TEXT), gbc);
frame.add(new JScrollPane(panel));
frame.setSize(200, 100);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
class WrapLabel extends JTextArea {
private static final JLabel LABEL = new JLabel();
public WrapLabel() {
setWrapStyleWord(true);
setLineWrap(true);
setBackground(LABEL.getBackground());
setFont(LABEL.getFont());
setBorder(LABEL.getBorder());
setFocusable(false);
setForeground(LABEL.getForeground());
setOpaque(false);
}
public WrapLabel(String text) {
this();
setText(text);
}
@Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
// Debug output
System.out.println(d);
return d;
}
}