简体   繁体   中英

ScalaFX type mismatch on event.getCode()

I'm getting this error in ScalaFx when trying to set an event handler for key presses:

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

I'm unsure as to why the actual type is coming out as a Java type, I suspect it might be in my imports but I cant find anything about it anywhere. Here's what I have so far:

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
  }


}

Update, I've found a solution. Whenever working with scalaFx make sure to

import scalaFx.Includes._

Its important to change the typing from Java types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM