Question

I am very new to java (and programming in general) and I trying to make a program that simply draws a vertical line down the centre of the screen. To do this, I made a variable x which gives me the x coordinate of the centre of the screen. I wanted to be able to use this variable within other private methods. When I run the code however, no line appears, as if x were set to 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 I put my variable x inside the run() method as below, the line is drawn correctly, but then I would not be able to use it later in other private methods as it is my understanding that then the variable would no longer be class variable but an instance variable and therefor only accessible by run() and 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 someone enlighten me as to why the first code does not work whereas the second one does? Thank you very much in advance!

Was it helpful?

Solution

In the first version getWidth() is called during instance initialisation and bounds of your window probably has not been set yet. So it still works but the method returns 0 and you probably don't see the line on the screen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top