[英]how to send message to actor akka
I'm beginner in Scala and akka, and I want to send message to MessageSender actor if the keybutton was pressed, I draw a field and 2 objects, but when I run a program and then press up arrow, message in actor is not printing 我是Scala和akka的初学者,如果按下键按钮,我想向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
}
}
}
Message sender 讯息寄件者
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")
}
}
I think this is an issue with your canvas
not getting events. 我认为这是您的
canvas
没有事件的问题。 If you move the onKeyPressed
handler to the Scene
level it will work. 如果将
onKeyPressed
处理程序移动到“ Scene
级别,它将起作用。
This is because you are missing the following: 这是因为您缺少以下内容:
canvas.setFocusTraversable(true)
here is a quick example I created: 这是我创建的一个简单示例:
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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.