JPanel getSize () method returns 0

Hi,

I am writing a 'pong' type game which consists of a JFrame main window (using BorderLayout) with a JPanel for drawing graphics. I used netbeans to set this up.

When i call getSize () from within my class which extends JPanel, it always returns 0. I have also tried getHeight (), getWidth () etc which all return 0.

The only way i can get correct values is to call getSize () from outside the class. For example:

gamePanel.getSize () works fine but

this.getSize () or getSize () from within the class returns 0.

This is usless to me as i need to use the height and width from within my GamePanel class so i can work out co-ordinates from the size of the screen.

How can i get this to work? Can anyone help?

Many Thanks

Dan

[791 byte] By [nobby_trussina] at [2007-10-3 9:56:56]
# 1
getSize() will always return 0 if you call it on a component before it's added to the awt tree. to say anything more would recquire seeing your code. As it has been suggested many times here, post a small self-contained program displaying the problem.
dberanskya at 2007-7-15 5:15:04 > top of Java-index,Desktop,Core GUI APIs...
# 2

It would be most helpful if you included some code with your example and I hate to say I'm an expert but I think I know the scenario, correct me if I'm wrong. I believe you're describing a scenario where you have either in the constructor or a method called from the constructor a call to getSize() and it's returning 0(zero).

If that is the case, the reason is because at the time of the constructor the component has not yet been layed out on the screen and thus has no size, unless you specifically set it to one. Once upon a time ago I was scared to use layout managers and specifically set the location and size of everything. When that happened, the size was known but once you introduce layout managers, sizes and in many cases locations are rarely known until the execution of the pack()

command.

My solution is to try getPreferredSize()

which I believe references the layout manager to get how big the object SHOULD be, given what was layed out already, or not use layout managers and specically set the location and size of everything in your frame. I hope that helps a little. To get more, please offer some code so we can see what is happening more clearly. Thanks!

Seth

dragonprincea at 2007-7-15 5:15:04 > top of Java-index,Desktop,Core GUI APIs...
# 3
The size of a component is 0 until the GUI is actually visible.
camickra at 2007-7-15 5:15:04 > top of Java-index,Desktop,Core GUI APIs...
# 4
thanks for your replies. i have sorted the problem now. I was calling getSize () from the constructor of my object; makes sense that its size would be 0 until it is displayed.thanks againDan
nobby_trussina at 2007-7-15 5:15:04 > top of Java-index,Desktop,Core GUI APIs...