---
title: "JRuby处理按钮点击事件"
author: "googya"
date: "2009-08-23T08:15:38Z"
tags: []
categories: ["编程语言"]
slug: "jruby"
draft: false
lastmod: "2009-08-23T08:15:38Z"
id: 455673
url: "https://googya.iteye.com/blog/455673"
---

```jruby
# 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.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(Color_T.new("yellow"))
    bluebutton.addActionListener(Color_T.new("blue"))
    redbutton.addActionListener(Color_T.new("red"))

  end
  class Color_T
      include ActionListener
      def initialize(c)
        @c=c
      end
      def action_performed(event)
           JOptionPane.show_message_dialog(nil,"#{@c}")
      end
  end
end
  ButtonFrame.new
```


    很简单的一个小应用。通过这个小例子可以看出JRuby调用Java中的东西很方便。不过我的代码写得有点臃肿，这里主要是想明白调用的过程。
    我对Java一直有点恐惧，Java要了解的东西太多了，特别是由于刚开始接触的时候，受到一定的打击，现在仍然有点惧，感觉有很多东西很深奥。但是实际上，并非如此，其实原理还是很简单的，比如这里的监听这个东西，以前很害怕这个，弄不懂。
    当接触到了Ruby之后呢，对语言稍微有点理解了，也消除了恐惧的心理，敢去正视它了
然后又出现了JRuby，使得Java和Ruby更好的结合，这个结合的过程同时也是个创新的过程。
    现在我感觉，通过2种语言的对比学习，可以更好的理解2种语言。