如何使用 scalafx KeyCodeCombination.match 函数?

How do I use the scalafx KeyCodeCombination.match function?

根据我见过的 javafx 示例,这是我认为可行的方法,但我在指向 "match" 的 (ctlA.match(ke)) 上收到错误并说 "identifier expected but 'match' found." 任何指向具有复杂 KeyEvent 处理的 scalafx 示例的链接都将不胜感激。

import scalafx.Includes._
import scalafx.application.JFXApp
import scalafx.application.JFXApp.PrimaryStage
import scalafx.scene.input.{KeyCode, KeyCombination, KeyCodeCombination, KeyEvent}
import scalafx.scene.Scene
import scalafx.stage.Stage

object Main extends JFXApp {
  val ctlA = new KeyCodeCombination(KeyCode.A, KeyCombination.ControlDown)
  stage = new PrimaryStage {
    scene = new Scene {
      onKeyPressed = { ke =>
        if (ctlA.match(ke))
          println("Matches ^A")
        else
          println("No match")
      }
    }
  }
}

这是一个古怪的问题。 ScalaFX 显然只是 JavaFX API 的包装器,因此它也试图忠实地遵循 API尽其所能。在这种情况下,有一个小问题,因为 match 是属于 KeyCodeCombination 的函数的名称和 Scala 关键字 - 这就是编译在到达这一点时失败的原因:Scala 编译器认为这是 match 关键字,并且无法理解它。

幸运的是,有一个简单的解决方案:只需将 match 括在反引号中,这样您的代码就变成了:

import scalafx.Includes._
import scalafx.application.JFXApp
import scalafx.application.JFXApp.PrimaryStage
import scalafx.scene.input.{KeyCode, KeyCombination, KeyCodeCombination, KeyEvent}
import scalafx.scene.Scene
import scalafx.stage.Stage

object Main extends JFXApp {
  val ctlA = new KeyCodeCombination(KeyCode.A, KeyCombination.ControlDown)
  stage = new PrimaryStage {
    scene = new Scene {
      onKeyPressed = { ke =>
        if (ctlA.`match`(ke))
          println("Matches ^A")
        else
          println("No match")
      }
    }
  }
}

您的程序现在运行得很好!