2016-02-05 47 views
1

我想要获得一个类生成的值,并让其他类使用它并实时更新它。这是我做过什么与生成数类:如何编辑另一个类的值?

public Integer red(int red){ 
    this.red = red; 
    return red; 
} 

然后我叫

private int red; 

在其他类我做:

int r = gui.red(); //Gui is the name of the original class 

但它告诉我诠释着适用于它。如果我将它设置为0,它始终保持为零,而其他班级无法改变它。我怎样才能使这项工作正确?

+0

为什么你不像'public int red()'返回一个原始的int? – user3437460

回答

3

如何编辑从另一个类的价值?

我假设你问如何改变和访问类的私有变量。您可以使用getter和setter方法:

例如:

class GUI{ 
    private int red; 

    public int getRed(){   //you can name it as red() as you wish 
     return red; 
    } 

    public void setRed(int red){ //you can name is as red(int red) 
     this.red = red; 
    } 
} 

从其他类访问:

public class TestRunner{ 
    public static void main(String[] args){ 
     GUI gui = new GUI(); 
     gui.setRed(val);   //edit gui's red value (val is an int) 
     int color = gui.getRed(); //retrieve red from gui object 
    } 
} 
+0

好吧,所以它的工作原理,另一个问题是我有一个滚动条,从0到100的值,我需要一个监听器来听取变化的值。但是因为我在监听器外面调用了private int红色,所以这个值始终保持为零,如果我在监听器中调用private int red,它就不起作用。 – ChrisEthanFox

+0

http://pastebin.com/0Z9beZaS – ChrisEthanFox

0

你没有在红色函数中传递任何值。做到这一点,然后使用setter函数来设置值,并使用getter来查找最新值。

0

制作一个setter方法,如Gui类中提到的Pritam。

public void setRed(Integer red) { 
     this.red = red; 
} 

然后你需要实例化Gui类的一个对象。

Gui objGui = new Gui(); 

然后在该对象上使用setter函数。

objGui.setRed(red); 
0

您可以设置红色变量作为private access member。这个变量的范围只会在你的gui类中。这里有两个选项可以改变:

添加setter和getter方法

这可能是访问类的私有变量最常见的方式。通过创建setter和getter方法,您可以将新值设置为红色变量,并“获取”新的或当前的红色值。举个例子:

public void setRed(int red){ 
    this.red = red; 
} 
public int getRed() { 
    return red; 
} 

更改访问会员

另一种选择是简单地将进入构件改变从private int redpublic static int red。不过,我并没有真正推荐这么做,因为所有gui类实例中的红色值都保持不变。除非你有充分理由使用相同的变量,否则创建setter和getters就是解决方案。

+0

好吧,所以它的工作原理,另一个问题是我有一个滚动条,从0到100的值,我需要一个监听器来听取变化的值。但是因为我在监听器外面调用了private int红色,所以这个值始终保持为零,如果我在监听器中调用private int red,它就不起作用。 – ChrisEthanFox

+0

@ChrisEthanFox我们很难在没有看到代码的情况下提供帮助。请在SO上打开一个新问题,以便可以帮助其他类似情况的人也:) – Brian

相关问题