Scala メモ - Enter キーを押したイベントをひろう

ログインのダイアログとかでパスワードを入力した後に Enter キーを押すと処理が進むと思うんですが、あれを自分が作ったウィンドウで実現しようというものです。

上のアプリを起動するとこうなります。
f:id:kaizawa2:20110211220110p:image
ここで文字を入力して…
f:id:kaizawa2:20110211220109p:image
Enter キーを押すと、こうなります。
f:id:kaizawa2:20110211220108p:image

肝はこの部分かなと思います。

    listenTo(textfield.keys)

listenTo はイベントを監視するオブジェクトを指定しますが、TextField の親の scala.swing.TextComponent も Publisher をミックスインしているので listenTo(textfield) でもよさげな気がするのですが、それだと TextField 上でキー入力のイベントを拾うことができません。TextField のメンバーである keys を指定します。

あとは Enter キーの KeyPressed イベントを reactions として追加してハンドラを指定します。

    reactions += {
      case KeyPressed(_, Key.Enter, _, _) => label.text_=(textfield.text)
    }

今回のエントリ作成時に以下のフォーラムを参考にさせていただきました

本当はなぜ keys を指定する必要があるのかという点をもっと追うと理解が深まると思うのですが、とりあえず期待どおり動いちゃったのでいいかなと日和って調べませんでした。
ちなみに上で紹介しているフォーラムでは以下のような投稿がありました。

You need to listenTo(textField.keys). This is one of the unfortunate points of the publisher/reactor design. In order to make things more efficient, components do not publish all events themselves. See Component.mouse, Component.keys and ListView.selection for examples. Also look into the test package which is part of the scala.swing distribution, do a grep, and you may find what you need. For your specific case, there is the painting demo (not in 2.7.x I believe but in 2.8/trunk) which also reacts to key events. Ingo