digicyc
digicyc

Reputation: 406

Scala Swing Popup menu on ListView

What would be the best way of adding a mouseListener to a Scala Swing ListView that what ever item in the list is clicked on it'll create a PopupMenu with options pertaining to that specific item that is clicked on?

Am I stuck with doing this with Java style code for now or has Scala Swing evolved a bit more since 2.8.1

A bit of what I got currently and maybe I'm listening to the wrong thing and am over looking the ScalaDocs on the ListView.

lazy val ui = new FlowPanel {
    val listView = ListView(items) {
        renderer = Renderer(_.name)
        listenTo(this.mouse.clicks)
        reactions += {
            case e: MouseClicked => 
                // How do I determine what item was clicked?
        }
    }
}

Upvotes: 4

Views: 1330

Answers (2)

Coffee_Table
Coffee_Table

Reputation: 284

This is unacceptably late, but I feel compelled to offer the "java-style" solution for anyone who might be interested (leaving aside the specific details of my implementation, the essence is in the 'reactions'):

 val listView = new ListView[Int] {
    selection.intervalMode = ListView.IntervalMode.Single
    listData = (1 to 20).toList
    listenTo(mouse.clicks)
    reactions += {
      case m : MouseClicked if m.clicks == 2 =>
        doSomethingWith( listData(selection.anchorIndex) )
        //where doSomethingWith is your desired result of this event
    }
 }

Assuming single interval mode, the key to getting the list item that was just double-clicked is in simply using anchorIndex.

Upvotes: 0

Luigi Plinge
Luigi Plinge

Reputation: 51109

  lazy val ui = new FlowPanel { 
    val listView = new ListView( Seq("spam", "eggs", "ham") )
    listenTo(listView.selection)
    reactions += {
      case SelectionChanged(`listView`) => println(listView.selection.items(0))
    }
    contents += listView
  }

This should produce output such as

spam
spam
eggs
eggs
ham
ham

as you click on the various items. I've never done this before but I had a look at the UIDemo example which can be found in the scala.swing.test package. To read the source, if you have IntelliJ, it's as simple as clicking on the relevant object in the scala-swing.jar in External Libraries in the Projects pane.

As for PopupMenu, I don't know - it doesn't look like that one has a scala-swing wrapper in 2.9.1, but I found one on GitHub here. Or you could just use the normal Swing version.

Upvotes: 1

Related Questions