tags:

views:

15

answers:

1

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 @swingcontrol ins place of @textArea in the 'actionPerformed' method.

A: 

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)

instantsetsuna
Thats whats happening alright. Guess i'll have to pass 'self' from the MainApp c'tor instead of passing a control. This way all controls will be accessible in the listener class.
Abhi