using a large JLabel in a JScrollPane

I was updating the SendSMS program I wrote, and instead of a JTable I wanted the list of messages sent to display in a better looking and more intuitive way. I decided to just use a JLabel and use html for displaying the sent messages:

JLabel using html in JScrollPane

I had the JLabel in a JPanel with GridLayout(1,1), and the Panel inside the JScrollPane. The JScrollPane always have vertical but never horizontal scrollbars.
The following problem arose: When the message got to long, it would not wrap, and end of message would disappear to the right.
The solution is simple: set the Width of the JPanel with the label to be roughly the size of the application window..

That did the trick, now however the scrollbar never updates when the Label gets very tall.

Apparently you cant just set just width for the Panel, you also have to set height.. again the solution is simple, set the height of the panel to be the height of the JLabel.

However since the JLabel is inside the JScrollPane (at least, I think that is the cause) the getSize and getPrefferedSize will return only the visible height of the JLabel. It took some playing around with but finally got it working by using the getMaximumSize.. NOTE: dont use the width from getMaximumSize() cause it is ridiculously large :)

the code:

historyPanel.setPreferredSize(new Dimension(historyScrollPane.getViewport().getSize().width, historyLabel.getMaximumSize().height));

Now I just have to find out if that way of getting the components height works the same across different platforms :)

Tags: , , , , , , , , , , , , , ,

Leave a Reply