Search code examples
javaswingjscrollpanejlabelmultiline

Java. Swing. Multiline labels in a JScrollPane


I have a JFrame with JScrollPane in it. I have JPanel inside a scrollPane. And add multiline labels in it. Everything is ok with multiline labels. I enclose my text in <HTML>..</HTML> tags. And labels display its wrapped text.

"..." means long multiline text.

The problem is that useless area is displayed in the bottom.

JFrame frame = new JFrame();        
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 300));
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
label1.setText("<html>" + "..." + "</html>");
panel.add(label1);
label2.setText("<html>" + "..." + "</html>");
panel.add(label2);
JScrollPane scroll = new JScrollPane(panel);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
frame.setContentPane(scroll);
frame.pack();
frame.setVisible(true);

EDIT.

So I have to set preferred size for inner JPanel. After that scrollPane draws its content(shows scrollbars) as its content has this fixed "inner panel preffered size". If I won't set preferred size for the panel, JLabels wouldn't wrap the text.

After being layed out by the layout manager inner panel's size grows and became larger than previously set preferred size. Panel grows itself, its ok, I see wrapped text of labels in it. But scrollpane behaves incorrectly. It paints scroll as inner panel is still of prefferred size size. So I need correct resizing behaviour for JScrollPane.


Solution

    • use JTextPane or JEditorPane instead of JPanel contains bunch of JLabels

    • JTextPane or JEditorPane supporting stylled text or Html <= 3.2 for Java6

    • theoretically you can use JList, instead of Jlabels, but in this case you have to call for setPreferredScrollableViewportSize(new Dimension) same as for JPanel in the JScrollPane

    EDIT