[ruby-list:39985] Re: ruby/tk のイベントハンドラをまとめて設定するには?
From:
"H.Yamamoto" <ocean@...2.ccsnet.ne.jp>
Date:
2004-09-01 12:13:13 UTC
List:
ruby-list #39985
山本です。
少し大きいですが、コードを全部載せます。(スケジュール表プログラムを作ろうとしています)
require "tk"
require 'date'
class Calendar < TkFrame
def initialize
super
cal = self
@prev = TkButton.new(self) {
text "prev"
command { cal.date <<= 1 }
grid("row" => 0, "column" => 0, "sticky" => "news")
}
@label = TkLabel.new(self) {
grid("row" => 0, "column" => 1, "sticky" => "news")
}
@next = TkButton.new(self) {
text "next"
command { cal.date >>= 1 }
grid("row" => 0, "column" => 2, "sticky" => "news")
}
@canvas = TkCanvas.new(self) {
grid("row" => 1, "column" => 0, "columnspan" => 3, "sticky" => "news")
}
cell(0, 0){|r,t| t.text "Sun"; r.fill "#F7CACA"}
cell(1, 0){|r,t| t.text "Mon"; r.fill "#E7FFE7"}
cell(2, 0){|r,t| t.text "Tue"; r.fill "#E7FFE7"}
cell(3, 0){|r,t| t.text "Wed"; r.fill "#E7FFE7"}
cell(4, 0){|r,t| t.text "Thu"; r.fill "#E7FFE7"}
cell(5, 0){|r,t| t.text "Fri"; r.fill "#E7FFE7"}
cell(6, 0){|r,t| t.text "Sat"; r.fill "#CEFFFF"}
@cells = []
for iy in 0...6
for ix in 0...7
cell(ix, iy + 1){|r,t|
c = Struct.new(:rect, :text, :date).new(r, t, nil) # caution! scope of variable
r.bind "ButtonPress-1", proc { cal.date = c.date }
t.bind "ButtonPress-1", proc { cal.date = c.date }
@cells << c
}
end
end
self.date = Date.today
end
def cell(ix, iy)
dx = @canvas.width / 7
dy = @canvas.height / 7
x = dx * ix
y = dy * iy
r = TkcRectangle.new(@canvas, x, y, x + dx, y + dy, "outline" => "gray")
t = TkcText.new(@canvas, x + dx / 2, y + dy / 2)
yield r, t
end
private :cell
def date
@date
end
def date=(value)
unless defined?(@date) && @date.year == value.year && @date.month == value.month
@label.text = "#{value.year} - #{value.month}"
@cells.each {|c| c.date = nil }
temp = value; temp -= 1 while temp.year == value.year && temp.month == value.month; temp += 1
day = nil
week = 0
while temp.year == value.year && temp.month == value.month
week += 1 if day && day + 1 != temp.day
day = temp.day
@cells[temp.wday + week * 7].date = temp
temp += 1
week += 1 if temp.wday == 0
end
@cells.each{|c|
if c.date
c.text.text = c.date.day
c.rect.fill "white"
c.rect.state "normal"
c.text.state "normal"
else
c.rect.state "hidden"
c.text.state "hidden"
end
}
end
@date = value
puts @date
end
end
$cal = Calendar.new {
pack
}
Tk.mainloop
Java のコードはこんな感じです。final int n = i の final が外れると、
コンパイルエラーになります(バインドできません)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Main
{
public static void main(String args[])
{
JFrame frame = new JFrame("Test");
frame.getContentPane().setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < 3; ++i) {
final int n = i;
JButton button = new JButton(String.valueOf(i));
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println(n);
}
});
frame.getContentPane().add(button);
}
frame.pack();
frame.setVisible(true);
}
}