TITLE:JRuby

Posted by at 2012-07-19

JRuby で Swing などのサンプル

概要

環境変数 JAVA_HOME, JRUBY_HOME を設定し、パスを通しておく。

> set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_04
> set JRUBY_HOME=C:\jruby-1.7.0
> set Path=%JAVA_HOME%\bin;%JRUBY_HOME%\bin;%Path%
> jruby -version
jruby 1.7.0.preview1 (ruby-1.9.3-p203) (2012-05-19 00c8c98) (Java HotSpot(TM) 64-Bit Server VM 1.7.0_05) [Windows 7-amd64-java]

Swing + JRuby サンプル

EDT で起動(JFrameを表示)

  • Event Dispatch Thread で起動するために、self が java.lang.Runnable の runメソッドを実装し、java.awt.EventQueue.invokeLater で実行している
  • require "java" より include Java が良い?
  • import より java_import javax.swing.JLabel が良い?
  • 適当なファイル名で保存して、 jruby Hoge.rb などで実行
include Java

java_import javax.swing.JLabel
java_import javax.swing.UIManager
java_import javax.swing.WindowConstants
def create_and_show_GUI
  begin
    UIManager.look_and_feel = UIManager.system_look_and_feel_class_name
  rescue Exception => e
    proxied_e = JavaUtilities.wrap e.cause
    proxied_e.print_stack_trace
  end
  frame = javax.swing.JFrame.new "Title"
  frame.default_close_operation = WindowConstants::EXIT_ON_CLOSE
  frame.content_pane.add JLabel.new "Test"
  frame.set_size(320, 240)
  frame.location_relative_to = nil
  frame.visible = true
end
def run
  create_and_show_GUI
end
java.awt.EventQueue.invokeLater self

クラスの継承(JPanelを継承)

  • class MainPanel < JPanel
include Java
java_import java.awt.Dimension
java_import javax.swing.JPanel
java_import javax.swing.JTextField

class MainPanel < JPanel
  def initialize
    super
    field = JTextField.new 32
    self.add field
    self.preferred_size = Dimension.new(320, 240)
  end
end

java_import javax.swing.UIManager
java_import javax.swing.WindowConstants
def create_and_show_GUI
  begin
    UIManager.look_and_feel = UIManager.system_look_and_feel_class_name
  rescue Exception => e
    proxied_e = JavaUtilities.wrap e.cause
    proxied_e.print_stack_trace
  end
  frame = javax.swing.JFrame.new "Title"
  frame.default_close_operation = WindowConstants::EXIT_ON_CLOSE
  frame.content_pane.add MainPanel.new
  frame.pack
  frame.location_relative_to = nil
  frame.visible = true
end
def run
  create_and_show_GUI
end
java.awt.EventQueue.invokeLater self

無名インナークラス(JButtonにActionListenerを追加)

include Java

java_import java.awt.Dimension
java_import javax.swing.JPanel
java_import javax.swing.JButton
java_import javax.swing.JTextField

class MainPanel < JPanel
  def initialize
    super
    field = JTextField.new 32
    button = JButton.new "add a"
    button.add_action_listener { |e|
      puts e
      field.text = field.text + "a"
    }
    self.add field
    self.add button
    self.preferred_size = Dimension.new(320, 240)
  end
end

java_import javax.swing.UIManager
java_import javax.swing.WindowConstants
def create_and_show_GUI
  begin
    UIManager.look_and_feel = UIManager.system_look_and_feel_class_name
  rescue Exception => e
    proxied_e = JavaUtilities.wrap e.cause
    proxied_e.print_stack_trace
  end
  frame = javax.swing.JFrame.new "JRuby Swing JButton ActionListener"
  frame.default_close_operation = WindowConstants::EXIT_ON_CLOSE
  frame.content_pane.add MainPanel.new
  frame.pack
  frame.location_relative_to = nil
  frame.visible = true
end
def run
  create_and_show_GUI
end
java.awt.EventQueue.invokeLater self

