0

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!

4

1 回答 1

0

在第一个版本getWidth()中,在实例初始化期间调用并且您的窗口的边界可能尚未设置。所以它仍然有效,但该方法返回 0,您可能在屏幕上看不到这条线。

于 2014-04-24T22:45:57.067 回答