ScalaFX Button => How to define an action?

I am trying to determine the onAction accion for a Button executed in scalafx , but I cannot get it to work.

package App.Desktop import javafx.event.EventHandler import scalafx.event.ActionEvent import scalafx.scene.control.Button class Window() { btn_YES.onAction = (event: ActionEvent) => new EventHandler[ActionEvent] { override def handle(event: ActionEvent) { /*Do something*/ } } } } 

I did this, but I get an error

 Error: type mismatch; found : scalafx.event.ActionEvent => javafx.event.EventHandler[scalafx.event.ActionEvent] required: javafx.event.EventHandler[javafx.event.ActionEvent] btn_YES.onAction = (event: ActionEvent) => new EventHandler[ActionEvent] 

I also tried using javafx.event.ActionEvent instead of scalafx , but it does not work either.

Any clue?

thanks

+5
source share
3 answers

I'm not a Scala programmer, but it looks like you are mixing two different forms here: a lambda expression and an explicit class.

Try

 package App.Desktop import javafx.event.EventHandler import javafx.event.ActionEvent import scalafx.scene.control.Button class Window() { btn_YES.onAction = new EventHandler[ActionEvent] { override def handle(event: ActionEvent) { /*Do something*/ } } } 

or

 package App.Desktop import javafx.event.EventHandler import javafx.event.ActionEvent import scalafx.scene.control.Button class Window() { btn_YES.onAction = (event: ActionEvent) => { /*Do something*/ } } 
+3
source

Fist, when working with ScalaFX, it is important to import scalafx.Includes._ . It brings many of the features of ScalaFX.

There are two recommended ways to add an onAction handler. The main (event:ActionEvent) => { ... ) is to use closure (event:ActionEvent) => { ... ) :

 import scalafx.Includes._ import scalafx.event.ActionEvent btn_YES.onAction = (event: ActionEvent) => { /*Do something*/ } 

If you do not need an event object. You can save some typing and use handle {...} :

 import scalafx.Includes._ btn_YES.onAction = handle { /*Do something*/ } 

In both cases, you need to import scalafx.Includes._

+2
source

You can use this for button action,

 btn_YES.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { //Do some action here } }); 
0
source

Source: https://habr.com/ru/post/1246940/


All Articles