event.getCode()上的ScalaFX类型不匹配

时间:2019-03-02 01:34:47

标签: scala scalafx

当尝试为按键设置事件处理程序时,我在ScalaFx中收到此错误:

Type mismatch, expected: scalafx.scene.input.KeyCode, actual: javafx.scene.input.KeyCode

我不确定为什么实际的类型会以Java类型出现,我怀疑它可能在我的导入文件中,但是我在任何地方都找不到。这是我到目前为止的内容:

import scalafx.application
import scalafx.application.JFXApp
import scalafx.scene._
import scalafx.scene.shape.{Circle, Rectangle}
import scalafx.scene.paint.Color._
import scalafx.scene.input.{KeyCode, KeyEvent}
import scalafx.event.{EventHandler, EventType}

object GUI extends JFXApp{

  var playerSpeed: Double = 10.0

  var sceneGraphics: Group = new Group{}

  val circle: Circle = new Circle{
    centerX = 100.0
    centerY = 50.0
    radius = 50.0
    fill = Green
  }
  sceneGraphics.children.add(circle)

  val rectangle: Rectangle = new Rectangle{
    width = 60
    height = 60
    translateX = 600
    translateY = 700
    fill = Blue
  }
  sceneGraphics.children.add(rectangle)

  def keyPressed(keyCode: KeyCode): Unit = {
    keyCode.getName match {
      case "W" => circle.translateY.value -= playerSpeed
      case "A" => circle.translateX.value -= playerSpeed
      case "S" => circle.translateY.value += playerSpeed
      case "D" => circle.translateX.value += playerSpeed
      case _ => println(keyCode.getName)
    }
  }

  stage = new application.JFXApp.PrimaryStage {

    title.value = "testing"
    //stage.setFullScreen(true)
    scene = new Scene(800, 800) {
      content = List(sceneGraphics)
    }

    EventHandler(KeyEvent.KeyPressed, (event: KeyEvent) => keyPressed(event.getCode)) <- error is here
  }


}

1 个答案:

答案 0 :(得分:2)

更新,我找到了解决方案。每当使用scalaFx时,请确保

import scalaFx.Includes._

从Java类型更改类型很重要