Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Swing reactions in an extended Panel

Well, simple question: I have a singleton object that extends scala.swing.Panel, and I want to have it react on a simple mouse click. But... well, it doesn't work. Since Scala's such a new language, finding infos to specific problems is not so easy. Maybe you can help:

import scala.swing._
import scala.swing.event._
import java.awt.{Graphics2D, Color}

object GamePanel extends Panel {
  val map: TileMap = new TileMap(10, 10)({
    (x, y) =>
      if (x == y) new Wood
      else if (x == 5) new Water
      else new Grass
  })

  reactions += {
    case MouseClicked(src, pt, mod, clicks, pops) => {
      selectedTile = (pt.x / map.tw, pt.y / map.th)
      println("Clicked")
      repaint
    }
  }

  var selectedTile = (0, 0)

  override def paint(g: Graphics2D) = {
    map.draw(g)
    g.setColor(Color.red)
    g.drawRect(selectedTile._1 - 1, selectedTile._2 - 1, 33, 33)
  }
}

Thanks for listening.

like image 678
Scán Avatar asked Nov 05 '10 22:11

Scán


1 Answers

Mouse events are not handled by default in Scala Swing for performance reasons. In your case you need to add a

listenTo(mouse.clicks)

to your object but there is also an event publisher mouse.moves you can listen to if you need to track the mouse move events.

like image 146
Moritz Avatar answered Nov 12 '22 00:11

Moritz