简体   繁体   English

从另一个类访问变量

[英]Accessing variable from another class

I am just a newbie in Java. 我只是Java的新手。 I have this following code snippets: 我有以下代码片段:

class Canvas extends JPanel{
    int x=-10,y=-10,z=-10;
    public Canvas() {
    }
    public void setCoordinates(int x,int y, int z){
        this.x=x;
        this.y=y;
        this.z=z;
    }
    public void paintComponent(Graphics g) {
        for(int i=0; i<50 ;i++){
            if(p[i].z==1) g.setColor(Color.red);
            else if (p[i].z==2) g.setColor(Color.green);
            else g.setColor(Color.blue);
            g.fillArc(p[i].x-5,p[i].y-5,10,10,0,360);
        }
    }
}

I have this class, it's a separate class from the one where p belongs. 我有这个课,这是与p所属的课分开的课。

public class Frame extends JFrame{
      ......
      public static Points[] p = new Points[50];
      ....
}

How can I call the points I have in the class Frame so that I can use it in the class Canvas?? 我怎样才能称呼我在Frame类中拥有的点,以便可以在Canvas类中使用它?

If you declare in this way: 如果以这种方式声明:

public static Points[] p = new Points[50]; 公共静态Points[] p = new Points[50];

you can do: Frame.p beacuse p is static 您可以这样做: Frame.p因为p 是静态的

Instead if you declare private Points[] p = new Points[50]; 相反,如果您声明了private Points[] p = new Points[50]; you use a getter method in Frame class : 您可以在Frame类中使用getter方法

public Point[] getPoints() {
    return this.p;
}

Frame.p ,因为它是static并且名称是p

as p is public static you can access it by Frame.p , but this is not nice and elegant way 因为p是公共静态的,所以可以通过Frame.p来访问它,但这不是一种好方法

if you want to do this properly, you will create separate object which holds all your points, you can make it singleton if you want have only one instance. 如果要正确执行此操作,则将创建一个单独的对象来保存您的所有要点,如果您只想拥有一个实例,则可以使其成为单例。 If you create it when your application is created you can pass it to each frame which is using it, or just use static method to access it(will work if you have singleton) 如果在创建应用程序时创建它,则可以将其传递给使用它的每个框架,或者仅使用静态方法来访问它(如果您具有单例功能,则可以使用)

由于pFrame类的公共静态字段,因此可以使用诸如Frame.p类的类名来访问它

您可以直接访问Frame.p因为该字段是公共静态的

You can use public and static fields of one class in other class with its class-name. 您可以将其他类别的一个类别的public字段和static字段及其类别名称一起使用。

Since in your class Frame the field p is public static , so You can use field p as Frame.p in class Canves . 由于在Frame类中,字段ppublic static ,因此您可以在Frame.pCanves字段p用作Canves

More about static fields : Static fields 有关静态字段的更多信息: 静态字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM