Alex
Alex

Reputation: 730

noob homework question window dimensions in java

I am a high school student taking cs106a at Stanford via video.

For my current assignment I have to add GObjects and position them relative to the size of the window.

I am currently trying to get the width of the window using the command

int width = getWidth();

however width = 0

One thing that could be causing this: this is one of the first programs I have written using multiple classes.

Thanks for the help!

Upvotes: 1

Views: 149

Answers (2)

Nate
Nate

Reputation: 16898

One possible cause - you may be calling getWidth() before the window (I'm assuming JFrame) has been realized (aka had setVisible(true) or pack() called on it). getWidth() will return 0 before it is realized.

Upvotes: 3

Scott Smith
Scott Smith

Reputation: 3986

Alex,

In the absence of example code from you, I'm going to take a wild guess and say that you're checking width in the constructor of your class, or at some other time either before the underlying OS window has been created, or after it has been destroyed.

If you try to get window attributes during these times, you'll probably get zero or some other nonsense result.

Upvotes: 1

Related Questions