MVP in Scala-Swing

2019-02-18 01:10发布

问题:

Does anybody know some well-written sample projects showing how to achieve MVP architecture in Scala+Swing?

I found only this topics about MVP in Scala + Swing:

  • Improving MVP in Scala
  • Scala model-view-presenter, traits

And second extra question: how you think, it's right to expose GUI widgets from view to presenter not using public getters:

def getNextButton(): Reactor // this code in view will be accessed by presenter to setup clickHandler 

but using abstract fields in traits (as described in second link I provide - Scala model-view-presenter, traits):

回答1:

Unfortunately, Scala Swing abandons quite a bit of the underlying Java Swing MVC. To give some examples: ComboBox has no direct access to the model (unlike JComboBox), neither does ListView, Button, etc. Only Table has the model, but not Scala'fied, so untyped.

So if you want to use the existing Java models, you need to go into the peer fields of the Scala Swing widgets. If you want MVC with your own models, well, then you'll have to do the wiring by hand.


import scala.swing._
import Swing._

val m  = new javax.swing.DefaultButtonModel
val cb = new CheckBox    ("Check" ) { peer.setModel(m) }
val tb = new ToggleButton("Toggle") { peer.setModel(m) }
val f  = new Frame {
  contents = new FlowPanel(cb, tb)
  pack().centerOnScreen()
  open()
}

m addChangeListener ChangeListener { _ =>
  println(s"Selected? ${m.isSelected}")
}

m.setSelected(true)

This is a tiny library to create models in Scala.



回答2:

This is a small bit of example of controllers in Scala, but might not be exactly what you're looking for:

https://github.com/lrytz/pacman/tree/master/src/main/scala/epfl/pacman