Java. Swing. Multi-line labels in JScrollPane
I have one JFrame
with JScrollPane. I have a JPanel inside a scrollPane. And add multi-line labels to it. Everything is fine with multi-line labels. I am attaching the text in tags <HTML>..</HTML>
. And the labels display wrapped text.
"..." means long multi-line text.
The problem is that a useless area is displayed at 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 my preferred size for the inner JPanel. The scrollPane then draws its content (showing scrollbars), since its content has this fixed "internal size of the preset panel". If I don't set a preferred size for the panel, the JLabels won't wrap the text.
After deploying using the layout manager, the inner pane grows and becomes larger than the previously set preferred size. The panel is growing, everything is fine, I can see the wrapped text of the labels in it. But the scrollpane is behaving incorrectly. It draws the scroll as the inner pane is still sized>. So I need the correct resizing for the JScrollPane.
source to share
-
use
JTextPane or JEditorPane
insteadJPanel
contains a bundleJLabels
-
JTextPane or JEditorPane
support for styled text orHtml <= 3.2
for Java6 -
in theory you could use JList instead of Jlabels, but in this case you should call for
setPreferredScrollableViewportSize(new Dimension)
the same as forJPanel
inJScrollPane
EDIT
-
then use Highlighter
source to share