Accessing private members of an outer class in an inner class: JRuby
I am not able to access an instance variable of the outer class in the inner class. Its a simple swing app that i am creating using 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
The only workaround i can think of is this:
...
@button.addActionListener(ButtonListener.new(@textArea))
...
class ButtonListener
def initialize(control)
@swingcontrol = control
end
end
and then use the @swi开发者_如何学Gongcontrol ins place of @textArea in the 'actionPerformed' method.
I guess it's not possible to directly access the outer class members from the inner class without resorting to hacks. Because @textArea in the ButtonListener class is different from @textArea in the MainApp.
(I'm new to ruby, so I could be wrong about this. So, feel free to correct me)
The Ruby way to do this is to use a block rather than a nested class.
class MainApp
def initialize
...
@textArea = Swing::JTextArea.new
@button = Swing::JButton.new
@button.addActionListener do |e|
puts @textArea.getText
end
...
end
end
精彩评论