如何发送消息给演员阿卡

时间:2018-07-31 11:46:42

标签: scala akka

我是Scala和akka的初学者,如果想按下keybutton,我想向MessageSender actor发送消息,我绘制了一个字段和2个对象,但是当我运行程序然后按向上箭头时,actor中的消息没有打印

//Boot
import akka.actor.{ActorSystem, Props}
import scalafx.Includes._
import scalafx.application
import scalafx.application.JFXApp
import scalafx.scene.Scene
import scalafx.scene.canvas.{Canvas, GraphicsContext}
import scalafx.scene.input.{KeyCode, KeyEvent}

object Boot extends JFXApp {



  val system = ActorSystem("MYsystem")
  val messageSender = system.actorOf(Props[MessageSender],"MessageSender")
  val wiDth = 500
  val heiDth = 500
  stage = new application.JFXApp.PrimaryStage {
    title = "Tanks"
    scene = new Scene(wiDth,heiDth) {
        val canvas = new Canvas(wiDth,heiDth)
        var g = canvas.graphicsContext2D
        val tank = new Objects(g)
        val thisTank = tank.drawTank(0,0)
        val thisBullet = tank.drawBullet(60,20)
        canvas.onKeyPressed = (e: KeyEvent) => {
            e.code match {
              case KeyCode.Up => messageSender ! MessageSender.Up

            }}
     content=canvas

    }
    }
  }

消息发件人

object MessageSender {

  case object Left
  case object Right
  case object Up
  case object Down
  case object StartGame
  case object MakeShoot

}

class MessageSender extends Actor with ActorLogging{
import  MessageSender._
  override def receive: Receive = {
    case Up => println("sent up")



  }

}

1 个答案:

答案 0 :(得分:0)

我认为您的canvas没有收到事件,这是一个问题。如果将onKeyPressed处理程序移到Scene级别,它将起作用。

这是因为您缺少以下内容:

canvas.setFocusTraversable(true)

这是我创建的一个简单示例:

class MsgActor extends Actor {
  def receive: Receive = {
    case keyCode: KeyCode =>
      println("incoming...\t" + keyCode.getName)
  }
}

object Boot extends JFXApp {

  implicit val system = ActorSystem("javafx")
  val msgActor = system.actorOf(Props(new MsgActor()))

  val canvas = new Canvas(500, 500)
  val gc = canvas.graphicsContext2D
  canvas.translateX = 0
  canvas.translateY = 0

  canvas.onKeyPressed = (e: KeyEvent) => e.getCode match {
    case code => msgActor ! code
  }

  // this is needed!
  canvas.setFocusTraversable(true)

  new application.JFXApp.PrimaryStage {
    title.value = "Tanks"
    width = 500
    height = 500
    scene = new Scene {
      fill = Color.AliceBlue
      content = canvas
    }
  }
}