2010-10-07 147 views
1

我无法访问内部类中外部类的实例变量。它是我使用JRuby中创建一个简单的Swing应用程序:在内部类中访问外部类的私有成员:JRuby

class MainApp 
def initialize 
    ... 
    @textArea = Swing::JTextArea.new 
    @button = Swing::JButton.new 
    @button.addActionListener(ButtonListener.new) 

    ... 
end 

class ButtonListener 
    def actionPerformed(e) 
     puts @textArea.getText #cant do this 
    end 
end 
end 

唯一的解决办法我能想到的是这样的:

... 
@button.addActionListener(ButtonListener.new(@textArea)) 
... 

class ButtonListener 
    def initialize(control) 
    @swingcontrol = control 
    end 
end 

,然后使用@swingcontrol插件地方@textArea在“ actionPerformed'方法。

+0

这是可能的java。那么为什么不在这里? – badmaash 2010-10-07 11:26:29

+0

因为Ruby不是Java。范围规则是不同的。 – hallidave 2011-02-14 03:28:28

回答

0

我想这是不可能的直接从内部类访问外层类成员而不诉诸黑客。因为ButtonListener类中的@textArea与MainApp中的@textArea不同。

(我是新来的红宝石,所以我可能是错误的这一点。所以,随时纠正我)

+0

这就是最新发生的情况。猜测我必须通过MainApp c'tor传递'self',而不是传递控制权。这样所有的控件都可以在监听器类中访问。 – badmaash 2010-10-07 11:46:30

0

Ruby的方式做到这一点是使用块,而不是一个嵌套类。

class MainApp 
def initialize 
    ... 
    @textArea = Swing::JTextArea.new 
    @button = Swing::JButton.new 
    @button.addActionListener do |e| 
     puts @textArea.getText 
    end 

    ... 
end 
end 
相关问题