I am trying to write an event handler for a dynamically created button in a FXML-defined form controller and it seems to work ok but as soon as I try accessing another element it fails.
For example this code works fine:
import java.util
import java.net.URL
import javafx.{scene => jfxs, fxml => jfxf}
import javafx.event.{EventHandler, ActionEvent}
import scalafx.Includes._
class MainFormFxmlController extends jfxf.Initializable{
@jfxf.FXML
private var anchorPane: jfxs.layout.AnchorPane = _
@jfxf.FXML
private var slider: jfxs.control.Slider = _
def initialize(url: URL, rb: util.ResourceBundle) {
// the slider variable becomes null at this point if I observe it in the button event handler below and is not null id I don't
slider.valueProperty.addListener{ (o: javafx.beans.value.ObservableValue[_ <: Number], oldVal: Number, newVal: Number) =>
// ...
}
//...
val button = new jfxs.control.Button("Button")
jfxs.layout.AnchorPane.setRightAnchor(button, 63.0)
jfxs.layout.AnchorPane.setTopAnchor(button, 14.0)
anchorPane.getChildren.add(button)
button.setOnAction(new EventHandler[ActionEvent]() {
@Override
def handle(event: ActionEvent) {
println("123") // trying to access the slider variable here makes the whole app fail on load
}
})
}
}
But it is enough to replace println("123")
with if(slider != null) println("123")
to make the application fail through throwing NullPointerException at the initialize
function beginning.
What I am trying to reach is to adjust the slider value on the button press (while creating this particular button dynamically having the rest of the form loaded from FXML) and I thought that my mistake is in using a wrong way to do that but I have found out that a mere null check made with the slider variable causes the fail, not necessarily its value adjustment.
This looks quite curious to me as if the slider variable would be null I'd get just this fact with the check and if it would be inaccessible the application would fail to get compiled but what I get is different.