Scala Swing ListView的删除/添加元素事件

时间:2011-08-21 16:55:32

标签: swing scala listview

参考这个,

How do I change the contents of a ListView in Scala?

我可以通过更改ListView来更改listData内容。但是,我无法ListView发布这些事件,ListElementsAddedListElementsAddedListChanged。从ListView源的外观来看,它只会向只读空模型添加一个侦听器。我该怎么做?

谢谢

1 个答案:

答案 0 :(得分:2)

后来,我设法找到了让ListView发布这些事件的方法。请参阅代码。

有权利吗?有一个更好的方法吗?请指教。

由于

**代码借用和修改**

object ListViewTest extends SimpleSwingApplication
{
  lazy val top = new MainFrame
  {
    title = "ListView Test"
    contents = new BoxPanel(Orientation.Vertical)
    {
      border = Swing.EmptyBorder(2, 2, 2, 2)

      val listModel = new DefaultListModel
      List("First", "Second", "Third", "Fourth", "Fifth").map(listModel.addElement(_))
      val myList = ListBuffer()
      val listView = new ListView[String](myList)
      {
        selection.intervalMode = ListView.IntervalMode.Single
        peer.setModel(listModel)

        //listData = myList

      }
      listView.peer.getModel.addListDataListener(new ListDataListener {
        def contentsChanged(e: ListDataEvent) { publish(ListChanged(listView)) }
        def intervalRemoved(e: ListDataEvent) { publish(ListElementsRemoved(listView, e.getIndex0 to e.getIndex1)) }
        def intervalAdded(e: ListDataEvent) { publish(ListElementsAdded(listView, e.getIndex0 to e.getIndex1)) }
      })

      contents += new ScrollPane(listView)

      val label = new Label("No selection")
      contents += label

      val b = new Button("Remove")
      contents += b

      listenTo(listView.selection, listView, b)
      reactions +=
        {
          case ListSelectionChanged(list, range, live) =>
            label.text = "Selection: " + range
          case e: ButtonClicked =>
            if (listView.listData.isEmpty)
            {
              b.enabled = false
            }
            else
            {
              listView.peer.getModel.asInstanceOf[DefaultListModel].remove(listView.selection.anchorIndex)
            }

          case ListElementsRemoved(source, range) =>
            println("Element at " + (range.start + 1) + " is removed.")
        }
    }
    pack
  }