[英]How to access an object from outside its method
I have a problem that looks simple but I can't figure it out. 我有一个看似简单的问题,但无法解决。
Here is a simplified version of my problem: 这是我的问题的简化版本:
public void createContents() {
Composite dataCalcComposite = new Composite(shell, SWT.NONE);
dataCalcComposite.setBounds(0, 10, 279, 146);
}
public void repositionObjects() {
dataCalcComposite.setLocation(50, 10)
}
This won't work because repositonObjects
can't see the dataCalcComposite
variable. 这将不起作用,因为
repositonObjects
无法看到dataCalcComposite
变量。
I know I could fix this by calling repostionObjects
inside the first method and passing the variable in as a parameter but this is a very simplified version of my problem and the number of objects that need to be repositioned will be changing, so I don't think that method will work. 我知道我可以通过在第一个方法中调用
repostionObjects
并将变量作为参数传递来解决此问题,但这是我的问题的非常简化的版本,需要重新定位的对象数量会发生变化,所以我不会认为该方法会奏效。
Also, I can't use static
on the variable, my IDE says that only final
will work with it. 另外,我不能在变量上使用
static
,我的IDE表示只有final
可以使用它。
So without being able to use static on the variable, how can I access it from another method? 因此,不能在变量上使用static,如何从另一种方法访问它呢?
You can move the declaration Composite dataCalcComposite;
您可以移动声明
Composite dataCalcComposite;
to be outside the method, so this variable will become an instance variable. 在方法之外,因此此变量将成为实例变量。
....
private Composite dataCalcComposite;
public void createContents() {
dataCalcComposite = new Composite(shell, SWT.NONE);
dataCalcComposite.setBounds(0, 10, 279, 146);
}
public void repositionObjects() {
if (dataCalcComposite != null) {
dataCalcComposite.setLocation(50, 10)
}
}
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.