user4702132
user4702132

Reputation:

Why doesn't my JavaFX slider event fire?

I'm trying to display the value of my slider when I am moving it around.

This is what I've tried so far but doesn't work:

public class ControlsController extends BaseController{
    @FXML
    private Slider slAcceleration;

    @FXML
    public void slAccelerationEventHandler(DragEvent event){
        System.out.println(slAcceleration.getValue());
    }
}

And my .fxml code:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.layout.Pane?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="250.0" prefWidth="300.0" style="-fx-background-color: bdc3ff;" xmlns="http://javafx.com/javafx/8.0.102" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.ControlsController">
   <children>
      <Label id="lbAcceleration" layoutX="14.0" layoutY="125.0" text="Versnelling simulatie x60" />
      <Slider id="slAcceleration" blockIncrement="1.0" layoutX="14.0" layoutY="151.0" max="600.0" min="1.0" onDragDone="#slAccelerationEventHandler" prefHeight="14.0" prefWidth="280.0" value="60.0" />
   </children>
</Pane>

Let me know if I should post more information. Any help would be greatly appriciated!

Upvotes: 0

Views: 1261

Answers (2)

tevemadar
tevemadar

Reputation: 13195

Because that's not the one you need. Property onValueChange does the trick, needing a ChangeListener<Number> signature for the handler (Double works too):

<Slider onValueChange="#doStuff"/>

@FXML
private void doStuff(ObservableValue<Number> ovn, Number before, Number after) {
    System.out.println(before+" "+after);
}

Upvotes: 0

James_D
James_D

Reputation: 209418

The dragDone event is part of the "drag and drop" system. It is called during full drag and drop processing (moving data around in your application, or between applications) and only happens if you have previously called startDragAndDrop() on some node.

What you need here is to observe the slider's valueProperty(). There is no event generated for that, so register the listener in the controller's initialize method:

public class ControlsController extends BaseController{
    @FXML
    private Slider slAcceleration;

    public void initialize() {
        slAcceleration.valueProperty().addListener((obs, oldValue, newValue) -> {
            System.out.println(newValue.doubleValue());
        });
    }
}

Note you also have errors in your FXML file: you are using id instead of fx:id. You need to fix this, otherwise the @FXML-injected fields in the controller will not be initialized.

Upvotes: 1

Related Questions