インタフェースの実装(MouseListenerを追加)

  • java_implements はもう使用できない?
    • 代わりに class MainPanel < JPanel; include MouseListener
    • カンマ区切りで複数指定しても可 class MainPanel < JPanel; include MouseListener, ActionListener
  • instanceof
    • self.java_kind_of?(MouseListener)
# -*- encoding: utf-8 -*-
include Java

java_import java.awt.event.MouseListener
java_import java.awt.Dimension
java_import javax.swing.JPanel
java_import javax.swing.JButton
java_import javax.swing.JTextField

class MainPanel < JPanel
                include MouseListener
  def initialize
    super
    field = JTextField.new 32
    button = JButton.new "add a"
    button.add_action_listener {
      field.text = field.text + "a"
    }

#     # https://blogs.oracle.com/nishigaya/entry/tips_for_accessing_java_objects2
#     button.add_mouse_listener do |ev|
#       p ev
#     end

#     #:1 warning: singleton on non-persistent Java type #<Class:0x103bdaa8> (http://wiki.jruby.org/Persistence)
#     class << listener = java.awt.event.MouseListener.new
#       def mouseEntered(e)
#         puts "mouseEntered"
#       end
#       def mouseExited(e)
#         puts "mouseExited"
#       end
#       def mousePressed(e)
#         puts "mousePressed"
#       end
#       def mouseClicked(e)
#         puts "mouseClicked"
#       end
#       def mouseReleased(e)
#         puts "mouseReleased"
#       end
#     end
#     button.add_mouse_listener listener

    # puts self.java_kind_of?(MouseListener)
    button.add_mouse_listener self

    self.add field
    self.add button
    self.preferred_size = Dimension.new(320, 240)
  end

  # MouseListener
  def mouseEntered(e)
    puts "mouseEntered"
  end
  def mouseExited(e)
    puts "mouseExited"
  end
  def mousePressed(e)
    puts "mousePressed"
  end
  def mouseClicked(e)
    puts "mouseClicked"
  end
  def mouseReleased(e)
    puts "mouseReleased"
  end
end

java_import javax.swing.UIManager
java_import javax.swing.WindowConstants
def create_and_show_GUI
  begin
    UIManager.look_and_feel = UIManager.system_look_and_feel_class_name
  rescue Exception => e
    proxied_e = JavaUtilities.wrap e.cause
    proxied_e.print_stack_trace
  end
  frame = javax.swing.JFrame.new "JRuby Swing JButton ActionListener"
  frame.default_close_operation = WindowConstants::EXIT_ON_CLOSE
  frame.content_pane.add MainPanel.new
  frame.pack
  frame.location_relative_to = nil
  frame.visible = true
end
def run
  create_and_show_GUI
end
java.awt.EventQueue.invokeLater self

配列(JTableに行追加)

  • ["No.", "Name", "Path"].to_java でrubyの配列をjavaの配列に変換
# -*- encoding: utf-8 -*-
include Java
java_import javax.swing.UIManager
java_import javax.swing.WindowConstants
java_import javax.swing.table.DefaultTableModel
def make_ui
  m = DefaultTableModel.new(nil, ["No.", "Name", "Path"].to_java)
  m.add_row java.util.Vector.new(["テスト", "あああ", "いいいい"])
  m.add_row ["aaa", "bbb", "ccc"].to_java
  t = javax.swing.JTable.new m
  p = javax.swing.JPanel.new java.awt.BorderLayout.new
  p.add javax.swing.JScrollPane.new(t)
  return p
end
def run #Override
  begin
    UIManager.look_and_feel = UIManager.system_look_and_feel_class_name
  rescue Exception => e
    proxied_e = JavaUtilities.wrap e.cause
    proxied_e.print_stack_trace
  end
  f = javax.swing.JFrame.new "jruby swing"
  f.default_close_operation = WindowConstants::EXIT_ON_CLOSE
  f.content_pane.add make_ui
  f.set_size(320, 240)
  f.location_relative_to = nil
  f.visible = true
end
java.awt.EventQueue.invoke_later self

