【问题标题】:Why doesn't my JavaFX slider event fire?为什么我的 JavaFX 滑块事件没有触发?
【发布时间】:2017-01-14 16:30:13
【问题描述】:

我试图在移动滑块时显示滑块的值。

这是我迄今为止尝试过但不起作用的方法:

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

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

还有我的.fxml 代码:

<?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>

如果我应该发布更多信息,请告诉我。任何帮助将不胜感激!

【问题讨论】:

  • 这里有什么问题?
  • @azro 它只是不在控制台中显示消息。
  • 改为:System.out.println("这里"+slAcceleration.getValue());只是想知道它是否暂时进入方法

标签: java events javafx


【解决方案1】:

dragDone 事件是“拖放”系统的一部分。它在完全拖放处理期间调用(在应用程序中移动数据,或在应用程序之间移动数据),并且仅当您之前在某个节点上调用过 startDragAndDrop() 时才会发生。

这里你需要观察滑块的valueProperty()。没有为此生成事件,所以在控制器的initialize 方法中注册监听器:

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

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

请注意,您的 FXML 文件中也存在错误:您使用的是 id 而不是 fx:id。你需要解决这个问题,否则控制器中的@FXML-injected 字段将不会被初始化。

【讨论】:

  • 谢谢詹姆斯!我知道 id 和 fx:id 之间的差异,我刚刚发现了。
【解决方案2】:

因为那不是你需要的。属性onValueChange 可以解决问题,需要为处理程序提供ChangeListener&lt;Number&gt; 签名(Double 也可以):

<Slider onValueChange="#doStuff"/>

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-18
    • 2012-01-11
    • 1970-01-01
    • 2011-05-05
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多