はじめてのswing on jruby その弐
import javax.swing.*; import java.awt.event.*; public class SimpleGui1B implements ActionListener { JButton button; public static void main (String [] args) { SimpleGui1B gui = new SimpleGui1B(); gui.go(); } public void go() { JFrame frame = new JFrame(); button = new JButton("click me"); button.addActionListener(this); frame.getContentPane().add(button); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); frame.setVisible(true); } public void actionPerformed(ActionEvent event){ button.setText("I've been clicked!"); } }
clickされたときにボタンの文字が入れ替わるようになっているものです。
これをjrubyで書くと
#!/usr/bin/env jruby require 'java' include_class 'javax.swing.JFrame' include_class 'javax.swing.JButton' include_class 'java.awt.event.ActionListener' class SimpleGui1B include java.awt.event.ActionListener def initialize frame=JFrame.new @button=JButton.new("click me") @button.add_action_listener(self) frame.default_close_operation=(JFrame::EXIT_ON_CLOSE) frame.content_pane.add(@button) frame.setSize(300,300) frame.visible=true end def actionPerformed(event) @button.text="I've been clicked!" end end SimpleGui1B.new
イベントが発生した時はイベントの処理のインスタンスを与えなければならないのですが、
これはselfでもいけました。
上のjavaのサンプルもthisって書いてあるので、真似をしてselfと書いたら
これでOKでした。後はメソッドを定義して、buttonをインスタンス変数@buttonに変更し、
実行したらいけました。
implementsしている部分はRubyのmix-inでOKですね。