ITeye博客

impl与内部类

googya · 2009-08-23 11:20 · JRuby&Ruby · Markdown

# To change this template, choose Tools | Templates
# and open the template in the editor.

#puts "Hello World"
include Java
include_class javax.swing.JFrame
include_class javax.swing.JPanel
include_class javax.swing.JButton
include_class java.awt.event.ActionListener
include_class javax.swing.JOptionPane
include_class java.awt.Color


#include_class java.awt.Container
class ButtonFrame < JFrame
  def initialize
    super "Hello world Swing"
    setTitle__method "Button"
    set_size(300,200)
    panel=ButtonPanel.new
    getContentPane().add(panel)
    set_default_close_operation JFrame::EXIT_ON_CLOSE
    set_visible true
  end
end



class ButtonPanel <JPanel
  def initialize
    super
    yellowbutton=JButton.new("Yellow")
    redbutton=JButton.new("Red")
    bluebutton=JButton.new("Blue")
    add(yellowbutton)
    add(redbutton)
    add(bluebutton)   
    yellowbutton.addActionListener ActionListener.impl{ setBackground(Color::YELLOW) }
    bluebutton.addActionListener ActionListener.impl{ 
setBackground(Color::BLUE) }
    redbutton.addActionListener ActionListener.impl{ setBackground(Color::RED) }
      end
#  class Color_T
#      include ActionListener
#      def initialize(c)
#        @c=c
#      end
#      def action_performed(event)
#           setBackground(@c)
#      
#      end
#  end

  
  
end
  ButtonFrame.new

在用class Color_T的时候,出现问题了,Color_T是内部类,但是setbackground是外部类的方法,在Java中这个不存在访问的问题。但是JRuby中出现问题了,但是我还不清楚问题如何解决

评论(2)

  1. #2 楼 · night_stalker · 2009-08-23 14:36

    用 jruby 跑了下,swing 真慢 ……

    something cool:

    
    require 'cici'
    
    app = Cici.app 'color me~~'
    
    app.paint [300, 200] do |v|
      v.marginx = 20 # 左边距
      v.br           # 换一行得到点空间
      v.button('red')   { v.bkcolor = RGB[0xff0000] }
      v.button('blue')  { v.bkcolor = RGB[0x0000ff] }
      v.button('yello') { v.bkcolor = RGB[0xffff00] }
    end
    
    app.message_loop
    
    
  2. #1 楼 · night_stalker · 2009-08-23 14:22

    ruby 的内部类不与实例绑定。自然不能调用外部类的实例方法。

    可以改成

    
        ...
        redbutton.addActionListener Color_T.new(Color::RED, self)
      end # initialize
    
      class Color_T
        include ActionListener
        def initialize(c, obj)
          @c = c
          @obj = obj
        end
        def action_performed(event)
          @obj.setBackground(@c)
        end
      end
      ...
    
    

    或者

    
        ...
        color_me_onpush Color::RED, redbutton
      end # initialize
    
      def color_me_onpush color, button
        button.addActionListener ActionListener.impl {
          setBackground(color)}
      end
      ...
    
    

评论功能维护中,当前仅展示历史评论。