我只是Java新手。我有以下代码片段:
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);
}
}
}
我有这个类,它是一个独立于 p
所属类的类。
public class Frame extends JFrame{
......
public static Points[] p = new Points[50];
....
}
如何调用 Frame
类中的点以便我可以在 Canvas 类中使用它?
最佳答案
如果您以这种方式声明:
public static Points[] p = new Points[50];
你可以这样做:Frame.p
因为p
是静态的
相反,如果您声明private Points[] p = new Points[50];
您在 Frame 类中使用 getter 方法:
public Point[] getPoints() {
return this.p;
}
关于java - 从另一个类访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21723766/