JRubyでリソース(URL)のエントリを取得してSwingで使用する

ソースコードの文字コード(エンコーディング)

# -*- encoding: utf-8 -*-
include Java
java_import javax.swing.UIManager
java_import javax.swing.WindowConstants
java_import javax.swing.table.DefaultTableModel
def make_ui
  p = javax.swing.JPanel.new java.awt.BorderLayout.new
  p.add javax.swing.JLabel.new("日本語")
  return p
end
def run #Override
  begin
    UIManager.look_and_feel = UIManager.system_look_and_feel_class_name
  rescue Exception => e
    proxied_e = JavaUtilities.wrap e.cause
    proxied_e.print_stack_trace
  end
  f = javax.swing.JFrame.new "タイトル"
  f.default_close_operation = WindowConstants::EXIT_ON_CLOSE
  f.content_pane.add make_ui
  f.set_size(320, 240)
  f.location_relative_to = nil
  f.visible = true
end
java.awt.EventQueue.invoke_later self

その他、JRuby + One-Liner などのサンプル

JRuby One-Liner で、UIManagerのDefaults.keySetを一覧表示する

> jruby -rjava -e "javax.swing.UIManager.lookAndFeelDefaults.keySet.each{|o| puts o}"

One-Liner での文字コード

> chcp
現在のコード ページ: 932
> jruby -J-Dfile.encoding=UTF-8 -rjava -e 'p java.net.URLEncoder.encode("日本語","UTF-8")'
> jruby -J-Dfile.encoding=UTF-8 -rjava -e "puts java.net.URLEncoder.encode('日本語','UTF-8')"
> jruby -J-Dfile.encoding=UTF-8 -rjava -e 'puts java.net.URLEncoder.encode(""日本語"",""UTF-8"")'
> jruby --1.9 -U -rjava -e 'puts java.net.URLEncoder.encode("日本語","UTF-8")'
> jruby -J-Dfile.encoding=UTF-8 -ruri -e 'puts URI.encode("日本語")'
%E6%97%A5%E6%9C%AC%E8%AA%9E
> jruby --1.9 -rjava -e 'puts java.net.URLEncoder.encode("日本語","MS932")'
> jruby --1.9 -ruri -e 'puts URI.encode_www_form_component("日本語")'
%93%FA%96%7B%8C%EA

JRuby 1.7.0.preview1 でArgumentErrorが発生する場合

lines = src.rstrip.split(/\r?\n/).map {|line| line.chomp }
C:\pukiwiki2markdown>jruby p2m.rb wiki
ArgumentError: invalid byte sequence in Windows-31J
   split at org/jruby/RubyString.java:4643
 to_html at p2m.rb:45
    main at p2m.rb:219
    each at org/jruby/RubyArray.java:1611
    main at p2m.rb:214
  (root) at p2m.rb:234
C:\pukiwiki2markdown>jruby -J-Dfile.encoding=UTF-8 p2m.rb wiki
wiki/2010-04-12-swing-leaftreecelleditor.markdown
wiki/2007-06-18-swing-leftclippedcombobox.markdown
...
C:\pukiwiki2markdown>jruby -E UTF-8 p2m.rb wiki
wiki/2011-07-18-swing-listmouseselection.markdown
...

JRuby で PukiWiki のファイル名をデコード

if ARGV[0] == nil then
  while line = STDIN.gets
    STDOUT.puts "#{line.gsub!(/[A-F\d]{2}/) {|x| [x.hex].pack('C*')} }"
  end
else
  Dir::glob("*.#{ARGV[0]}").each {|f|
    puts "#{f.gsub!(/[A-F\d]{2}/) {|x| [x.hex].pack('C*')} }"
  }
end
> ls *.txt | jruby decode.rb
> ls *.txt | jruby -pe "$_.gsub!(/[A-F\d]{2}/) {|x| [x.hex].pack('C*')}"

PukiWiki形式のテキストをMarkdown形式のファイルに変換する

PukiWiki形式のテキストをMarkdown形式のファイルに変換するに移動

リンク

コメント