2010-10-07 135 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 
相關問題