scala.swing.ListView

ListView は、javax.swing.JList に代えて、任意の項目をリスト形式で表示します。ここでは、ある項目を選択したときの動作を規定する技法を紹介します。

《関連記事》

┃for example

プログラムを実行します。

$ cd cherry/tips336
$ scalac -d bin {Tips,Window}.scala
$ scala -cp bin cherry.swing.Tips

  • リスト項目を選択すると、それに呼応してタイトルが変化します。
┃source code
    
cherry/tips336/Window.scala
import swing._ import swing.event._ // ---------------------------------------- object Window extends MainFrame { title = "ListView" contents = new View(this) peer.setLocationRelativeTo(null) } // ---------------------------------------- import scala.collection.mutable.ListBuffer import java.awt.Dimension class View(frame: Frame) extends FlowPanel { val items = new ListBuffer[String] ++ (BorderPanel.Position.values map { _.toString }) val listView = new ListView(items) { Command.listenTo(selection) } new ScrollPane(listView) { preferredSize = new Dimension(150,70) View.this.contents += this } ...
  • ListView には、提示するリスト項目 items を初期設定できます。
  • Command は、ListView のリスト項目を選択 selection すると、そのイベントに呼応 listenTo します。
┃イベント処理
    
cherry/tips336/Window.scala
class View... object Command extends Publisher { reactions += { case ListSelectionChanged(source, range, live) => this.update(source) } def update(source: ListView[_]) { frame.title = source.selection.items(0).toString } }
  • reactions には、発生したイベントに呼応する処理を登録しておきます。
  • case ListSelectionChanged では、リスト項目を選択したときに、それに呼応する処理を記述します。このとき、source を介して、イベントが発生したコンポーネントにアクセスできます。