changevalue listener spinner javafx

时间:2017-02-22 07:51:09

标签: javafx

您好我想在一个微调器中为每个键刷新一个Label。 我有以下代码:

<input ng-model="formData.dueDate" type="button" id="dueDate" name="dueDate" class="form-control" datepicker-options="dateOptions" datepicker-popup="MM-dd-yyyy" datepicker-append-to-body="true" is-open="true" min-mode="week" datepicker-mode="day"  show-button-bar="false" ng-click="data.isOpen = true" custom-class="classForWeek(date,mode)" />

好的,当我点击微调器的箭头时,这段代码很好,但是当我点击微调器的输入字段并且我写了一个数字时,

spinner.valueProperty().addListener((obs, oldValue, newValue) -> {
        if (!"".equals(newValue)) {
            System.out.println("spiinerrrr");
        } 
    });

未执行。

为什么?我没有找到组件微调器的更改值监听器,而对于文本字段,当我在文本字段中写入时,以下代码是好的:

System.out.println("spiinerrrr");

3 个答案:

答案 0 :(得分:2)

您可以将监听器添加到textProperty的{​​{1}}:

Spinner

否则,您必须在更新spinner.getEditor().textProperty().addListener((obs, oldValue, newValue) -> { if (!"".equals(newValue)) { System.out.println("spiinerrrr"); } }); 之前按Enter键。

如果您想在焦点丢失时更新valueProperty(无需按Enter键),请为valueProperty添加额外的听众:

focusedProperty

答案 1 :(得分:1)

正如其他人所说,由于valueProperty没有改变,代码不会被执行。

您必须按输入才能在编辑器中应用文本并更改valueProperty

来自doc of editableProperty

  

editable属性用于指定用户输入是否能够   输入Spinner编辑器。如果editable为true,则用户输入将为true   一旦用户输入并按下Enter键即可收到。在这   将输入传递给SpinnerValueFactory转换器   StringConverter.fromString(String)方法。来自的返回值   然后将此调用(类型T)发送给   SpinnerValueFactory.setValue(Object)方法。如果该值有效,则为   将保留为价值。如果它无效,则值为factory   需要做出相应的反应并退出这一变化。

如果您需要Spinner立即对其编辑器中文本的更改做出反应,您可以这样做:

Spinner<Integer> spinner = new Spinner<>(0, 500, 0);
spinner.setEditable(true);
spinner.getEditor().textProperty().addListener((obs, oldval, newval) -> {

    SpinnerValueFactory<Integer> valueFactory = spinner.getValueFactory();
    if (valueFactory != null) {
        StringConverter<Integer> converter = valueFactory.getConverter();
        if (converter != null) {
            try {
                Integer value = converter.fromString(newval);
                if (value != null)
                    valueFactory.setValue(value);
                else
                    valueFactory.setValue(0);
            } catch (NumberFormatException ex) {
                spinner.getEditor().setText(converter.toString(valueFactory.getValue()));
            }
        }
    }
});

注意:您的需求完全匹配使用绑定而不是侦听器:

label.textProperty().bind(spinner.valueProperty().asString());

答案 2 :(得分:0)

使用getEditor()方法访问微调器的TextField,然后添加侦听器:

Spinner<String> sp = new Spinner<>(FXCollections.observableArrayList("aaa", "bbb", "ccc"));
sp.setEditable(true);
sp.getEditor().textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
    System.out.println(newValue);
});

如果您需要知道,当用户输入新值时:

sp.getEditor().setOnAction(e -> {
    System.out.println(sp.getEditor().getText());
}); 
相关问题