Search code examples
scalafx

How do I use the scalafx KeyCodeCombination.match function?


Here is what I thought would work based on javafx examples I've seen, but I'm getting an error on the (ctlA.match(ke)) pointing to "match" and saying "identifier expected but 'match' found." Any links to scalafx examples that have complex KeyEvent processing would be appreciated.

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")
      }
    }
  }
}

Solution

  • This is a quirky issue. ScalaFX is obviously just a wrapper for the JavaFX API, and so it tries to faithfully follow that API as well as it can. In this case, there's a slight problem, because match is both the name of a function belonging to KeyCodeCombination and a Scala keyword - which is why compilation fails when it reaches this point: the Scala compiler thinks this is the match keyword, and can't make sense of it.

    Fortunately, there is a simple solution: just enclose match within backticks, so that your code becomes:

    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")
          }
        }
      }
    }
    

    Your program now runs just fine!