Posts Tagged ‘jlabel’

Bye bye memoryleak

Monday, November 3rd, 2008

I finally got rid of that stupid memory leak in the Star Trek game I’m working on. It turns out when I optimized the use of JLabels I forgot about the action listeners, so the reference to the local copy of the game map was never removed from memory.

With a map update every 35 seconds, the client would go out of memory (200 MB) in 15 minutes, in where around 270’000 action listeners where in memory.

Memory leak

Now however the game can run smoothly for days:
NO memory leak :)

Currently I’m working on a major overhaul of the GUI, and the game looks much better now. I’m gonna release the new screenshots when I get the client stable again and re-integrate the map window in a new way (soon) :)

using a large JLabel in a JScrollPane

Thursday, August 23rd, 2007

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 :)