java - getWidth not working correctly as class variable -
i new java (and programming in general) , trying make program draws vertical line down centre of screen. this, made variable x
gives me x coordinate of centre of screen. wanted able use variable within other private methods. when run code however, no line appears, if x
set 0.
import acm.graphics.*; import acm.program.*; import java.awt.*; public class target extends graphicsprogram { int x = getwidth()/2; public void run() { gline line = new gline (x,0,x,300); add (line); } }
if put variable x
inside run()
method below, line drawn correctly, not able use later in other private methods understanding variable no longer class variable instance variable , therefor accessible run()
, no other methods?
public class target extends graphicsprogram { public void run() { int x = getwidth()/2; gline line = new gline (x,0,x,300); add (line); } }
could enlighten me why first code not work whereas second 1 does? thank in advance!
in first version getwidth()
called during instance initialisation , bounds of window has not been set yet. still works method returns 0 , don't see line on screen.
Comments
Post a Comment